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();
}
};
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With