Why can I assign one object to another without overloading the "=" operator?

Viewed 180

I'm new to C++ and just learned about overloading operators. I'm confused because it seems like I can assign one object to another without having to overload the "=" operator. Take this code as example:

class process
{
  int size;
  
public:
  process(int s)
  {
    size = s;
  }
  ~process();

  int getSize()
  {
    return size;
  }
  
};

int main()
{
  process p1(2);
  process p2(3);
  p1 = p2;
  std::cout << p1.getSize() << "\n";
}

The output is:

3

As you can see, the info from the process class "p2" were copied to "p1", but I haven't overloaded the "=" operator. Why is this happening? Is there any place where I can have some concrete info about what C++ did for this to happen? Thanks.

1 Answers

Why can I assign one object to another without overloading the “=” operator?

Because classes have an implicitly generated copy (and move) assignment operator.

Is there any place where I can have some concrete info about what C++ did for this to happen?

Authorative source of info is the standard document.

Books have also been written about C++.


But then why would I want to overload the "=" operator?

There is no reason to want to overload assignment operator of your example class.

In general, you may want to overload because

  • The assignment operator generated by the compiler cannot read your mind and do what you want it to do. it does exactly one thing, and if that is not what you want, then you need to define your own. If you follow best practices, then most often the implicitly generated assignment operator does do what you want.

  • You may sometimes want to be able to assign other types.

  • Sometimes the implicitly generated operator is deleted, such as when there are non-assignable members. In such case, you may define your own if you know what the operator should do.


P.S. The compiler also implicitly generates the destructor. You don't need to define a destructor for your class.

Related