Understanding Virtual Copy Designers

I am having trouble understanding what is actually happening with the code in the book that I use to learn C ++. Here is the code:

class Base { public: Base() {}; virtual ~Base() {}; virtual Base* Clone() {return new Base(*this);} }; class Derived { public: Derived() {}; virtual ~Derived() {}; virtual Base* Clone() {return new Derived(*this);} }; 

So, in this Clone() function, I understand that the function returns a pointer to an object of the Base class. I do not understand what is going on inside this function. When I previously used new , as in int *pInt = new int , I got the impression that new essentially allocates enough memory in free storage for an integer, and then returns that address, applying the address to the pInt pointer, From the same By logic, I am trying to understand part of the new Derived(*this) code. Therefore, I think that it allocates enough memory in free storage for an object of class Derived and returns an address, which is then returned by the Clone() function.

Why, however, does it pass *this through the constructor, if it is a constructor? I understand that *this means that it passes the address of any object cloned, but I donโ€™t understand the syntax of class_name(address_of_an_object) in the context of the new function.

Can someone explain what is happening in this part?

Thanks in advance.

+4
source share
1 answer

Misunderstanding here:

*this means that it passes the address of any cloned object

Actually, this is the address of the object being cloned, but *this (note the asterisk) is the result of dereferencing this address. So *this is of type Derived & , this is a reference to the cloned object, not its address.

Therefore, calling new Derived(*this) means that after dynamically allocating space (which makes new ), the new space is initialized by the Derived(const Derived &) copy constructor Derived(const Derived &) , which in this case was not actually defined by the user, therefore, the version of the copy constructor (generated by compiler) by default.


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 initialize this space. This is part of the new semantics: it always calls the constructor to initialize the newly allocated space.

When you call

 new C(a,b,c); 

with some arguments a , b and C , then new calls the constructor of C , which takes these three arguments. If such a constructor is not defined, you will get a compiler error.

Now in the special case when you call

 new C(a); 

with argument a , which in itself is a C& type, new , as always, will invoke the corresponding constructor. The corresponding constructor is either C(C &) (if defined) or C(const C&) (copy constructor automatically determined by the compiler).

+10
source

All Articles