8

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.

Caesar
  • 9,483
  • 8
  • 40
  • 66
Pablosproject
  • 1,374
  • 3
  • 13
  • 33
  • In case you need to access full information of Derived1 within Derived2 and vice-versa, you are coupling the classes strongly. Maybe it would be easier to simply not to store pointers of each class into another class, but to implement the accessor functions in Derived1 and Derived2 and another class OperateOnDerived that stores references to both Derived1 and Derived2 and computes what ever you need from them. – tmaric Dec 19 '12 at 10:33

1 Answers1

5

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){...};
Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185