-2

Can anyone tell me why i get the error "name was not declared in the scope when running this?

Thanks.

class lrn11_class{
    public:
        void setName(string x){
            name = x;
        }
        string getName(){
            return name;
        }
    private:
        string lrn11_name;
};

int main()
{
    lrn11_class lrn11_nameobject;
    lrn11_nameobject.setname("Zee");
    cout << lrn11_nameobject.getname() << endl;
return 0;
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190

2 Answers2

5

This should work - see comments (BTW use std:: - Why is "using namespace std" considered bad practice?)

#include <iostream>
#include <string>

class lrn11_class{
    public:
        void setName(const std::string& x){  // Potentially saves copying overhead
            name = x;
        }
        std::string getName() const { // Look up const and its uses
            return name;
        }
    private:
        std::string name; // - Used: string lrn11_name; but functions use name!
};

int main()
{
    lrn11_class lrn11_nameobject;
    lrn11_nameobject.setName("Zee"); // Fixed typo
    std::cout << lrn11_nameobject.getName() << std::endl; // Ditto
    return 0;
}
Community
  • 1
  • 1
Ed Heal
  • 59,252
  • 17
  • 87
  • 127
0
  1. You have declare lrn11_name as a member varible for this class. But in set and get functions you are using name.
  2. Other than than you need to call functions as you have defined. so instead of :- lrn11_nameobject.setname("Zee"); cout << lrn11_nameobject.getname() << endl;

You have to use following code :-

lrn11_nameobject.setName("Zee");
cout << lrn11_nameobject.getName() << endl;
  1. Make sure that

    #include <iostream>
    using namespace std;
    

should be included.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190