What are constant parameter member functions in C++2 min read

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:

Following program demonstrates the use of constant member functions:

Output for the above program is as follows:

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:

Output of the above program is as follows:

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.

Leave a Comment