Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ what is the purpose of putting an operator at the end of a class? [duplicate]

Let's say I have a simple c++ component called Component like this :

class Component {
 public:
  explicit Component(int i)
  : _integer(i) {
  }

  ~Component() {
  }

  private:
   int _integer;

  Component(const Component&);
  Component& operator=(const Component&);
};

I usually found in the code I read the two last instructions but I do not really understand it. Is it mandatory for the correct use of the component ?

like image 622
klaus Avatar asked Dec 23 '22 12:12

klaus


1 Answers

This declares an overload for operator=. Overloading the operator would normally allow you to control how assignment expressions (a = b) are carried out.

In this case however, what's of interest is not the fact the operator is last, but that it's under the private access specifier. This means that outside code may not preform assignment (or copy construction for that matter, since the copy c'tor is there as well) of Component objects.

Code inside the class (in member functions) may assign and copy construct. But I would say that it's unlikely that it does. Marking those two special member functions private, and not defining them was the C++03 way of disabling copying for the class. One had to declare them to prevent the compiler from synthesizing the default copy constructor and assignment operator.

In modern C++, one may turn the "undefined symbol" error into a compile time error, by explicitly deleting those functions:

Component(const Component&) = delete;
Component& operator=(const Component&) = delete;
like image 175
StoryTeller - Unslander Monica Avatar answered Feb 23 '23 13:02

StoryTeller - Unslander Monica