operator overloading C++ | SoloLearn: Learn to code for FREE!


operator overloading C++

#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; return res; } }; int main() { MyClass obj1(12), obj2(55); MyClass res = obj1+obj2; cout << res.var; } Please helppp. Why missing the “MyClass() { }”in line 7 will cause error??

10/29/2019 2:03:57 AM


5 Answers

New Answer


Your code works just fine for me. To answer your question, C++ requires you to have an empty constructor when conducting constructor overloading


If we want to overload C++ constructors in a class, the default constructor will not be available and if you want to create an object that calls the empty constructor, this will fail. The compiler checks for this hence the error you see


Here is a simple example, in following code below, if we remove the empty constructor from the class and create object like "Employee obj," a compiler error will be thrown because the compiler will not find default constructor. Once, we write an empty constructor, everything will be fine. class Employee { int id; public: //Empty Constructor required here Employee(){} //one argument overloaded constructor Employee(int id) { this->id = id; } };


Why is it required🤔Does it have any special meaning?