copy a derived class object thru a pointer to base


Is there a way to copy a derived class object thru a pointer to base?

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?
Add virtual clone() function to the class and return new copy-constructed object from it: http://coliru.stacked-crooked.com/a/4a82202f605ca790
Topic archived. No new replies allowed.