Operator Overloading
Jun 5, 2017 at 7:37am UTC
I keep getting the error "no function for call to 'MyClass::MyClass()'" on the line where I create object2 (MyClass object2;). I'm a total noob, so please don't roast me. XD
main.cpp
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
#include "MyClass.h"
using namespace std;
int main()
{
MyClass obj1(7), obj2(8);
MyClass res = obj1 + obj2;
cout << obj.var;
return 0;
}
MyClass.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#ifndef MYCLASS_H
#define MYCLASS_H
#include <iostream>
using namespace std;
class MyClass
{
public :
int var;
MyClass(int );
void printStuff();
MyClass operator +(MyClass &object);
};
#endif
MyClass.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include "MyClass.h"
MyClass::MyClass(int x):var(x)
{
}
void MyClass::printStuff(){
cout << var << endl;
cout << this ->var << endl;
cout << (*this ).var << endl;
}
MyClass MyClass::operator +(MyClass &object){
MyClass object2;
object2.var = this ->var + object.var;
return object2;
}
Jun 5, 2017 at 8:18am UTC
Hi,
When the compiler sees this:
MyClass object2;
It needs a default constructor, and you don't have one. You can default it:
1 2 3 4 5 6 7 8 9 10
class MyClass
{
public :
int var;
MyClass(int );
MyClass() = default ;
void printStuff();
MyClass operator +(MyClass &object);
};
You have another problem:
cout << obj.var;
obj
is not an object, did you mean
res
?
One should not have public class variables. But you are a beginner, so that is OK for now, but try to avoid that habit very soon.
Good Luck!!
Jun 5, 2017 at 8:36am UTC
Topic archived. No new replies allowed.