a basic problem

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
include <iostream>


using namespace std;
class Man{
public:
	Man(int id){m_id = id; cout << "build" << m_id  << endl;}
	~Man(){cout << "destroy" << m_id << endl;}
private:
	int m_id;
};
int
main()
{
	Man a(1);
	a = Man(2);
	cout << "program end" << endl;
	return 0;

}


running the code to get the following result:
1
2
3
4
5
build1
build2
destroy2
program end
destroy2


Why "destroy2" appear twice?
Why "destroy2" appear twice?
Because on line 16 you changed m_id to 2. Hence destroy1 doesn't appear
on line 16 you set 'a' equal to a different value, the line creates a temporary unnamed object with the value of 2 and sets 'a' equal to the object using a default overloaded operator supplied by c++. Once the object is used then the compiler destroys the object. Literally the same answer as coder777, just more in depth
Last edited on
Topic archived. No new replies allowed.