Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isnt the copy constructor of member class called?

class member
{
public:
    member()
    {
       cout<<"Calling member constr"<<'\n';
    }
    member(const member&)
    {
        cout<<"Calling member copy constr"<<'\n';
    }
};

class fred
{
public:
    fred()
    {
        cout<<"calling fred constr"<<'\n';
    }
    fred(const fred &)
    {
        cout<<"Calling fred copy constr"<<'\n';
    }
protected:
    member member_;
};

int main()
{
    fred a;
    fred b=a;
}

Output:
Calling member constr
calling fred constr
**Calling member constr**
Calling fred copy constr
like image 459
sandeep Avatar asked Dec 31 '25 07:12

sandeep


2 Answers

Because you did not call member's copy constructor. You need to copy the members explicitly if you override the default copy constructor of fred.

fred(const fred& other) : member_(other.member_) {
    cout<<"Calling fred copy constr"<<'\n';
}
like image 172
kennytm Avatar answered Jan 02 '26 00:01

kennytm


It isn't called because you explicitly asked the compiler not to call it. When you defined your own copy constructor for class fred, you essentially told the compiler that you wanted to take matters into your hands and do the copying yourself. Since you do nothing to copy the member_ in the fred's copy constructor, it isn't copied.

If you get rid of the explicit definition of fred's copy constructor, the compiler will provide an implicit one for you, which will call the member's copy constructor to copy member_.

If you insist on defining fred's copy constructor yourself, you have to copy member_ yourself, as KennyTM suggested.

like image 23
AnT Avatar answered Jan 01 '26 23:01

AnT



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!