Using a method of a const object

I had a case similar to the following code. In this case I have a const object and I want to call a member function of it, in the case get_x.

#include <iostream>

class C {

    int x;

public:

    C(int _x) : x(_x) {}

    int get_x() {
        return x;
    }
};

int main (){
    const C c(10);
    int x = c.get_x();
    std::cout << x << std::endl;
}

This code does not compile though. I get the following error:

error: passing ‘const C’ as ‘this’ argument of ‘int C::get_x()’ discards qualifiers

Even though I don’t modify c, I think it’s hard to the compiler to tell whether the code inside get_x will modify x. It could call complicated recursive functions, for example. To avoid this problem, we must force the function not to modify the object x. To this end we add a const right after the parameters:

int get_x() const {
    return x;
}

All member of the object are seen as const now. It solves the problem for the compiler because it only need to check if any member is modified locally inside the function and if all members are passed either by value or by const reference. That is, the compiler doesn’t need to follow any execution path.

The following example illustrates this property. The compiler will raise an error because x is passed to no_const as a non-const reference, even though it’s not modified.

#include <iostream>

class C {

    int x;

public:

    C(int _x) : x(_x) {      
    }

    void no_const(int &x){
        int y = 2;
    }

    int get_x() const {
        no_const(x);
        return x;
    }

};

int main (){
    const C c(10);
    int x = c.get_x();
    std::cout << x << std::endl;
}
About these ads

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s