Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

where should I implement the operator = in C++

Tags:

c++

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!

like image 989
feelfree Avatar asked Nov 22 '25 15:11

feelfree


1 Answers

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

like image 98
Balog Pal Avatar answered Nov 24 '25 06:11

Balog Pal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!