Why defining private members below public members in C++?

Why defining private members below public members in C++?

梦中楼上月下 发布于 2021-11-30 字数 422 浏览 891 回复 6 原文

In C++ sometimes in class definition public members are declared at first and privates later. But the variables or data members are normally private and used by the public methods. So, in this case variables are used but not even declared yet. Thus the code become difficult to understand. But I found renowned programmers, sites or books to declare the private members later. Does anybody knows what is the reason?

如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。

扫码加入群聊

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

吹泡泡o 2022-06-07 6 楼

Agreed. Private members should be declared at bottom. The only good reason to declare private members first that i found, is when a function needs to get or return a custom data type, like: vector . The compiler will ask you about what kind of data is that.

But even, in that case i preffer to do:

{
private: /// advicing ofc theres more private below!
   earlier declare just of the type

public:


private:

};
梦在夏天 2022-06-07 5 楼

We are like opposites: My Question

My reasoning is that when you are becoming familiar with a class it is more beneficial to first get introduced to the public interface then go deeper into the private members when you need to. If you start by looking at the private members, you have no context how they are used.

黯淡〆 2022-06-07 4 楼

Normally private members don't matter. If I'm looking at a class to determine how to use it somewhere else in code I don't care about it's internals so put private members at the bottom since i don't need to know about them. If I"m modifying a class then I'll take the time to find the private members and know they'll be at the bottom instead of having to skim the entire class.

鸩远一方 2022-06-07 3 楼

Private members and implementation should be hidden from the header file. Putting the private member definitions at the bottom is a quick way to do so. Perhaps it is better to use the Pimpl idiom and hide the private part of your class in an internal struct.

猫七 2022-06-07 2 楼

We read text from top to bottom, so the most relevant information should be at the top. In a class definition, that's the public interface.

糖果控 2022-06-07 1 楼

I do things that way round since users of my class don't care about the private members, they're interested in the public API (i.e. how to use my class).

Also, in header files I'm generally just declaring member functions, rather than defining them, so I'm not accessing any private members anyway.