understanding virtual copy constructors

折月煮酒 提交于 2019-12-05 18:20:49

The misunderstanding is here:

*this means its passing the address of whatever object is being cloned

In reality, this is the address of the object that is being cloned, but *this (note the asterisk) is the result of dereferencing that address. So *this is of type Derived &, it's a reference to the object being cloned, not its address.

Therefore, calling new Derived(*this) means that after dynamically allocating space (which is what new does), the new space is initialised by the copy constructor Derived(const Derived &), which in this case hasn't actually been user-defined, so the (compiler-generated) default version of the copy constructor is used.


To clarify the semantics of new: If C is a class, then

new C;

allocates enough space for an object of type C and then calls the constructor of C to initialise that space. This is part of the semantics of new: It always calls the constructor to initialise the newly allocated space.

When you call

new C(a,b,c);

with some arguments a, b and c, then new will call a constructor of C that takes these three arguments. If no such constructor has been defined, you'll get a compiler error.

Now in the special case where you call

new C(a);

with an argument a that is itself of type C&, new will, as always, call the appropriate constructor. The appropriate constructor is either C(C &) (if defined), or C(const C&) (copy-constructor auto-defined by the compiler).

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