Const member

If you pass an object as const, you can only call const methods. To make a method const, you have to explicit that you’re not changing any member of the class when calling this method by adding the keyword const after the parameters list. See example below.

class C {
    int v_;
public:
    C() : v_(123) {}

    int const_get_v() const {
	return C::v_;
    }
    int non_const_get_v() {
	return C::v_;
    }
};

int func(const C &c){
    c.const_get_v(); // OK
    c.non_const_get_v(); // Error: discards qualifiers
}
int main (){
    C c;
    func(c);
}
Advertisements

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