Is there a way to copy a derived class object thru a pointer to base? Or how to create such a copy constructor?
For example:
class Base {
public: Base( int x ) : x( x ) {}
private: int x;
};
class Derived1 : public Base {
public:
Derived( int z, float f ) : Base( z ), f( f ) {}
private:
float f;
};
class Derived2 : public Base {
public:
Derived( int z, string f ) : Base( z ), f( f ) {}
private:
string f;
};
void main()
{
Base * A = new *Base[2];
Base * B = new *Base[2];
A[0] = new Derived1(5,7);
A[1] = new Derived2(5,"Hello");
B[0] = Base(*A[0]);
B[1] = Base(*A[1]);
}
The question is whether *B[0] would be a Derived1 object and *B[1] a Derived2 object? If not, how could I copy a derived class thru a pointer to the base class? Is there a specific way of building a copy-constructor thru the base class or the derived one? Is the default copy-constructor good enough for the example?