Reputation: 1255
class A
{
protected:
int a;
public:
A();
A(int);
virtual void print()=0;
virtual ~A();
};
class B: public A
{
int b;
public:
B();
B(int,int); //initialize attributes a and b
void print(); //print a and b
};
class C: public A
{
float c;
public:
C();
C(float,int); //initialize attributes a and c
void print(); //print a and c
};
class D
{
int size; //number of objects in v
A **v; /* an array(a vector) of A pointers that allows me to have both B and C type objects */
public:
D();
D(int);
D(D&);
~D();
D operator=(const D&);
void PrintAll();
};
All methods for D:
D::D()
{
v=NULL;
}
D::D(int x)
{
size=x;
v=new A*[x];
for(int i=0;i<x;i++)
{
if(i%2==0)
v[i]=new B(4,7);
else
v[i]=new C(3,5);
}
}
D::D(D& other)
{
size=other.size;
v=new A*[size];
for(int i=0;i<size;i++)
{
if(i%2==0)
{
v[i]=new B();
*v[i]=other.v[i][0];
}
else
{
v[i]=new C();
*v[i]=other.v[i][0];
}
}
}
D::~D()
{
if(v!=NULL)
{
for(int i=0;i<size;i++)
{
delete v[i];
}
delete[] v;
}
}
D D::operator=(const D& other)
{
if(v!=NULL)
{
for(int i=0;i<size;i++)
{
delete v[i];
}
delete[] v;
}
size=other.size;
v=new A*[size];
for(int i=0;i<size;i++)
{
if(i%2==0)
{
v[i]=new B();
*v[i]=other.v[i][0];
}
else
{
v[i]=new C();
*v[i]=other.v[i][0];
}
}
return *this;
}
void D::PrintAll()
{
cout<<"Printall():"<<endl;
for(int i=0;i<size;i++)
v[i]->print();
}
As you can see, the D class constructor makes the objects of type B or C as i is odd or even. If I know this, then I know how to write the operator= and the copy constructor for D. But If the class D constructor would make the objects of type B or C randomly, then how can I write the copy constructor (and operator=) for class D? My guess is I have to use typeid operator to solve this problem.
Upvotes: 0
Views: 166
Reputation: 18368
Define pure virtual method clone
as part of your interface A
definition - clone
shall return a copy of the object.
Override and implement it in each of your B
and C
classes.
In D
class copy constructor and assignment operator implementations use A
's interface to create the required class instance instead of explicit call to new
: v[i] = other.v[i]->clone();
. No need for RTTI
, normal polymorphism will do.
Upvotes: 1