This C++ program illustrates the illustrates logical const-ness. Logical constness comes from declaring a reference or pointer const, and is enforced by the compiler. The value referenced by the reference or pointer variable can be changed only by casting away the constness of the reference variable by using const_cast.
Here is the source code of the C++ program which illustrates the illustrates logical const-ness. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C++ Program to illustrate logical constness
*/
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class A {
private:
const int i, j;
public:
A(int ii = 0, int jj = 0) : i(ii), j(jj) {}
string getResponse() const {
string s;
stringstream ss;
ss << "i = " << i << ", j = " << j << "\n";
s = ss.str();
return s;
}
void makeSomeChanges() const;
};
void A::makeSomeChanges() const
{
const int& iref = i;
const_cast<int&>(iref) = i + 10;
const int& jref = j;
const_cast<int&>(jref) = j + 10;
}
int main()
{
A a(10, 20);
cout << "A::A(10, 20) : " << a.getResponse();
a.makeSomeChanges();
cout << "A::makeSomeChanges() : " << a.getResponse();
}
$ a.out A::A(10, 20) : i = 10, j = 20 A::makeSomeChanges() : i = 20, j = 30
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
If you find any mistake above, kindly email to [email protected]Related Posts:
- Check C++ Books
- Practice Programming MCQs
- Practice Computer Science MCQs
- Apply for Computer Science Internship
- Check Computer Science Books