Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"invalid use of non static member function" What is this?

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;
}
like image 240
Carpetfizz Avatar asked Dec 04 '22 15:12

Carpetfizz


1 Answers

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:

  • create and initialize x and y inside your main and pass them as arguments
  • make add 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:

  • declare int x, y; inside your main
  • read the user input inside the main (the part, where you use cin and cout)
  • pass the x and y as arguments to add like this: addobj.add( x, y );
  • store the result (if needed), like this: int result = addobj.add( x, y );
like image 52
Kiril Kirov Avatar answered Dec 09 '22 15:12

Kiril Kirov