What is a const object and function in C++? Why do we need to declare an object and function as const?

Const Object in C++

C++ is Object Oriented Programming language and we often write code using classes and objects but sometimes we intend not to change the object’s attribute’s value in any situation.

In that case, we declare the object as constant using const keyword in C++.

By declaring the object as const, once its attribute’s value is initialized it cannot be changed further. If any attempt is made to change any of the attribute’s value of the const object, the compiler will throw an error.

Let’s see an example of a const object in C++.


In the above example, we have explicitly changed the value of breed of dog object.

We do not want the object to get modified once it has been initialized with values, not even by mistake.

To solve the above ambiguity we could modify the access specifier of attributes to private or declare them constant inside the class. But doing so will apply the same restriction to all instances of the Dog class.

Hence to only restrict few objects from modification we use const objects because const object attributes cannot be changed once initialized.

After changing the declaration.

If we now try to change breed value, the compiler will throw an error.

Const Function in C++

A function is declared const by using const keyword as postfix in the function declaration.

It is used mostly for the const objects because if we try to call a member function (non-const) on a const object, the compiler will throw an error because it assumes that the member function could potentially modify the current object data, even when the member function does not intend to do so.

If we run the above code we get the following error.

error: ‘this’ argument to member
function ‘getName’ has type ‘const Dog’, but
function is not marked const

To solve the ambiguity we make the member function const.

Output : Scobby

Now everything works fine. It is important to not to modify the current object data in the const function otherwise the compiler will raise an error.

I hope you understood the concept of const function and objects in C++. If you have any doubts or suggestion then comment below.

Leave a Reply