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;
}
Community
  • 1
  • 1
Ranjith
  • 53
  • 1
  • 7

2 Answers2

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.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • we have not declared S *const s inside the class .then how it can be a constant pointer ? – Viku Dec 28 '12 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*`. – Davis Herring Feb 25 '23 at 08: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
Nawaz
  • 353,942
  • 115
  • 666
  • 851