   C++ Polymorphism and Returning by Reference
  Hi all,Since it's pretty straighfoward here's the code:class A {public:  A() { }  virtual ~A() {}  virtual void Show()   {    cout << "A Shows" << endl;  }};class B : public A {public:  B() { }  virtual ~B() { }  void Show()   {    cout << "B Shows" << endl;  }};class C {private:  B b;public:  C() { }  // Returning by pointer  A* GetB()  {    return &b;  }  // Returning by reference  const A& GetA() const  {    return b;  }};void main(){C c;A* b = c.GetB();A a = c.GetA();b->Show();  // Prints: "B Shows"a.Show();   // Prints: "A Shows"}Quote:From MSDNA virtual function is a member function that you expect to be redefined in derived classes. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the function.So, what i'm doing wrong? I'm expecting both method to print out "B Shows", i think i should be right after reading MSDN!Thanks in advance,Jonathan   
  A a = c.GetA();Should be:A& a = c.GetA();Otherwise you're creating a copy of an A class, not a reference or pointer to an A that's actually a B.   ;  Thanks Evil Steve,I got another question,Quote:In class C const A& GetA() const  {    return b;  }I've remove both const for this to work, can you explain me what both stands for? The first one probably means the return value cannot be changed, but the second?Thanks,Jonathan   ;Quote:Original post by LowRadThanks Evil Steve,I got another question,Quote:In class C const A& GetA() const  {    return b;  }I've remove both const for this to work, can you explain me what both stands for? The first one probably means the return value cannot be changed, but the second?Thanks,JonathanThe second const means that the function do not change anything in the object. BTW, const A& a = c.GetA(); would have worked. Regards,   ;Quote:Original post by LowRadI've remove both const for this to work, can you explain me what both stands for? The first one probably means the return value cannot be changed, but the second?The second means the function doesn't change any members and so is const safe. If you wanted to use your orginal function you could have just done const A& a = c.GetA();Edit:Im too slow, also if your going to use the const version you need to make void Show() const safe - virtual void Show() const  {    cout << "A Shows" << endl;  };  Be aware that you *do not need* to assign the result of a function call to a temporary in order to make further use of it. Just like you can write (12 + 23) * 42, you can write c.getA().Show(). Because no assignment-to-temporary happened, there is no chance for this to get messed up.However, when you assign a Foo& to a Foo, it copies the object, just like if you assign a Foo to some other Foo. Assigning a Foo& to another Foo& only copies the reference.As for the const business...