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

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.