Question

#include <iostream>

class Hello {
public:
    void Test() {
        std::cout << "Testing" << std::endl;
    }
};

class Hi {
public:
    Hi()
    :hello(new Hello())
    {}

    ~Hi()
    {
        delete hello;
    }

    void Testing() const {
        hello->Test();
    }

private:
    Hello  * hello;
};

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

As i know a non-constant member function cant be called inside a constant member function but how the above code has been compiled successfully and giving the expected result .

Was it helpful?

Solution

Inside Hi::Testing, the hi object "is const". Which means the pointer hello can't be modified inside that method. (It is as if hello had been defined as Hello * const hello; for the duration of that method.)

But this doesn't mean that hello is transformed into a pointer-to-const (which would look like Hello const * const hello;). The object pointed to by hello isn't const, so you can invoke its non-const methods without restriction.

OTHER TIPS

You can reduce the problem to the following situation:

Foo x;

Foo       *       p1 = &x;
Foo       * const p2 = &x;

p1->non_const_method();     // OK
p2->non_const_method();     // OK

Foo const *       q1 = &x;
Foo const * const q2 = &x;

q1->non_const_method();     // error
q2->non_const_method();     // error

Whether or not your Hi-object is constant only affects the top-level const modifier in this analogy (i.e. whether Hi::hello is Hello * or Hello * const). However, the first const modifier is an integral part of the pointer type itself (and unaffected by the constness of your object).

If you have a pointer to a const object, that will restrict you to calling const member functions in the target object.

A const pointer to a (normal) object just means you can't modify the pointer itself. Since it's still a pointer to a normal object, you can use any member function, not just const member functions. If the target object has const and normal overloads of that function, the normal overload will be chosen.

When you have a pointer as a member of a const object, you get the second, not the first.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top