Error message, "num1 + num2 were not declared in this scope"

0 Alex Dale · April 17, 2015
Hey guys very new to this but had a problem when compiling this program:
error messages: lines 9&10 "warning unused variables num1 + num2" line 13 "num1 + num2 not declared in this scope"
Thanks for helping me out I appreciate it


#include <iostream>
using namespace std;

class ExampleClass{
private:

public:
     void setter(int a,int b){
        int num1 = a;
        int num2 = b;
    }
    int adder(){
        int ans = num1 + num2;
        return ans;

    }
};

int main()
{
    ExampleClass so();
    so.setter(4,5);
    cout << so.adder();
    return 0;
}

Post a Reply

Replies

Oldest  Newest  Rating
0 Franz Schmidt · April 17, 2015
You declaired your variables just for the function setter and not for the complete class
the purpose of a class is to isolate data from the rest of the program.
so you need variables in your class where you can store values and these variables are mostly private

Your corrected code:

#include <iostream>
using namespace std;

class ExampleClass{
   private:
      int num1;
      int num2;
   public:
      void setter(int a,int b){
         num1 = a;
         num2 = b;
      }
      int adder(){
         int ans = num1 + num2;
         return ans;
      }
};

int main(){
   ExampleClass so();
   so.setter(4,5);
   cout << so.adder();
   return 0;
}

see the difference i declaired two private variables and those variables can be set with your setter function and returned by another function. And these variables are encapsuled that means they can ONLY be used inside the class.
0 Harrison Pickering · April 21, 2015
When you declare variables, you have to declare them globally if you want them to be able to be used by another function, class, or object. When you declare them inside of a function like you did in the setter function, they're declared locally inside of the function and can't be seen by any other scope.
  • 1

C++

107,093 followers
About

Used in many types of software including music players, video games, and many large scale applications.

Links
Moderators
Bucky Roberts Administrator