How to write copy constructor for Class with object of another class
Asked Answered
L

1

5

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;
    }
};
Larkin answered 23/5, 2018 at 3:2 Comment(4)
a{new A{*parm.a}}, using modern uniform initialization syntax.Danseuse
"/* Null check */ delete a;". deleting null pointer is noop, no check needed.Felix
@Felix When I have two objects of B having the same instance of A don't we want a NULL check required there?Larkin
I meant that A* a = nullptr; delete a; is valid.Felix
T
6

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) { }
};
Trachytic answered 23/5, 2018 at 3:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.