开发者

Accessing attributes in C++ through getters-setters

Hi I have background in Java and currently learning C++. In Java it is not advisable to access the instance attributes directly, instance attributes are made private and accessed through get开发者_JAVA百科ters-setters. Is it also advisable to create something like JavaBean in C++? Or is this not a common thing in the C++ lingo? If not, why isn't it advisable to create getters-setters in C++ to access instance attributes?


Don't create getters & setters "by default". Create classes that encapsulate functionality, ideas, algorithms, and so on. Don't make classes that are just a bunch of fields, or if you do, just declare them as structs and admit that's what they are: a bunch of related data tied together without much if any encapsulation (which is fine in many cases).

There are exceptions to every rule, so you'll end up with a handful of getters & setters eventually, but it's not useful in most applications to have more than say one or two per class (very rough guess).

Edit to note: this is just my opinion, and I haven't seen your particular code. Maybe you need hundreds of getters and setters. I just happen to doubt it. I hope the down-voters will offer a comment with some rationale.


Using getters/setters is good advice for any OO driven language so yes, you should protect your internal data members via the properly exposed methods.

A nice byproduct of the C++ language is that those getters/setters will probably end of being inlined which means it's just as fast as accessing the members directly, only more safe.


This is really a general OO design question rather than a language question. Personally, I follow the school of thought "if you have many getters and mutators, your class design has a flaw". Public interface of a class is behavior, not its internal structure or some model of such structure. But of course it's just one point of view, and it is completely language-agnostic.

One thing that C++ discourages are "setters". Since well-written C++ classes are fully functional after the constructor runs (see "Scope-Bound Resource Management") any sort of post-construction "setting" goes against this language's best practices.


Getters/Setters are part of object oriented programming. Since C++ lacks properties (which are the only way to get the equivalent of getters/setters), there's really no other way to get that functionality in C++.

So go for it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜