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.
/*
* C++ Program to illustrate physical constness
*/
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class A {
private:
int i, j;
public:
A(int ii = 0, int jj = 0) : i(ii), j(jj) {}
void changeData(int ii, int jj ) {
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;
};
/*
* Can't change A::i or A::j
void A::makeSomeChanges() const {
i = i + 10;
j = j + 10;
}
*/
int main()
{
A a(10, 20);
cout << "A a(10, 20) : " << a.getResponse();
a.changeData(30, 40);
cout << "A::changeData(30, 40) : " << a.getResponse();
// a.makeSomeChanges();
cout << "A::makeSomeChanges() : " << a.getResponse();
}
$ 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.
Next Steps:
- Get Free Certificate of Merit in C++ Programming
- Participate in C++ Programming Certification Contest
- Become a Top Ranker in C++ Programming
- Take C++ Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Buy Programming Books
- Apply for Information Technology Internship
- Practice Programming MCQs
- Buy Computer Science Books
- Practice Computer Science MCQs