Question with virtual functions

半城伤御伤魂 提交于 2019-12-05 05:07:44

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')

John Dibling

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'.

x b = a copies a to b. Since b is type x, you end up with an object of type x. An object of type x will print x.

The only way you get y is when you are calling into an object of type y.

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 might be confusing for you is that when you write x b = a;, you're creating a new object b and initializing it with a. When you write x* c = &a;, c is not a new object. You just introduced an alias to an existing object.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!