Reputation: 11763
I have a question related to the implementation of the =
operator in C++. If I remember correctly, there are two ways of implementing =
in a class: one is to overload =
explicitly, and for example:
class ABC
{
public:
int a;
int b;
ABC& operator = (const ABC &other)
{
this->a = other.a;
this->b = other.b;
}
}
and the other is to define =
implicitly. For example:
class ABC
{
public:
int a;
int b;
ABC(const ABC &other)
{
a = other.a;
b = other.b;
}
}
My question is as follows:
1) Is it necessary to implement =
explicitly and implicitly?
2) If only one of them is necessary, which implementation is preferred?
Thanks!
Upvotes: 3
Views: 123
Reputation: 23650
In your case you neither need to implement copy construction nor copy assignment, since the compiler will automatically generate these member functions for you. The generated functions will simply call the copy constructor or the copy assignment operator respectively for each data member.
You only need to implement functions, if you want to have customized behavior. By the way, if you implement the copy constructor, then the copy assignment operator will still have the same default behavior as described above and vice verse. Hence, if you customize one of the two, then you probably need to customize the other one too. And possibly the destructor as well. This is called the rule of three. In most cases the default behavior will be just fine.
Upvotes: 1
Reputation: 17193
The first thing you show is the assignment operator and the second is the copy constructor. They are distinct functions doing different things. (namely the ctor sets up an object that is being born and op= changes the state of an existing object to match that of another.)
With some luck (helped by design) you do not implement either of them but leave it to the language to create them. If you use sensible members and base classes it will just happen.
If you need to go implementing them (checking twice it is really the case!) you will likely need both of them, see Rule of 3
Upvotes: 4
Reputation: 6999
If you want to customize assignment/copy, you have to implement both:
operator=
is used for assignments, for instance: ABC a; ABC b; a = b;
ABC::ABC(const ABC &other)
is used for copies, for instance: ABC a; ABC b(a);
.It's also very likely that you will want to implement a default constructor and a destructor too. You may want to read more about the rule of three.
Upvotes: 3