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 welcome () to print different messages? Why don't they type "y"? Is it because the first is a copy, and the second actually points to an object in memory?

 int main() { ya; xb = a; b.hello(); // prints x x* c = &a; c->hello(); // prints y return 0; } 
+7
source share
4 answers

Yes you are right

 xb = a; 

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

 x& b = a; 

Assigns a link and will use redefinition (b is still actually "y")

+6
source

Because xb = a; fragments of the object.

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

+6
source

xb = a copies a to b. Since b is of type x, you get an object of type x. An object of type x will print x.

The only way to get y is when you call an object of type y.

0
source

b.hello() prints "x" because b is an instance of class X. c->hello() prints "y" because c points to a , and a is an instance of class Y.

What may confuse you is that when you write xb = a; , you create a new object b and initialize it a . When you write x* c = &a; , c not a new object. You simply entered the alias of an existing object.

0
source

All Articles