3

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.

13
  • 2
    typedef human const struct _human{...} ?
    – Walfrat
    Jun 15, 2017 at 11:29
  • 4
    Does get create a human out of thin air, or just provide read-access to an existing one? In the latter case, return by constant reference. Jun 15, 2017 at 11:32
  • @Deduplicator It creates one out of thin air :)
    – Rakete1111
    Jun 15, 2017 at 11:32
  • @Walfrat That wouldn't work nicely, as typedef (or using) doesn't create a new type. Basically std::decay_t<human> would result in a _human.
    – Rakete1111
    Jun 15, 2017 at 11:34
  • 1
    What are you exactly trying to do ? Forbid another developer to modify the data in memory ? In a persistant storage ? Others ? Why would a (competent enough) developer that need only to read the data to do its job will modify it ? Otherwise check Deduplicator suggestion.
    – Walfrat
    Jun 15, 2017 at 11:42

1 Answer 1

5

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.