Constant Member Functions
Member functions in a class can be declared as constant if that member function has no necessity of modifying any data members. A member function can be declared as constant as follows:
1 2 3 4 5 6 |
return–type function–name(params–list) const { //body of function } |
Following program demonstrates the use of constant member functions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
#include<iostream> using namespace std; class Circle { private: int r; public: void area() const; void peri() const; void set_radius(int); }; void Circle::area() const { //r = 20; cout << "Area of circle is: " << (3.1415 * r * r) << endl; } void Circle::peri() const { //r = 20; cout << "Perimeter of circle is: " << (2 * 3.1415 * r) << endl; } void Circle::set_radius(int radius) { r = radius; } int main() { Circle c; c.set_radius(10); c.area(); c.peri(); return 0; } |
Output for the above program is as follows:
1 2 3 4 |
Area of circle is: 314.15 Perimeter of circle is: 62.83 |
In the above program there is no need for area() and peri() functions to modify the data member r. So, they are declared as constant member functions.
Constant Parameters
To prevent functions from performing unintended operations on data members of an object, we can declare the object arguments as constant arguments as follows:
const ClassName object-name
Following program demonstrates the use of constant parameters:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
#include<iostream> using namespace std; class Circle { private: int r; public: void area() const; void peri() const; void set_radius(int); void get_radius(const Circle); }; void Circle::area() const { //r = 20; cout << "Area of circle is: " << (3.1415 * r * r) << endl; } void Circle::peri() const { //r = 20; cout << "Perimeter of circle is: " << (2 * 3.1415 * r) << endl; } void Circle::set_radius(int radius) { r = radius; } void Circle::get_radius(const Circle c) { //c.r = 30; cout << "Radius of circle is: " << r << endl; } int main() { Circle c; c.set_radius(10); c.get_radius(c); c.area(); c.peri(); return 0; } |
Output of the above program is as follows:
1 2 3 4 5 |
Radius of circle is: 10 Area of circle is: 314.15 Perimeter of circle is: 62.83 |
In the above program inside the get_radius() function, Circle object has been declared as constant. So performing c.r = 30 is invalid as modifying constant values is illegal.
Take your time to comment on this article.