Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Must parameter of assignment operator be reference?

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!

like image 889
Tim Avatar asked May 30 '10 22:05

Tim


1 Answers

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.

like image 64
James McNellis Avatar answered Sep 20 '22 23:09

James McNellis