Q:

C++ const Keyword | Find output programs | Set 2

belongs to collection: C++ find output programs

0

This section contains the C++ find output programs with their explanations on const Keyword (set 2).

Program 1:

#include <iostream>
using namespace std;

class Sample {
    int A;
    int B;

public:
    Sample(): A(10), B(20)
    {
    }

    void set(int a, int b) const
    {
        A = a;
        B = b;
    }
    void print()
    {
        cout << A << " " << B;
    }
};

int main()
{
    Sample S;

    S.print();

    return 0;
}

Program 2:

#include <iostream>
using namespace std;

int main()
{
    int X = 10;
    int* const ptr = &X;

    *ptr = 20;

    cout << X;

    return 0;
}

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer Program 1:

Output:

main.cpp: In member function 'void Sample::set(int, int) const':
main.cpp:15:13: error: assignment of member 'Sample::A' in read-only object
         A = a;
             ^
main.cpp:16:13: error: assignment of member 'Sample::B' in read-only object
         B = b;
             ^

Explanation:

The above code will generate an error because in the above program we defined a const member function. And we are trying to modify the value of data members in const member function set().

In C++, we cannot modify values in a const member function.

Answer Program 2:

Output:

20

Explanation:

Here we declared a variable X with initial value 10. We need to understand the below statement carefully.

in the above statement, ptr is constant, we cannot move the pointer in the backward or forward direction for address displacement, but *ptr it means we can modify the value because * is a value of the operation. And ptr contains the address of X, then we can modify the value of X.

Then the final value is 20.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ find output programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C++ Manipulators | Find output programs | Set 1... >>
<< C++ const Keyword | Find output programs | Set 1...