I wanted to ask a question about operator overloading in C++.
I am a beginner in C++ and have been learning OOP.
Consider the following overloaded copy assignment operator:
class Base {
private:
int value;
public:
Base () : value {0}
{
cout << "Base No-args constructor" << endl;
}
Base (int x) : value {x} {
cout << "Base (int) overloaded constructor" << endl;
}
Base (const Base &other) : value {other.value} {
cout << "Base copy constructor" << endl;
}
Base & operator = (const Base &rhs) {
cout << "Base operator=" << endl;
if (this == &rhs)
return *this;
value = rhs.value;
return *this;
}
~ Base () {cout << "Base Destructor" << endl;}
};
I wanted to clarify two points.
- How does this copy assignment operator work?
- Does the reference before the operator keyword need a parameter name?
I wanted to give my interpretation on (1).
If I have the following code in my main()
:
Base b {100}; // overloaded constructor
Base b1 {b}; // copy constructor
b = b1; // copy assignment
What I think happens is that the no args constructor is called for a1
, evidently because no arguments are passed into the construction of the object.
When a2
is initialised, a temporary copy of a1
is made and then the operator is evaluated with respect to the Base
class, hence the Base
overloaded copy assignment block is run, and the a1
object is returned via return *this
to the reference a2
.
To explain my thoughts on the second question,
I thought that all parameters need a name when a function or method is declared (I may of course be wrong).
If my overloaded copy assignment block was written hypothetically as:
Base &lhs operator = (const Base &rhs)
am I right in saying that lhs
is referring to a2
but as we don't do anything with lhs
due to the implied this
parameter, we don't need to give a parameter name following the ampersand before the operator?