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;
}
};
Can copy constructor be used to initialize one class object with another class object? Explanation: The restriction for copy constructor is that it must be used with the object of same class. Even if the classes are exactly same the constructor won't be able to access all the members of another class.
CPP. A copy constructor is called when a new object is created from an existing object, as a copy of the existing object. The assignment operator is called when an already initialized object is assigned a new value from another existing object.
If an object is passed as value to the Copy Constructor then its copy constructor would call itself, to copy the actual parameter to the formal parameter.
You can't assign two objects of different classes to each other which are not related to each other until you overload "=" operator for them.
B
's copy constructor needs to allocate a new A
object that copies data
from the source parm.a
member, which you can do using A
's copy constructor:
B(const B &parm) {
a = new A(*(parm.a));
}
Also, in B
's assignment operator, both A
objects are already allocated, so just invoke A
's assignment operator:
B& operator=(const B &parm) {
if (this != &parm) {
*a = *(parm.a);
}
return *this;
}
That being said, you can greatly simplify the code if you get rid of the pointer and let the compiler handle the memory allocations and copies for you:
class A {
public:
int data;
A(int parm = 0) : data(parm) { }
~A() { cout << "A is destroyed"; }
};
class B {
public:
A a;
B() : a(10) { }
};
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