Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't understand the const method declaration

Tags:

c++

Too much C# and too little C++ makes my mind dizzy... Could anyone remind me what this c++ declaration means? Specifically, the ending "const". Many thanks.

protected:
     virtual ostream & print(ostream & os) const
like image 886
smwikipedia Avatar asked Feb 16 '10 08:02

smwikipedia


People also ask

How do you declare a const method?

A constant member function can't modify any non-static data members or call any member functions that aren't constant. To declare a constant member function, place the const keyword after the closing parenthesis of the argument list. The const keyword is required in both the declaration and the definition.

What is the effect of declaring a method to be const?

A function becomes const when the const keyword is used in the function's declaration. The idea of const functions is not to allow them to modify the object on which they are called. It is recommended the practice to make as many functions const as possible so that accidental changes to objects are avoided.

What is const declaration?

A constant holds a value that does not change. A constant declaration specifies the name, data type, and value of the constant and allocates storage for it. The declaration can also impose the NOT NULL constraint.

What is meant with const at end of function declaration?

A "const function", denoted with the keyword const after a function declaration, makes it a compiler error for this class function to change a member variable of the class. However, reading of a class variables is okay inside of the function, but writing inside of this function will generate a compiler error.


1 Answers

A const method will simply receive a const this pointer.

In this case the this pointer will be of the const ThisClass* const type instead of the usual ThisClass* const type.

This means that member variables cannot be modified from inside a const method. Not even non-const methods can be called from such a method. However a member variable may be declared as mutable, in which case this restriction will not apply to it.

Therefore when you have a const object, the only methods that the compiler will let you call are those marked safe by the const keyword.

like image 81
Daniel Vassallo Avatar answered Oct 09 '22 06:10

Daniel Vassallo