Using 'const' in class's functions

48,545

Solution 1

A const method can be called on a const object:

class CL2
{
public:
    void const_method() const;
    void method();

private:
    int x;
};


const CL2 co;
CL2 o;

co.const_method();  // legal
co.method();        // illegal, can't call regular method on const object
o.const_method();   // legal, can call const method on a regulard object
o.method();         // legal

Furthermore, it also tells the compiler that the const method should not be changing the state of the object and will catch those problems:

void CL2::const_method() const
{
    x = 3;   // illegal, can't modify a member in a const object
}

There is an exception to the above rule by using the mutable modifier, but you should first get good at const correctness before you venture into that territory.

Solution 2

Others have answered the technical side of your question about const member functions, but there is a bigger picture here -- and that is the idea of const correctness.

Long story short, const correctness is about clarifying and enforcing the semantics of your code. Take a simple example. Look at this function declaration:

bool DoTheThing(char* message);

Suppose someone else wrote this function and you need to call it. Do you know what DoTheThing() does to your char buffer? Maybe it just logs the message to a file, or maybe it changes the string. You can't tell what the semantics of the call are by just looking at the function declaration. If the function doesn't modify the string, then the declaration is const incorrect.

There's practical value to making your functions const correct, too. Namely, depending on the context of the call, you might not be able to call const-incorrect functions without some trickery. For example, assume that you know that DoTheThing() doesn't modify the contents of the string passed to it, and you have this code:

void MyFunction()
{
  std::string msg = "Hello, const correctness";
  DoTheThing(msg.c_str());
}

The above code won't compile because msg.c_str() returns a const char*. In order to get this code to compile, you would have to do something like this:

void MyFunction()
{
  std::string msg = "Hello, const correctness";
  DoTheThing(msg.begin());
}

...or even worse:

void MyFunction()
{
  std::string msg = "Hello, const correctness";
  DoTheThing(const_cast<char*>(msg.c_str()));
}

neither of which, arguably, are 'better' than the original code. But because DoTheThing() was written in a const-incorrect way, you have to bend your code around it.

Solution 3

const, when attached to a non-static class method, tells the compiler that your function doesn't modify the internal state of the object.

This is useful in two ways:

  • If you do write code that changes internal state in your const method, the compiler catches the error, moving a programming error from run-time to compile-time.
  • If client code calls a non-const method on a constant pointer, the compiler catches the error, ensuring the "chain of not changing things" is maintained.

Typically you want to declare all non-mutating non-static class methods as const. This allows calling code to use the const qualifier on pointers, and it helps catch mistakes.

Typical C++: you can declare a class member variable "mutable" and then change it even from a const method.

Solution 4

The meaning is that you guarantee to clients calling a const function member that the state of the object will not change. So when you say a member function is const it means that you do not change any of the objects member variables during the function call.

Solution 5

If this is true, then should it be used everywhere, because i don't want ANY of the member variables to be altered or changed in any way?

Well, no. Sometimes you do want instance methods to modify members. For example, any set method will obviously need to set variables, so it's not the case that you should put const everywhere. But if your object's state is totally immutable, first consider whether it might not be better to have no instances at all (i.e., a static class), and if that's not the case, then make everything const.

Share:
48,545
ggg
Author by

ggg

Updated on January 29, 2020

Comments

  • ggg
    ggg over 4 years

    I've seen a lot of uses of the const keyword put after functions in classes, so i wanted to know what was it about. I read up smth at here: http://duramecho.com/ComputerInformation/WhyHowCppConst.html .

    It says that const is used because the function "can attempt to alter any member variables in the object" . If this is true, then should it be used everywhere, because i don't want ANY of the member variables to be altered or changed in any way.

    class Class2
    { void Method1() const;
      int MemberVariable1;} 
    

    So, what is the real definition and use of const ?