Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ copy of two derived class

I have a base class and two derived class, and I need to copy a pointer to an object of the derived class to one of the other class, like the 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 pass from Derived 1 ti base (upcasting allowed), and then to *dynamic_cast* Base to Derived2 and call the copy constructor, but it won't work. I only need to copy between the two derived object the Base part of both objects.

like image 937
Pablosproject Avatar asked Dec 19 '12 09:12

Pablosproject


1 Answers

If your intent is to just copy the Base class part, make a constructor that receives a base class.

Derived2(const Base& other): Base(other){...};

Derived1(const Base& other): Base(other){...};
like image 157
Yochai Timmer Avatar answered Nov 03 '22 09:11

Yochai Timmer