I'm having trouble understanding what's really happening with the code in a book I'm using to learn C++. Here's 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 a Base class object. What I don't understand is what's happening within that function. When I've previously used new
as in int *pInt = new int
, I was under the impression that new
essentially allocates enough memory on the free store for an integer, then returns that address, applying the address to the pointer pInt
. With that same logic I'm trying to understand the new Derived(*this)
portion of the code. So, I think it is allocating enough memory on the free store for a Derived class object, and returning the address, which is then returned by the function Clone()
.
Why, though, does it pass *this
through the constructor, if that is a constructor? I understand *this
means its passing the address of whatever object is being cloned, but I don't understand the syntax of class_name(address_of_an_object)
in the context of the new
function.
Could someone please explain what's happening in that portion?
Thanks in advance.