Home > Blockchain >  Here is a C program where it is showing that my function is out of scope. Can someone please tell
Here is a C program where it is showing that my function is out of scope. Can someone please tell

Time:04-12

Question

You have to create a class, named Student, representing the student's details, as mentioned above, and store the data of a student. Create setter and getter functions for each element; that is, the class should at least have following functions:

get_age, set_age get_first_name, set_first_name get_last_name, set_last_name get_standard, set_standard Also, you have to create another method to_string() which returns the string consisting of the above elements, separated by a comma(,). You can refer to stringstream for this.

code:

#include <iostream>
using namespace std;

class Student{
    private:
    int age;
    string fname;
    string lname;
    int std;
    public:
    void set_age(int a){age=a;;}
    void set_fname(string f){fname=f;}    //fname= first name
    void set_lname(string l){lname=l;}    //lname= last name
    void set_std(int s){std=s;}
    
    void get_age(){
        cout<<age<<endl;
    }
    void get_fname(){
        cout<<fname<<endl;
    }
    void get_lname(){
        cout<<lname<<endl;
    }
    void get_std(){
        cout<<std<<endl;
    }  
    
    void to_string(){
        string fl=lname ", " fname;  //fl stand for first and last
        cout<<fl;
    }     
};
int main() {
    
    Student z;
    int a,s;
    string f,l;
    cin>>a;
    z.set_age(a);
    cin>>f;
    z.set_fname(f);
    cin>>l;
    z.set_lname(l);
    cin>>s;
    z.set_std(s);
    
    get_age();
    to_string();
    get_std();      
    return 0;
}

output

Solution.cpp:52:11: error: ‘get_age’ was not declared in this scope
     cout<<get_age();
           ^~~~~~~
Solution.cpp:52:11: note: suggested alternative: ‘getdate’
     cout<<get_age();
           ^~~~~~~
           getdate
Solution.cpp:53:15: error: no matching function for call to ‘to_string()’
     to_string();
               ^

CodePudding user response:

You create one Student instance, z, and call misc. setter member functions on that instance. When you then call the functions to print some of the values you've set, you forgot to tell the compiler which instance you want to print the values for. Since you only have one instance, z, add that before the member functions:

    z.get_age();
    z.to_string();
    z.get_std();

Improvement suggestion: Functions that does not return a value but that prints the value would be better named print-something rather than get-something.

  • Related