George Nikolaou George Nikolaou - 3 months ago 34
C++ Question

Explaining constructor and copy constructor example

I have this code and I can understand what happening with the contractor of class Fat.

#include <iostream>
using namespace std;
class Block{
int data;
public:
Block(int i = 10) : data(i){
cout << "I just created a Block " << endl;
}
~Block() {
cout << "I will destroy a Block with " << data << endl;
}
void inc() {
data++;
}
};

class A{
Block& block1;
Block block2;
public:
A(Block& blk) : block1(blk), block2(blk) {
cout << "I just created an A " << endl;
}

A(const A& a): block1(a.block1), block2(a.block2) {
cout << "I just created an A by copying but I will also do bad things" << endl;
block1.inc(); block2.inc();
}
~A() {
cout << "I will destroy an A " << endl;
}

void inc() {
block1.inc(); block2.inc();
}
};

class Fat{
A a;
A& ra;
A* pa;
public:
Fat(A& da) : a(da),ra(da) {
pa = new A(da);
cout << "Fat just created !" << endl;
}
~Fat() {
delete pa;
cout << "Fat to be destroyed !" << endl;
}
void inc() {
a.inc();
ra.inc();
pa->inc();
}
};

int main(){
Block block;
A a(block);
Fat fat(a);
fat.inc();
return 0;
}


and the result of this :

I just created a Block
I just created an A
I just created an A by copying but I will also do bad things
I just created an A by copying but I will also do bad things
Fat just created !
I will destroy an A
I will destroy a Block with 12
Fat to be destroyed !
I will destroy an A
I will destroy a Block with 12
I will destroy an A
I will destroy a Block with 11
I will destroy a Block with 15


Why does the copy constructor run twice?

Answer

The first "I just created an A by copying but I will also do bad things"comes from this line:

Fat(A& da) : a(da), ra(da) {

a(da) this one calls A's copy constructor

the seconds one from the constructer of class fat:

Fat(A& da) : a(da), ra(da) {
    pa = new A(da); //HERE!!
    cout << "Fat just created !" << endl;
}

again, with pa = new A(da); you call A's copy constructor.

edit: thank you for formatting your code