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