C ++ copy of two derived classes

I have a base class and two derived classes, and I need to copy the pointer to the object of the derived class to one of the other class, for example, an example.

class Base { public: Base(const Base& other); } class Derived1 :public Base { public: Derived1(const Derived& other): Base(other){...}; } class Derived2: public Base { public: Derived2(const Derived& other): Base(other){...}; } main() { Derived 1 d1; Derived2 d2(d1) } 

I try to go from Derived 1 ti base (promotion allowed) and then to * dynamic_cast * Base to Derived2 and call the copy constructor, but this will not work. I only need to copy the base of both objects between two derived objects.

+8
c ++ inheritance copy-constructor derived-class
source share
1 answer

If you just want to copy part of the base class, create a constructor that gets the base class.

 Derived2(const Base& other): Base(other){...}; Derived1(const Base& other): Base(other){...}; 
+5
source share

All Articles