Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the const operator mean when used with a method in C++?

Tags:

c++

Given a declaration like this:

class A {
public:
    void Foo() const;
};

What does it mean?

Google turns up this:

Member functions should be declared with the const keyword after them if they can operate on a const (this) object. If the function is not declared const, in can not be applied to a const object, and the compiler will give an error message.

But I find that somewhat confusing; can anyone out there put it in better terms?

Thanks.

like image 241
Bernard Avatar asked Sep 08 '08 02:09

Bernard


1 Answers

Consider a variation of your class A.

class A {
public:
    void Foo() const;
    void Moo();

private:
    int m_nState; // Could add mutable keyword if desired
    int GetState() const   { return m_nState; }
    void SetState(int val) { m_nState = val; }
};

const A *A1 = new A();
A *A2 = new A();

A1->Foo(); // OK
A2->Foo(); // OK

A1->Moo(); // Error - Not allowed to call non-const function on const object instance
A2->Moo(); // OK

The const keyword on a function declaration indicates to the compiler that the function is contractually obligated not to modify the state of A. Thus you are unable to call non-const functions within A::Foo nor change the value of member variables.

To illustrate, Foo() may not invoke A::SetState as it is declared non-const, A::GetState however is ok because it is explicitly declared const. The member m_nState may not be changed either unless declared with the keyword mutable.

One example of this usage of const is for 'getter' functions to obtain the value of member variables.

@1800 Information: I forgot about mutable!

The mutable keyword instructs the compiler to accept modifications to the member variable which would otherwise cause a compiler error. It is used when the function needs to modify state but the object is considered logically consistent (constant) regardless of the modification.

like image 183
Henk Avatar answered Oct 25 '22 14:10

Henk