Pregunta

I have a class(let's call it A) and I want to copy A. So I call A's copy constructor. A has a member of type B* which is a pointer of type B to one of his subclasses.(let's call them B with a number. (ie: B1, B5, ..)) Since I don't want to just copy the address, I call memberofA->copyconstructor from one of the subclasses. The copy constructor in the base class is called from within the copy constructor of the subclass. But is this possible or do i need to dynamic cast the pointer of type baseclass to the correct subclass the pointer is pointing too?

 class A {
 public: 
    A(const A& object) {
        // what should i call here to deep copy member
        }
 private:
    B* member //pointer to subclass of B
  };

 class B {
     privatedatamamber
  public:
     B (const B& object) {
        privatedatamember = object->getprivatedatamember(); 
     }
  };

  class B1 : public B {
    privatedatamember
  public:
    B1 (const B1& object) : B(object) {
      privatedatamember = object->getprivatedatamember(); 
    }
  };
¿Fue útil?

Solución 2

Add a public function to B:

virtual B* Clone() = NULL;

B's subclasses must implement this (pure virtual function). Here's an example:

B header:

virtual B* Clone() = 0; //public

B1 header:

virtual B* Clone();

B1 cpp:

B* B1::Clone()
{
   return new B1(*this);
}

A:

A::A(const A& object) : member(object.member->Clone()) {
}

Otros consejos

The approach I'd use is to give B an abstract method clone() returning a std::unique_ptr<B> which is implemented in every concrete class to return a copy, e.g.:

std::unique_ptr<B> D::clone() const {
    return std::unique_ptr<B>(new D(*this));
}

When a deep copy is needed you can then just call clone().

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top