Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy constructor for a baseclasspointer to a subclass

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(); 
    }
  };
like image 370
user2321611 Avatar asked Sep 06 '25 02:09

user2321611


1 Answers

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().

like image 182
Dietmar Kühl Avatar answered Sep 07 '25 15:09

Dietmar Kühl