Click here to Skip to main content
12,448,563 members (57,244 online)
Rate this:
 
Please Sign up or sign in to 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 28-Dec-12 3:38am
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 3

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.
  Permalink  
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

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
  Permalink  
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

See here[^].
  Permalink  
Comments
Albert Holguin 28-Dec-12 15:08pm
   
+5... pretty much says it all.

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web02 | 2.8.160811.3 | Last Updated 2 Jan 2013
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100