Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy constructor invocation for member objects

Tags:

c++

C++ says that to create a copy constructor for a class that uses composition, the compiler recursively calls the copy constructors for all the member objects. I tried that same thing in the below code:

class A
{
public:
    A(){cout<<"A constructor called"<<endl;}
    A(const A&){cout<<"A copy constructor called"<<endl;}
};

class B
{
public:
    B(){cout<<"B constructor called"<<endl;}
    B(const B&){cout<<"B copy constructor called"<<endl;}
};

class C
{
    A a;
    B b;
public:
    C(){cout<<"C constructor called"<<endl;}
    C(const C&){cout<<"C copy constructor called"<<endl;}// If you comment this line, you will get output: Case 1 (see below)     and if you don't comment, you will get o/p: case 2(see below)
};


void main()
{
    C c;
    cout<<endl;
    C c2 = c;
}`

Case 1:

A constructor called

B constructor called

C constructor called

A copy constructor called

B copy constructor called

Case 2:

A constructor called

B constructor called

C constructor called

A constructor called

B constructor called

C copy constructor called

My doubt is that the o/p for case 2 should be: A, B, C, constructor called and then.. A, B, C copy constructor called. But it is not happening. Please help.

like image 742
Jatin Avatar asked Feb 15 '26 13:02

Jatin


1 Answers

That would happen, except that you have provided your own copy constructor for C, which tells the compiler "don't provide the default copy constructor."

If you want your copy constructor to do the same thing that the implicitly defined copy constructor would do (along with your extra printing), you'd need to define it as follows:

C(const C& other)
    : a(other.a), b(other.b)
{
    std::cout << "C copy constructor called" << std::endl;
}
like image 139
James McNellis Avatar answered Feb 19 '26 01:02

James McNellis



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!