EDIT: thanks for all the speedy responses, I have a much better understanding of this concept now. Also, I'll try to make my error messages more clear next time. EDIT: updated with my newest code. the error happens on line 18. Also, I'm beginning to wonder if my latest issue has to do with the original class itself?
I'm trying to teach myself classes and objects in C++. I did it once by just declaring a void
function, outputting something on the screen, calling the object in main and everything worked fine.
Now, I wanted to expand upon this and make a simple addition thing. However, I get a couple errors on Code Blocks:
error: invalid use of non-static member function 'int Addition::add(int, int)'
error: no matching function for call to 'Addition::add()'
Here's my code:
#include <iostream>
using namespace std;
class Addition {
public:
int add (int x, int y) {
int sum;
sum=x+y;
return sum;
}
};
int main()
{
int num1;
int num2;
int ans=addobj.add(num1,num2);
Addition addobj;
addobj.add(num1,num2);
cout<<"Enter the first number you want to add"<<endl;
cin>>num1;
cout<<"Enter the second number you want to add"<<endl;
cin>>num2;
cout<<"The sum is "<<ans<<endl;
}
One of the most important things, a developer should learn to do is to read compiler's messages. It's clear enough:
error: no matching function for call to 'Addition::add()'
Your function in your class is
int add (int x, int y)
it takes 2 arguments and you pass none:
addobj.add();
You have 2 options:
x
and y
inside your main
and pass them as argumentsadd
without parameters, create x
and y
inside add
's body, as their values are taken from user input.In this case, as the function's name is add
, I'd chose the first option:
int x, y;
inside your main
main
(the part, where you use cin
and cout
)x
and y
as arguments to add
like this: addobj.add( x, y );
int result = addobj.add( x, y );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With