How should I order the members of a C++ class?

后端 未结 15 1773
Happy的楠姐
Happy的楠姐 2020-12-04 11:50

Is it better to have all the private members, then all the protected ones, then all the public ones? Or the reverse? Or should there be multiple private, protected and pub

15条回答
  •  再見小時候
    2020-12-04 12:37

    As always, write your code for humans first. Consider the person who will be using your class and place the most important members/enums/typedefs/whatever to them at the top.

    Usually this means that public members are at the top since that's what most consumers of your class are most interested in. Protected comes next followed by privates. Usually.

    There are some exceptions.

    Occasionally initialisation order is important and sometimes a private will need to be declared before a public. Sometimes it's more important for a class to be inherited and extended in which case the protected members may be placed higher up. And when hacking unit tests onto legacy code sometimes it's just easier to expose public methods - if I have to commit this near-sin I'll place these at the bottom of the class definition.

    But they're relatively rare situations.

    I find that most of the time "public, protected, private" is the most useful to consumers of your class. It's a decent basic rule to stick by.

    But it's less about ordering by access and more about ordering by interest to the consumer.

提交回复
热议问题