Why doesn't my overloading operator activate??

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
#include<iostream>

using namespace std;

class Try{
	public:
		Try(int);
		Try(const Try &pich);
		Try& operator=(const Try &pich);
		int a;
		
		
		
	
};

Try::Try(int b){
	a=b;
}
Try::Try(const Try& pich)
{
	cout<<"dssd";
	a=pich.a;

}

Try& Try::operator =(const Try &pich)
{
	cout<<"SDsa";
	a=pich.a;
	return *this;
}

int main()
{
	Try e(24);
	Try q=e;
	cout<<q.a<<endl;

	
}


I was trying to make both the copy constructor and the overloading operator activate. Some advice please :)
When you say "overloading operator" I assume you mean operator=.

When the compiler sees Try q=e;, it's free to implement it as either Try q; q=e; (default constructor followed by assignment operator) or Try q(e); (copy constructor). Since you haven't defined a default constructor it can't do the former so it must do the latter.

Note that giving the compiler this flexibility is the reason why a default constructor and assignment operator must be symantically equivalent to a copy constructor.
1
2
3
4
5
6
7
Try q( 24 ); // Calls Try::Try(int)

Try e ( q ); // Calls Try::Try(const Try&)
Try d = q; // Calls Try::Try(const Try&)
Try f { e }; // C++11, calls Try::Try(const Try&)

f = e; // Calls Try::operator= (const Try&) 
dhayden wrote:
When the compiler sees Try q=e;, it's free to implement it as either Try q; q=e; (default constructor followed by assignment operator) or Try q(e); (copy constructor).

That's incorrect, Try q=e; is not an assignment expression, just like int * p; is not a multiplication. It can only call the constructor.
Thank you SO VERY MUCH!!!! :)))
Topic archived. No new replies allowed.