C++ Program to Illustrate Const Keyword with Member Functions

This C++ program illustrates the const keyword with member functions. The functions with a const keyword specified before the function definition prevents the calling of non-const data members for a given instance of the class. It also prevents t

Here is the source code of the C++ program which illustrates the const keyword with member functions. 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 physical constness
  3.  */
  4. #include <iostream>
  5. #include <string>
  6. #include <sstream>
  7. using namespace std;
  8.  
  9. class A {
  10.     private:
  11.         int i, j;
  12.     public:    
  13.         A(int ii = 0, int jj = 0) : i(ii), j(jj) {}
  14.         void changeData(int ii, int jj ) {
  15.             i = ii;
  16.             j = jj; 
  17.         }
  18.         string getResponse() const {
  19.             string s;
  20.             stringstream ss;
  21.             ss << "i = " << i << ", j = " << j << "\n";
  22.             s = ss.str();
  23.             return s;
  24.         }
  25.         void makeSomeChanges() const;
  26.  
  27. };
  28.  
  29. /*
  30.  * Can't change A::i or A::j
  31. void A::makeSomeChanges() const {
  32.     i = i + 10;
  33.     j = j + 10;
  34. }
  35. */
  36.  
  37. int main()
  38. {
  39.     A a(10, 20);
  40.  
  41.     cout << "A a(10, 20)           : " << a.getResponse();
  42.     a.changeData(30, 40);
  43.     cout << "A::changeData(30, 40) : " << a.getResponse();
  44.     // a.makeSomeChanges();
  45.     cout << "A::makeSomeChanges()  : " << a.getResponse();
  46. }

$ a.out
A a(10, 20)           : i = 10, j = 20
A::changeData(30, 40) : i = 30, j = 40
A::makeSomeChanges()  : i = 30, j = 40

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.