1

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?

  • Look up [*clone pattern*](https://katyscode.wordpress.com/2013/08/22/c-polymorphic-cloning-and-the-crtp-curiously-recurring-template-pattern/). – Quentin Jan 14 '15 at 19:04
  • 1
    Is `Base * A = new *Base[2];` a typo? That won't compile. Actually, your whole main() method is full of problems. – mbgda Jan 14 '15 at 19:05
  • I believe polymorphic copies are idiomatically implemented via a method called `Clone()` (you would have to write the clone method yourself) and you basically write it the way you would a constructor, but as @Quentin says, look up the clone pattern for the specifics. – YoungJohn Jan 14 '15 at 19:05
  • 1
    [_The definition void main() is not and never has been C++, nor has it even been C._ – Bjarne Stroustrup](http://www.stroustrup.com/bs_faq2.html#void-main) – Julian Jan 14 '15 at 19:49

2 Answers2

5

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;
};
Jarod42
  • 203,559
  • 14
  • 181
  • 302
0

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.

Community
  • 1
  • 1
Mustafa
  • 1,814
  • 3
  • 17
  • 25