Gulshan
Gulshan

Reputation:

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

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?

Upvotes: 40

Views: 23845

Answers (6)

user3541285
user3541285

Reputation: 11

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:

};

Upvotes: 1

kgiannakakis
kgiannakakis

Reputation: 104168

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.

Upvotes: 10

unwesen
unwesen

Reputation:

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.

Upvotes: 31

JimDaniel
JimDaniel

Reputation: 12703

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.

Upvotes: 2

Jared
Jared

Reputation: 39877

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.

Upvotes: 2

Dominic Rodger
Dominic Rodger

Reputation: 99751

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.

Upvotes: 39

Related Questions