Are get and set functions popular with C++ programmers?

前端 未结 14 779
忘掉有多难
忘掉有多难 2020-11-28 23:12

I\'m from the world of C# originally, and I\'m learning C++. I\'ve been wondering about get and set functions in C++. In C# usage of these are quite popular, and tools like

14条回答
  •  一个人的身影
    2020-11-28 23:58

    [edit] It seems I need to emphasize that setters need to validate parameters and enforce invariants, so they are usually not as simple as they are here. [/edit]


    Not with all, because fo the extra typing. I tend to use them much more often now that Visual Assist gives me "encapsulate field".

    The legwork is not more if you implement just the default setters / getters inline in the class declaration (which I tend to do - more complex setters move to the body, though).

    Some notes:

    constness: Yes, the getter should be const. It is no use to make the return value const, though, if you return by value. For potentially complex return values you might want to use const & though:

    std::string const & GetBar() const { return bar; } 
    

    Setter chaining: Many developers like to modify the setter as such:

    Foo & SetBar(std::string const & bar) { this->bar = bar; return *this; }
    

    Which allows calling multiple setters as such:

    Foo foo;
    foo.SetBar("Hello").SetBaz("world!");
    

    It's not universally accepted as a good thing, though.

    __declspec(property): Visual C++ provides this non-standard extension so that callers can use property syntax again. This increases legwork in the class a bit, but makes caller code much friendlier looking.


    So, in conclusion, there's a little bit of more legwork, but a handful of decisions to make in C++. Typical ;)

提交回复
热议问题