C++

What are constant member functions and constant parameters in C++2 min read

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 operation on data member of an object, we can declare the object argument 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 value is illegal.

Take your time to comment on this article.

Leave a Comment