Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy Constructor for not dynamic allocation

Tags:

c++

According to definition : When an object of this class is copied, the pointer member is copied, but not the pointed buffer, resulting in two objects pointing to the same so we use copy constructor.
But in following class there is no copy constructor but it Works! why? Why i dont need to deep copying?

class Human
{
private:
    int* aValue;

public:
    Human(int* param)
    {
        aValue=param;
    }

    void ShowInfos()
    {
        cout<<"Human's info:"<<*aValue<<endl;
    }
};

void JustAFunction(Human m)
{
    m.ShowInfos();
}

int main()
{
    int age = 10;
    Human aHuman(&age);
    aHuman.ShowInfos();
    JustAFunction(aHuman);
    return 0;
}


output:

Human's info : 10
Human's info : 10

like image 762
Vito Carleone Avatar asked Mar 24 '26 11:03

Vito Carleone


1 Answers

A copy constructor is useful when your class owns resources. In your case, it doesn't - it neither creates nor deletes aValue itself.

If you did do that though, say:

Human()
{
    aValue=new int;
}

and properly cleaned up the memory:

~Human()
{
    delete aValue;
}

then you'd run into issues, because Human a; and Human b(a); would have the members aValue point to the same location, and the when they go out of scope, the same memory is released, resulting in a double delete.

like image 157
Luchian Grigore Avatar answered Mar 27 '26 01:03

Luchian Grigore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!