Best practice: ordering of public/protected/private within the class definition?

后端 未结 10 1319
遥遥无期
遥遥无期 2020-12-12 14:34

I am starting a new project from the ground up and want it to be clean / have good coding standards. In what order do the seasoned developers on here like to lay things out

10条回答
  •  粉色の甜心
    2020-12-12 14:35

    The best practice is to be consistent.

    Personally, I prefer putting public methods first, followed by protected methods, following by private methods. Member data should in general always be private or protected, unless you have a good reason for it not to be so.

    My rationale for putting public methods at the top is that it defines the interface for your class, so anyone perusing your header file should be able to see this information immediately.

    In general, private and protected members are less important to most people looking at the header file, unless they are considering modifying the internals of the class. Keeping them "out of the way" ensures this information is maintained only on a need to know basis, one of the more important aspects of encapsulation.

提交回复
热议问题