Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question with virtual functions

I have two classes:

class x {
public:
  virtual void hello() {
    std::cout << "x" << std::endl;
  }
};

class y : public x {
public:
  void hello() {
    std::cout << "y" << std::endl;
  }
};

Can someone explain why the following two calls to hello() print different messages? Why don't they both print "y"? Is it because the first one is a copy while the second one actually points to the object in memory?

int main() {
  y  a;

  x b = a;
  b.hello(); // prints x

  x* c = &a;
  c->hello(); // prints y
  return 0;
}
like image 536
Marlon Avatar asked Jan 28 '11 06:01

Marlon


2 Answers

Yes, you are right

x b = a;

Invokes a copy constructor (b IS an 'x')

x& b = a;

Assigns a reference and will use the override (b is still actually a 'y')

like image 71
StuartLC Avatar answered Sep 29 '22 11:09

StuartLC


Because x b = a; slices the object.

When this code executes, it creates a new x, not a y, which is a copy of the original y, a'.

like image 22
John Dibling Avatar answered Sep 29 '22 12:09

John Dibling