Search code examples
c++functionclassconstantsfunction-qualifier

Why use a const member function?


i'm trying to understand class getters and setters functions...

My question is: If i design a function that just only get a state from its class (a "getter" function), why mark it as "const member function"? I mean, why use a const member function if my function is designed to not change any proprieties of its class? i don't understand please :(

for example:

int GetValue() {return a_private_variable;}

and

int GetValue() const {return a_private_variable;}

what is the real difference?


Solution

  • When you declare a member function as const, like in

    int GetValue() const;
    

    then you tell the compiler that it will not modify anything in the object.

    That also means you can call the member function on constant object. If you don't have the const modifier then you can't call it on an object that has been defined as const. You can still call const member functions on non-constant objects.

    Also note that the const modifier is part of the member function signature, which means you can overload it with a non-const function. That is you can have

    int GetValue() const;
    int GetValue();
    

    in the same class.