operator overloading?

Hi guys I'm just wondering why do we need to return a reference when overloading an operator such as =,I tried returning an object and it still worked but when I tried returning an object the copy constructor gets called after the operator= gets called but when I return a reference the copy constructor does not get called after it how come?

**note sorry about the bad naming I really should have named human animal but originally I was going to name humans but decided it would be easier with animals and seeing as I'm just revising naming conventions didn't seem important to me


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
54
55
56
57
58
59
60
61
62
63
64
65
66
  #include <iostream>
using namespace std;

class Human{

private:
	string name;
	int age;

public:

	Human(string name,int age)
   :name(name),age(age)
	{
     cout << "normal with params" << endl;

	}

	Human(){

		cout << "normal" << endl;
		name = "no name";
		age = 0;
	}

	Human(const Human &other){

		cout << "copy called" << endl;
		name = other.name;
		age = other.age;

	}

	const Human& operator=(const Human &other){

		 cout << "operator = called" << endl;
         name = other.name;
         age = other.age;

         return *this;

	}

	void printInfo(){

		cout << "name is " << name << "age is " << age << endl;

	}


};



int main() {

	Human dog;
	Human cat("cat",3);
	Human lizard = cat;
	lizard.printInfo();
	Human tiger;
	tiger = cat;


}


this is the output

normal
normal with params
copy called
name is catage is 3
normal
operator = called

but when I don't return a reference and just return Human instead of Human&

I get the following output

normal
normal with params
copy called
name is catage is 3
normal
operator = called
copy called

thanks
> when I tried returning an object the copy constructor gets called
> but when I return a reference the copy constructor does not get called
> how come?
you tell it to make a copy and then you are surprise that it does do a copy.


> why do we need to return a reference
you don't need to, it's a convention
http://users.cms.caltech.edu/~donnie/cs11/cpp/cpp-ops.html
The rule of thumb is, «If it's good enough for ints, it's good enough for user-defined data-types.»
Last edited on
but when I return a reference the copy constructor is not called?
When you return a reference, that reference refers to the current object.

If you don't return a reference, then the compiler must generate a separate object and return that.

This might give an idea:
1
2
3
4
5
6
7
8
9
    const Human operator=(const Human &other) {

         cout << "operator = called" << endl;
         name = other.name;
         age = other.age;

         Human temp ( *this);
         return temp;
    }

Topic archived. No new replies allowed.