user4260490
user4260490

Reputation: 21

Is there a way to 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? 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?

Upvotes: 1

Views: 798

Answers (2)

Mustafa
Mustafa

Reputation: 1854

In the second line of your main (apart from the typo) you construct two instances of the class Base, then you are asking if somehow in the last two lines those objects will metamorphose on the fly and become instances of derived classes. That is of course not possible.

Also, check this answer.

Note: I am just commenting on the code and use case you provided. Using a virtual Clone function is the right design to copy polymorphic objects.

Upvotes: 0

Jarod42
Jarod42

Reputation: 217145

You may provide virtual method Clone for that:

class Base { 
public:
    Base(int x) : x(x) {}
    virtual ~Base() {}
    virtual Base* Clone() const { return new Base(*this); }
private:
    int x;
};

class Derived1 : public Base { 
public: 
    Derived1(int z, float f) : Base(z), f(f) {}
    virtual Derived1* Clone() const { return new Derived1(*this); }
private: 
    float f;
};

class Derived2 : public Base {
public: 
    Derived2(int z, std::string f) : Base(z), f(f) {}
    virtual Derived2* Clone() const { return new Derived2(*this); }
private: 
    std::string f;
};

Upvotes: 5

Related Questions