1

Consider the following C++ code such that I took it from "Sololearn". I'm a beginner and I would be grateful if any one could answer. It is on operator-overloading topic.

  class MyClass {
 public:
  int var;
  MyClass() {}
  MyClass(int a)
  : var(a) { }

  MyClass operator+(MyClass &obj) {
   MyClass res;
   res.var= this->var+obj.var;
   return res; 
  }
};

When they use it in main environment they use the following code

int main() {
  MyClass obj1(12), obj2(55);
  MyClass res = obj1+obj2;

  cout << res.var;
}

My questions:

Why does MyClass has two constructors? The most important question for me is that "operator+" has been defined like a function but when we use it in main its usage is not like a function. Why? Another different question is that is it true to say that the + used in this line MyClass res = obj1+obj2; is from the Operator+?

Math
  • 157
  • 7

1 Answers1

2

Why does MyClass has two constructors?

Because that's what the person who wrote it wanted. They wanted to make it so that you can provide an initial value if you wanted, and just let it default to zero otherwise.

Unfortunately, they made a mistake, and their default constructor is broken. It should be like this:

MyClass() : var(0) {}

…otherwise the value of var is indeterminate and a program trying to read it has undefined behaviour.

Now you can create an object like this:

MyClass obj;      // uses first constructor

Or like this:

MyClass obj(12);  // uses second constructor

"operator+" has been defined like a function but when we use it in main its usage is not like a function. Why?

Because you can. Because operators are special. C++ is designed this way. To be able to overload/define them they need to be functions, but to be operators they need their own syntax to use.

Note that you can call it like a function if you want to:

MyClass res = obj1.operator+(obj2);

…but you don't want to.


is it true to say that the + used in this line MyClass res = obj1+obj2; is from the Operator+?

Yes.


It would be better to learn C++ from a proper book.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055