celavek
celavek

Reputation: 5705

C++ struct, public data members and inheritance

Is it ok to have public data members in a C++ class/struct in certain particular situations? How would that go along with inheritance? I've read opinions on the matter, some stated already here

practices on when to implement accessors on private member variables rather than making them public Accessors vs. public members

or in books/articles (Stroustrup, Meyers) but I'm still a little bit in the shade.

I have some configuration blocks that I read from a file (integers, bools, floats) and I need to place them into a structure for later use. I don't want to expose these externally just use them inside another class (I actually do want to pass these config parameters to another class but don't want to expose them through a public API).

The fact is that I have many such config parameters (15 or so) and writing getters and setters seems an unnecessary overhead. Also I have more than one configuration block and these are sharing some of the parameters. Making a struct with all the data members public and then subclassing does not feel right. What's the best way to tackle that situation? Does making a big struct to cover all parameters provide an acceptable compromise (I would have to leave some of these set to their default values for blocks that do not use them)?

Upvotes: 1

Views: 1750

Answers (4)

Stephen
Stephen

Reputation: 49196

I usually write my program config files using Google's protocol buffers. The getters and setters (among many other useful functions) are generated for you, similar to a struct. It also makes editing your config files trivial, allowing for obvious field naming and grouping.

http://code.google.com/apis/protocolbuffers/

Upvotes: 3

Daniel Earwicker
Daniel Earwicker

Reputation: 116674

If you have a data structure that isn't intended to have behaviour but genuinely is nothing more than a pure struct in the C sense, particularly if each instance of it is only used internally to the implementation of other "proper" classes, then it is fine to make it a struct and have public fields. After all, as you've pointed out, once you've given it get/set accessor functions for every field then you're back to the logical equivalent of public data anyway.

Upvotes: 4

JUST MY correct OPINION
JUST MY correct OPINION

Reputation: 36107

If the class you want accessing the internals inherits from your main class, setting things protected will do what you like. If you want another unrelated class to have access you have to make them friends.

Upvotes: 1

Paul R
Paul R

Reputation: 212979

It sounds like you just need to make these members protected - that way they can be accessed by derived classes but are not public.

Upvotes: 0

Related Questions