I have a question regarding copying polymorphic objects. My starting point is the usual example of how to implement a clone-function:
#include <iostream>
class Base
{
protected:
int a;
public:
void set_a(int x) { a = x; }
void get_a() { std::cout << a << "\n"; }
virtual ~Base() {}
virtual Base *clone() const = 0;
};
class Derived : public Base
{
public:
virtual Derived *clone() const
{
return new Derived(*this);
}
};
int main(int argc, char *argv[])
{
Base *ptr = new Derived;
ptr->set_a(20);
ptr->get_a();
Base *cpy = ptr->clone();
cpy->get_a();
}
Why does the line new Derived(*this) result in a copying of this? Is it because we call the copy constructor of Derived with this as argument?
If we are indeed calling the copy constructor of Derived, then why doesn't the following compile:
Base *b = new Derived(ptr); //does not compile
Is it because we call the copy constructor of
Derived?
Absolutely. *this expression inside Derived::clone is of type Derived&, so Derived::Derived(const Derived& original) copy constructor is called.
Why doesn't the following compile:
Base *b = new Derived(ptr);
This call does not compile because ptr is a pointer, not a reference. This would compile, but it would be pointless in the context of cloning:
Base *b = new Derived(*ptr);
The point of cloning is that you don't know what type you get as the result; when you do new Derived(*ptr) you specify the type explicitly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With