When overloading assignment operator of a class in C++, must its parameter be reference?
For example,
class MyClass {
public:
...
MyClass & operator=(const MyClass &rhs);
...
}
Can it be
class MyClass {
public:
...
MyClass & operator=(const MyClass rhs);
...
}
?
Thanks!
The parameter of an overloaded assignment operator can be any type and it can be passed by reference or by value (well, if the type is not copy constructible, then it can't be passed by value, obviously).
So, for example, you could have an assignment operator that takes an int
as a parameter:
MyClass& operator=(int);
The copy assignment operator is a special case of an assignment operator. It is any assignment operator that takes the same type as the class, either by value or by reference (the reference may be const- or volatile-qualified).
If you do not explicitly implement some form of the copy assignment operator, then one is implicitly declared and implemented by the compiler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With