Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
C++
#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 .
Posted

See here[^].
 
Share this answer
 
Comments
Albert Holguin 28-Dec-12 15:08pm    
+5... pretty much says it all.
In your code, Hello is a pointer to something else. In a const method, you can change the 'something else' through Hello, and can call non-const methods on Hello, but you can't change Hello.
 
Share this answer
 
This is perfectly legal:

  1. you do not modify the Hi instance's memory. Doing hello = NULL; would not work since you would modify the Hi instance's memory.
  2. If hello was defined as Hello const * hello;, the call to the non-const method Test was not legal.

Cheers
Andi
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900