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

+1

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

+5

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

+5

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

+4

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; } };

+2

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

+2