Constructor and Destructor in C++

Hello,

Why is the destructor called 4 times?
We create two objects, but we destroy it four times. that is weird.
I expected it to be: CCDD
Thanks

Output is: CCDDDD

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include<string.h>
using namespace std;


class test {
public:
	test()
	{
		cout << "C";
	}
	~test()
	{
		cout << "D";
	}
};
test func(test ob1)
{
	test a;
	return ob1;
}


int main()
{
	{
		test ob;
		func(ob);
	}
	return 0;
}
Last edited on
It's because you haven't defined a copy constructor, so the compiler made a default one.

When you pass your ob into func, that calls the copy constructor.
When you return ob1, that also calls the copy constructor.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
using namespace std;

class test {
public:
	test()
	{
		cout << "C";
	}
	test(const test& other)
	{
		cout << "C";   
	}
	~test()
	{
		cout << "D";
	}
};

test func(test ob1)
{
	test a;
	return ob1;
}

int main()
{
	{
		test ob;
		func(ob);
	}
	return 0;
}
CCCCDDDD
Last edited on
Line 27, an object is default constructed in main.

Line 17, a copy of the passed object is copy-constructed when invoking the function. You don't have a copy constructor so you never see it being constructed.

Line 19, a local function object is constructed.

Line 20, another copy of the passed object is copy constructed.

Line 21, both of the copied and function local objects are destructed. 3 destructors called when the function terminates.

Line 30, the object in main is destructed when the program terminates.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>

class test
{
public:
   // ctor
   test() { std::cout << "Ctor\n"; }

   // copy ctor
   test(const test& obj) { std::cout << "Ctor &\n"; } // ooops! forgot the const!

   // dtor
   ~test() { std::cout << "Dtor\n"; }
};

test func(test ob1)
{
   std::cout << "line 19: ";
   test a;

   std::cout << "line 22: ";
   return ob1;
}


int main()
{
   std::cout << "line 29: ";
   test ob;

   std::cout << "line 32: ";
   func(ob);

   std::cout << "line 35: ";
}

line 29: Ctor
line 32: Ctor &
line 19: Ctor
line 22: Ctor &
Dtor
Dtor
Dtor
line 35: Dtor


Last edited on
Topic archived. No new replies allowed.