I have been programming in C# for a while and now I want to brush up on my C++ skills.
Having the class:
class Foo
{
const std::string& name
Even though the name is immutable, you may still want to have the option of computing it rather than storing it in a field. (I realize this is unlikely for "name", but let's aim for the general case.) For that reason, even constant fields are best wrapped inside of getters:
class Foo {
public:
const std::string& getName() const {return name_;}
private:
const std::string& name_;
};
Note that if you were to change getName()
to return a computed value, it couldn't return const ref. That's ok, because it won't require any changes to the callers (modulo recompilation.)