0
could someone break down this piece of code for me, i didnt understand a word
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; } }; int main() { MyClass obj1(12), obj2(55); MyClass res = obj1+obj2; cout << res.var; } //Outputs 67 // like why are there 2 constructors, one inside another
1 Antwort
+ 3
first constructor takes no arguments, second constructor takes an int argument and assign it to public member 'var'. With first constructor you can create object with no initial value for var.
This line (the second constructor):
MyClass(int a) : var(a) {}
take argument int a and initializes the member var with value of 'a'. It's same as:
MyClass(int a) { this->var = a; }
except the first version can initialize constant members.
After that you do operator overloading on + and define how the + operator will work for objects of your class type.
You will add their internal variables (called var) together and return the sum in another object of that class called 'res'.
In main() function where you do res = obj1 + obj2, the + operator does the same as:
res.var = obj1.var + obj2.var.
obj1 was initialized with value 12, obj2 initialized with value 55.
The sum of both is 67 which is stored in object 'res'. You print out the result with res.var.