C++ Program to Illustrate Logical Constness

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.

  1. /*
  2.  * C++ Program to illustrate logical constness
  3.  */
  4. #include <iostream>
  5. #include <string>
  6. #include <sstream>
  7. using namespace std;
  8.  
  9. class A {
  10.     private:
  11.         const int i, j;
  12.     public:
  13.         A(int ii = 0, int jj = 0) : i(ii), j(jj) {}
  14.         string getResponse() const {
  15.             string s;
  16.             stringstream ss;
  17.             ss << "i = " << i << ", j = " << j << "\n";
  18.             s = ss.str();
  19.             return s;
  20.         }
  21.         void makeSomeChanges() const;	
  22. };
  23.  
  24. void A::makeSomeChanges() const
  25. {
  26.     const int& iref = i;
  27.     const_cast<int&>(iref) = i + 10;
  28.     const int& jref = j;
  29.     const_cast<int&>(jref) = j + 10;
  30. }
  31.  
  32. int main()
  33. {
  34.     A a(10, 20);
  35.  
  36.     cout << "A::A(10, 20)          : " << a.getResponse();
  37.     a.makeSomeChanges();
  38.     cout << "A::makeSomeChanges()  : " << a.getResponse();	
  39. }

$ 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]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.