I'm trying to implement a copy constructor and an overloaded assignment constructor. I've an Employee class that has three data members. 1-name 2-title 3-salary.
Employee::Employee(const Employee &emp)
{
name = emp.name;
title = emp.title;
salary = emp.salary;
cout << "\nOverloaded copy constructor called\n";
}
Employee Employee::operator = (const Employee &emp) //Overloading the assignment operator.
{
name = emp.name;
title = emp.title;
salary = emp.salary;
cout << "\nOverloaded assignment operator called\n";
return emp; //Or return *this.
}
Here's what I do not understand:
1- I haven't got to the "this" pointer. Should my overloaded assignment operator return *this or the emp object. Because it seems to me that that object in the parameter is the right hand object at the assignment. So shouldn't I return the left hand object with *this(if that's what *this will be doing)?
2- At the main function, I tried to call to call the assignment operator first and the copy constructor after that. So I was expecting that I will see the cout statements I've included there one after the other however, Here's my output:
Overloaded copy constructor called
Overloaded assignment operator called
Overloaded copy constructor called
Overloaded copy constructor called
Why is this happening?
3-Do I have to pass the objects with const? The book I'm learning from does not.
In the main I just wrote
Employee x;
x = another;
Employee y = x;
"another" is just a (poorly named) Employee object I've initialized earlier in my code.
So shouldn't the first assignment output
"Overloaded assignment operator called" and the second assignment (Which isn't an assignment but a copy according to my understanding) output "Overloaded copy constructor called"