Question

I want to get the value of a private string name in sampleclass.

#include <iostream>
#include <string>

using namespace std;

class sampleclass {
public:
    int getname(){ //this is my attempted getter
    string x = name;
    }
private:
    string name= "lance"; //this is the private I want returned by value

};

int main(){    
    sampleclass object;
    cout << object.getname();
}
Was it helpful?

Solution

You need to return a string in your getname() function, since your name variable is a string

string getname() {
    return name;
}

By doing so, you get a new instance of std::string as an rvalue result, which is then outputted to the screen in your main function.

As another thought, not related to your problem though: there is no problem in using a namespace globally for small programs like this one, but you should try to not get used to it because it can lead to name conflicts within different namespaces in bigger projects.

OTHER TIPS

#include <iostream>
#include <string>

using namespace std;

class sampleclass{
public:
    sampleclass() : name("lance") { }
    string getname(){ // return a string (not an int)
       return name;
    }
private:
    string name;

};
int main(){

    sampleclass object;
    cout << object.getname();

}

g++ test.cpp && ./a.out lance

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top