First off, you don't need a pointer. Second, you can return a copy (like you do) or a reference (or pointer if you want to stick with that), but there are pros and cons to either approach:
class myclass
{
private:
std::string _name;
public:
myclass() : _name("my name")
{
}
std::string getName1() { return _name; }
std::string& getName2() { return _name; }
const std::string& getName3() const { return _name; }
}
getName1
returns by value. The con is that a copy gets made, which can impact performance, but the returned value is safe to use after the object goes out of scope.
The difference between getName2
and getName3
is that you can use the former to modify the actual member of the class. The con is that the reference can no longer be used if the object goes out of scope, so you'd be left with a dangling reference. The pro is that it's more efficient, since there's no copying involved.
myclass x;
std::string a = x.getName1(); // copy is made
std::string& b = x.getName2(); // no copy
// b is mutable
b = "something else"; //this will modify x._name
const std::string& c = x.getName3; // no copy
// c is const
myclass* y = new myclass;
std::string d = x.getName1(); // copy is made
std::string& e = x.getName2(); // no copy
delete y;
d = "something else"; //legal
e = "something else"; //undefined behavior, e is a dangling reference