Click here to Skip to main content
Rate this: bad
good
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 1

See here[^].
  Permalink  
Comments
Albert Holguin at 28-Dec-12 15:08pm
   
+5... pretty much says it all.
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  

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

  Print Answers RSS
0 OriginalGriff 369
1 Sergey Alexandrovich Kryukov 294
2 Maciej Los 270
3 George Jonsson 185
4 PIEBALDconsult 175
0 Sergey Alexandrovich Kryukov 10,934
1 Maciej Los 5,614
2 OriginalGriff 5,603
3 CPallini 3,879
4 BillWoodruff 3,579


Advertise | Privacy | Mobile
Web04 | 2.8.141030.1 | Last Updated 2 Jan 2013
Copyright © CodeProject, 1999-2014
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