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

29.8k Views Asked by At

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) {

}
5

There are 5 best solutions below

2
On BEST ANSWER

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. :)

0
On

Means that this function will not modify any member variables, or call any non-const member functions.

If you have a const reference/pointer to an instance of the class, you will only be able to call functions that are marked const like this.

0
On

This means the method is const, and means the method will not modify any members, it can thus be used in a setting where the object is const.

class Foo
{
   public:
      void foo(int a) { m = a; }
      int bar() const { return m; }
   private:
      int m;
};

int baz(const Foo* ptr)
{
   ptr->foo(10); // Not legal, Foo::foo is not const, and ptr is pointer to const.
   return ptr->bar(); // Legal, Foo::bar is a const method, and does not modify anything.
}
0
On

A member function that inspects, i.e. reads, rather than modifies or writes to an object. The following link is helpful to me.

http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.10

0
On

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.