I am having trouble writing this fairly simple program. I have two class A and B. B has an object of A. I need to write Copy constructor of B so that two instances of B will have the different instance of A. Is there any neat way to do this? One thing to do is getting all the member variable of parm, creating a new A object and assigning those member variables. But if the class is having more member variables then it is a problem. How to write this in a simple way?
class A
{
public:
int data;
A()
{
}
A(int parm) : data(parm)
{
}
A(const A&parm)
{
this->data = parm.data;
}
A& operator = (const A& parm)
{
if (this != &parm)
{
this->data = parm.data;
}
return *this;
}
~A()
{
cout << "A is destroyed";
}
};
class B
{
public:
A *a;
B()
{
a = new A(10);
}
B(const B&parm)
{
// How to copy the value of parm so this and parm have different A object
// this.a = parm.a --> both this and parm points to same A object
}
B& operator = (const B&parm)
{
if (this != &parm)
{
this->a = parm.a;
}
return *this;
}
~B()
{
// Null check
delete a;
}
};
a{new A{*parm.a}}
, using modern uniform initialization syntax. – Danseuse/* Null check */ delete a;
". deleting null pointer is noop, no check needed. – FelixA* a = nullptr; delete a;
is valid. – Felix