-1

I failed to understand the steps of compilation of this code. First, where is what is purpose of the default constructor, and why so many objects of type MyClass? link to sololearn where I saved the code

#include <iostream>
using namespace std;

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

        MyClass operator+(MyClass &obj) {
            MyClass res;
            res.var= this->var+obj.var;
            //'this' is refering to active (obj1)
            return res; 
        }
};

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

    MyClass res = obj1+obj2;

    cout << res.var;
}
//I've not understood, its from a lesson
Hilary Diaz
  • 39
  • 1
  • 6

2 Answers2

0

If you suspect you don't need a piece of code, try compiling without it and you'll know pretty quickly whether your suspicion was correct or not.

When you remove the default constructor in the class you provided here's what happens:

..\Playground\: In member function 'MyClass MyClass::operator+(MyClass&)':
..\Playground\:11:21: error: no matching function for call to 'MyClass::MyClass()'
             MyClass res;
                     ^~~
..\Playground\:7:9: note: candidate: MyClass::MyClass(int)
         MyClass(int a)
         ^~~~~~~
..\Playground\:7:9: note:   candidate expects 1 argument, 0 provided
..\Playground\:4:7: note: candidate: constexpr MyClass::MyClass(const MyClass&)
 class MyClass {

Which is to say the problem is in the +operator implementation at the line MyClass res; . This line creates an instance of the object MyClassusing the default constructor, so there's no way the code snippet your provided works without a default constructor.

samuelnj
  • 1,627
  • 1
  • 10
  • 19
0

The constructor without parameters is for the object that doesn't pass any value, the one that stores the sum of the two operand objects. ---simple---

Hilary Diaz
  • 39
  • 1
  • 6