Operator overloading question

I am new to C++ programming, and i currently working on operator overloading.
I modify one sample code in order to see which constructor and which deconstructer runs.
the code is below

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class MyClass
{
public:
	int num;
	char name;
	MyClass();
	MyClass(char, int);
	~MyClass();
	MyClass operator+ (MyClass);
};
#include "MyClass.h"
#include <iostream>
#include <string>
using namespace std;

MyClass::MyClass()
{
	cout << "MyClass constructor runs " <<name<< endl;
}
MyClass::MyClass(char newName ,int a) {
	name = newName;
	num = a;
	cout << "MyClass overloaded constructor runs " << name << endl;
	
}
MyClass MyClass::operator+ (MyClass aso) {
	MyClass brandNew;
	brandNew.num =num+ aso.num;
	return (brandNew);
}
MyClass::~MyClass() {
	cout << "Deconstructor runs " <<name<< endl;

}
#include <iostream>
#include "MyClass.h"
using namespace std;

int main()
{
	MyClass a('a',34);
	MyClass b('b',21);
	MyClass c;

	c = a + b;

	cout << c.num << endl;
	
	
    return 0;
}



after i run the program, the output is:
1
2
3
4
5
6
7
8
9
10
11
MyClass overloaded constructor runs a
MyClass overloaded constructor runs b
MyClass constructor runs
MyClass constructor runs
Deconstructor runs
Deconstructor runs b
Deconstructor runs
55
Deconstructor runs
Deconstructor runs b
Deconstructor runs a

why deconstructor for object b runs twice?

Thank you for helping!

Last edited on
Because you passed b by value, so a copy is made. When operator+ returns the copy is destroyed, hence "Deconstructor runs b".
When you pass by const reference, b isn't copied and results in

MyClass overloaded constructor runs a
MyClass overloaded constructor runs b
MyClass constructor runs 
MyClass constructor runs 
Deconstructor runs 
Deconstructor runs 
55
Deconstructor runs 
Deconstructor runs b
Deconstructor runs a
Thank you for explanation ! its really helpful !
Topic archived. No new replies allowed.