I have a function get()
which gets a human
object from somewhere. That is literally the only use of human
, to provide a collection of properties of a human
.
struct human {
std::string first_name;
std::string last_name;
unsigned int age;
std::string location;
};
Doing things like
human user;
user.first_name = "Foo";
doesn't really make sense, because human
is only supposed to be used to read the properties of the object that get()
returns, if that makes sense.
human user = get();
std::cout << user.age << '\n';
It should effectively be a read-only struct. I think it makes sense to enforce this, as if you accidently modify the data, you'll maybe be surprised to see that it changed or has a weird value.
I thought of declaring the properties private
and providing getter functions like first_name()
and age()
. Making every member variable const
is also not ideal, because that would remove the implicit copy constructor.
But I was wondering if there is a better way to achieve this, because those two methods require a lot of boilerplate code.
1 Answer 1
Make the members private but do not make them const. Provide getters but no setters and mark your getters const. now your object is copiable but the client cannot modify the values. You will have to provide all values in the constructor. Boilerplate code is unavoidable here.
You could have your function return a const Human, but that does little more than hint to the developer that it is not to be modified.
get
create ahuman
out of thin air, or just provide read-access to an existing one? In the latter case, return by constant reference.typedef
(orusing
) doesn't create a new type. Basicallystd::decay_t<human>
would result in a_human
.