Although there are numerous posts with managing pointers in copy constructors, i did not find the suitable answer to realize the following properly.
An object 'a' of class A stores a 'tab' array of elements that are pointers to elements of either type B1 or B2, both derived from class B.
I want to save a copy of 'a' (to restore it later) by calling a copy constructor. My problem is to allocate memory in this copy constructor, to make a copy of the contents of the 'tab[i]' elements.
There must be a canonical way of doing this (i suppose without invoking <dynamic_cast> to determine if this is type B1 or B2).
This is the MWE i have build to illustrate the question:
#include <iostream>
using namespace std;
//-----------------------
class B {
public:
virtual void display()=0;
};
//-----------------------
class B1 : public B {
public:
B1() : val(1) // ctor
{}
void display() {
cout << val << endl;
}
private:
int val;
};
//-----------------------
class B2 : public B {
public:
B2() : val(2) // ctor
{}
void display() {
cout << val << endl;
}
private:
int val;
};
//---------- A -------------
class A {
public:
A () { // ctor
tab = new B * [2];
tab[0] = new B1;
tab[1] = new B2;
}
A (A const &orig) // copy ctor
: tab(orig.tab)
{
// ... HOW should i make a copy of the tab[i] elements ?...
// ... as i do not know if tab[i] is type B1 or B2 ...
}
void display() {
tab[0]->display();
tab[1]->display();
}
private:
B ** tab;
};
//------M A I N ---------
int main() {
A a;
a.display();
return 0;
}