2

Possible Duplicate:
Invoking a nonconst method on a member from a const method

Constant member functions are able to call non constant member functions via pointer member variables in C++, is it as expected? Below give code snippet is compiling successfully

#include <iostream>

class S {
public:
    void hi() {
        std::cout << "Hi" << std::endl;
    }
};

class T {
public:
    T()
    : s(new S())
    {}

    ~T()
    {
        delete s;
    }

    void hi() const {
        s->hi();
    }

private:
    S  * s;
};

int main(int argc, char ** argv) {
    T t;
    t.hi();
    return 0;
}
0

2 Answers 2

5

The behavior is correct.

That's because the pointer is const - S * s;, not the object.

For example, the following would fail:

void hi() const {
    s->hi();     //OK
    s = NULL;    //not OK
}

Remember, you can't modify s (which is a pointer), but you can modify *s, which is the actual object.

2
  • we have not declared S *const s inside the class .then how it can be a constant pointer ?
    – Viku
    Commented Dec 28, 2012 at 12:01
  • @Viku: In the same fashion that, given struct X {int i;}; const X *x;, x->i has type const int. The point of this question is that t.s has type S *const, not const S*. Commented Feb 25, 2023 at 8:11
2

The type of s in the const member function is S * const, not S const*, which means the pointer itself is constant, not the object the pointer is pointing to. So the object which is non-const is used to invoke non-const function, which is Standard conformant behavior.

S const * s1 = initialization1; //same as : const S *s1  = initialization1;
S * const s2 = initialization2;

s1->hi();     //error: the object is const
s1 = nullptr; //okay : the pointer is non-const

s2->hi();     //okay: the object is non-const
s2 = nullptr; //error: the pointer is const

Not the answer you're looking for? Browse other questions tagged or ask your own question.