Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "const" mean (in context) at the end of a function definition? [duplicate]

Tags:

c++

Possible Duplicate:
What is the meaning of a const at end of a member function?

If my class definition is as follows:

type CLASS::FUNCTION(int, const char*) const 

What does the last const after the closing bracket mean, and how do I apply it to the function:

type CLASS::FUNCTION(int var1, const char* var2) {  } 
like image 435
Matt Dunbar Avatar asked Mar 04 '11 23:03

Matt Dunbar


People also ask

What does it mean for a function to be const?

The const member functions are the functions which are declared as constant in the program. The object called by these functions cannot be modified. It is recommended to use const keyword so that accidental changes to object are avoided. A const member function can be called by any type of object.

How do you declare a const object in C++?

A const object can be created by prefixing the const keyword to the object declaration. Any attempt to change the data member of const objects results in a compile-time error. When a function is declared as const, it can be called on any type of object, const object as well as non-const objects.

Does it matter where you put const?

The rule is: const applies to the thing left of it. If there is nothing on the left then it applies to the thing right of it.

What is a const class?

Class constants can be useful if you need to define some constant data within a class. A class constant is declared inside a class with the const keyword.


2 Answers

It means that this function does not modify the observable state of an object.

In compiler terms, it means that you cannot call a function on a const object (or const reference or const pointer) unless that function is also declared to be const. Also, methods which are declared const are not allowed to call methods which are not.

Update: as Aasmund totally correctly adds, const methods are allowed to change the value of members declared to be mutable.

For example, it might make sense to have a read-only operation (e.g. int CalculateSomeValue() const) which caches its results because it's expensive to call. In this case, you need to have a mutable member to write the cached results to.

I apologize for the omission, I was trying to be fast and to the point. :)

like image 54
Jon Avatar answered Oct 02 '22 05:10

Jon


const at the end of the function means it isn't going to modify the state of the object it is called up on ( i.e., this ).

type CLASS::FUNCTION(int, const char*) const ; // Method Signature  type CLASS::FUNCTION(int var1, const char* var2) const {  } 

You need to mention the keyword const at the end of the method definition too. Also note that only member functions can have this non-modifier keyword const at their end.

like image 41
Mahesh Avatar answered Oct 02 '22 07:10

Mahesh