firstName is a string, so you don't have to worry about overflowing a buffer.
getFirstName() returns a const reference to the string. By returning a reference, you aren't making a copy of the string. By making the reference const, you prevent the caller from changing the underlying string (at least they can't without some casting gymnastics). Finally, my making the method itself const, you say that it can be called on a const object.
Here are four different versions (and more variations are possible)
Think about it, and choose one that is the most appropriate for the specific use case.
Hint: when in doubt, favour xxxx_3
class xxxx_1
{
// may not be so good; the fixed size for a name is not very flexible
// good: standard layout type, trivially copyable etc.
staticconstexpr std::size_t NAMESZ = 20 ;
char fname[NAMESZ] {} ;
// ...
public:
// not so good; unencapsulated interface exposes the implementation
// (change in implementation may break the interface)
constexprconstchar* first_name() const { return fname ; }
// ...
};
class xxxx_2
{
// may not be so good; the fixed size for a name is not very flexible
// good: standard layout type, trivially copyable etc.
staticconstexpr std::size_t NAMESZ = 20 ;
char fname[NAMESZ] {} ;
// ...
public:
// good; encapsulated interface does not expose the implementation
std::string first_name() const { return fname ; }
// ...
};
class xxxx_3 // favour this as the default choice
{
// good, flexible size for name
std::string fname ;
// ...
public:
// good; encapsulated interface does not expose the implementation
std::string first_name() const { return fname ; }
// ...
};class xxxx_4
{
// good, flexible size for name
std::string fname ;
// ...
public:
// not so good, un-encapsulated interface exposes the implementation
// (change in implementation would break the interface)
// however, the performance would be better (avoid copying the string)
// (in general, treat performance as a constraint rather than a goal;
// so do this if and only if this performance improvement is a requirement)
const std::string& first_name() const { return fname ; }
// ...
};