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

This section contains the C++ find output programs with their explanations on const Keyword (set 2).
Submitted by Nidhi, on June 04, 2020

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;
}

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.

Program 2:

#include <iostream>
using namespace std;

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

    *ptr = 20;

    cout << X;

    return 0;
}

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.





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.