Search code examples
c++object

Variables not declared in the scope?


I get these error messages with my program ...

Error: 'A' was not declared in the scope

Error: 'a' was not declared in the scope

Error: 'UIClass' was not declared in the scope

Error: 'AgeObject' was not declared in the scope

Error: Expected ';' before 'NameObject'

Error: 'NameObject' was not declared in the scope

Error: Expected ';' before 'ResultObject'

Error: 'ResultObject' was not declared in the scope

#include <iostream>
#include <string>
 using namespace std;

class UI{

public:

void Age(){
int a;
cout << "Age?" << endl;
cin >> a;}

void Name(){
string A;
cout << "Name" << endl;
cin >> A;}

void Results(){
cout << "Your name is " << A << "and you are " << a << " years old." << endl;
 }


};


int main ()

{

cout << "Enter Your Name and Age?" << endl;

UIClass; AgeObject;
AgeObject.Age();

UIClass NameObject;
NameObject.Name();

UIClass ResultObject;
ResultObject.Results();

return 0;

}

Solution

  • So in your code, in the Results method, you're trying to access variables that are not declared in there.

    So you have:

    void age()
    {
        // does stuff with age
    } 
    
    void name()
    {
        // does stuff with name
    }
    

    The variables only exist in these methods. So when you try to get to them from Results() you'll get an "Out of scope" error.

    So what you could do is declare four additional methods, setAge, setName which will take in arguments as follows:

    class UI
    {
        private:
            int age;
            string name;
    
        public:
            void setAge(int ag)
            {
                age = ag;
            }
    
            int getAge()
            {
                return age;
            }
    

    Then you'd change your void age() method to something like this:

    void age()
    {
        // Do the stuff you've already done
        setAge(a);
    }
    

    Then when you try to get the output done:

    cout << "Your name is " << getName() << " and you are " << getAge() << " years old." << endl;
    

    Which ever book you're using, they really should have explained this sort of stuff. If not, I'd get a new one. This is one of the most basic programs you'll ever write in C++.

    I've not given you the complete answer, but this should encourage you and give you a starting point. Hope it all helps.

    Happy coding.