Is it confusing to omit the "private" keyword from a class definition? - c++

I recently removed a private specified from a class definition because it was at the top, immediately after the class keyword:
class MyClass
{
private:
int someVariable;
// ...
I thought that it was redundant.
A coworker disagreed with this, saying that it effectively "hid" the private nature of the data.
Most of our legacy code explicitly states the access specifiers, and usually intermingles them inconsistently throughout the definition. Our classes also tend to be very large.
I'm trying to make my newer classes small enough so that my class definitions are similar to:
class MyClass
{
// 3-4 lines of private variables
protected:
// 3-4 lines of protected functions
public:
// public interface
}
which would allow omission of the redundant access specifier while (hopefully) keeping the private members close enough to the struct/class keyword for reference.
Am I sacrificing readability for brevity, or are the struct/class keywords sufficient?

If you are very familiar with all the default access levels then you probably won't see any difference in readability if you omit them whenever they are unnecessary.
However you will find that many people you work with aren't 100% sure about the default access level rules. This is especially true for people who regularly use different languages where the rules might be different in the different languages. As a result they might get the rules mixed up.
Always specifying the access is the safest option, if only to help the people you work with have one less thing to worry about.

Technically, "private" at the beginning of a class or "public" at the beginning of a struct is redundant, however I personally do not like the intermingled style but rather like to order by access and by declaration type. Readability is more important to me as brevity. So I would have a section "public methods", "private attributes" and so on and I format them as such:
class A
{
public: // methods
private: // methods
private: // attributes
};
This of course also generates redundant access declarations. Also, I like putting "public" stuff first because that's most important to users of the class. So, I need an access specifier at the beginning anyway. And I put "public" at the beginning of a "struct" as well.

While incorrect — strictly speaking — your coworker has a point; an experienced C++ programmer doesn't need the default access spoon fed to them, but a less experienced programmer might.
More to the point: most code I've seen and worked with puts the public stuff first, which renders the question moot.

I personally think that being very explicit is generally a good thing. The extra line of code is a small price to pay for the clarity that it adds.
In addition, it allows you to easily reorder your members (private must be first if it's omitted, which is really "backwards" from what you'd expect). If you reorder, and there's a private: modifier in place, other developers are less likely to break something.

Personally, I think it is much more clear with the private keyword included and I would keep it. Just to make sure it is private and everyone else knows it as well.
But I assume this is of personal taste and different for everyone.

I almost always arrange my classes backwards from yours: Public interface first, any protected interface second, and private data last. This is so that users of my classes can simply look at the public and protected interfaces at the top and need not look at the private data at all. Using that order then there's no possible redundancy and the question become moot.
If you prefer to organize yours in the way you outlined, I believe being explicit far outweighs the gain one of line of code. This way it's completely obvious to code readers what the intention is (for example if you change a struct to a class or the reverse at any point).

I often see the public part of a class/struct definition first, thus the protected/private stuff comes later.
It make sense, as a header file is meant to show what the public interface for your class actually is.
At the same time, why not use struct? public by default...
Still, it never hurts to be extra clear in your code as to what is going on. This is the same reason why I avoid the ternary operator and still put in the braces for an if statement that only has one line of code after it.
The most pressing issue though, is what are your companies code standards? Like them or not, that's the standard style you should do for your company, if they say do it such a way, you do it such a way.

Related

Is acceptable usage access specifiers before each member of class in C++

I write some code c++
public class SomeClass
{
private:
int m_CurrentStatus;
int m_PreviouseStatus;
public:
int get_CurrentStatus() { return m_CurrentStatus; }
int get_PreviouseStatus() { return m_PreviouseStatus; }
}
in c# style
public class SomeClass
{
private: int m_CurrentStatus;
private: int m_PreviouseStatus;
public: int get_CurrentStatus() { return m_CurrentStatus; }
public: int get_PreviouseStatus() { return m_PreviouseStatus; }
}
Such usage access specifiers before each member of class is acceptable?
Or can trouble compiler spend more time for compilation or other effects?
Code successfully compiled with no warning.
What you describe is legal C++.
The impact on compilation times will depend on the compiler. However, practically, you will probably be hard pressed to detect any difference of compilation times.
There may be either impact or benefit on code readability - i.e. ability of a human to understand what is going on. Generally, people prefer "sections" (e.g. the declaration of several members following a single access modifier (public, private, or protected)) quite well, as long as the sections don't get too large (e.g. fill more than a screen when editing the code). So doing it the way you are may be unpopular with other developers. This is highly subjective though - different people will have different preferences. However, if you find other people objecting to your approach, listen to them - unless you are happy to be unpopular with other team members, lose jobs, etc etc.
There may or may not be an impact on layout of data members in the class. Different versions of the C++ standard make different guarantees but there are considerable freedoms for compilers to lay out classes differently. If you are writing code that relies on (or tests for) particular class layout (order of data members, offsets, etc) you might observe a difference. Or you might not. However, these things are permitted to vary between implementations (compilers) anyway so writing code that relies on specific layouts is often a bad idea anyway.
It's legal syntax and shouldn't upset the compiler, you can have as many public and private blocks as you want. I don't see that it's an improvement syntactically though.
It's certainly legal and free from compile time penalties to put access specifiers before each and every class member. You could also put 50 semicolons at the end of every line. It simply isn't canonical C++.
It is Legal and also very correct. You won't use an object oriented language if you want to have your members public. A basic usage of object oriented programming is information hiding.
The only thing that can trouble compiler in your case(in a matter of time), is that your function block is inside the class.
What do I mean?
If you have a main.cpp and a class.h , and your functions are declared and defined inside class.h, your compilation will take a little longer, rather than if your function body was in functions.cpp
It's perfectly legal syntax for C++,
except for the public keyword before class
and the missing semicolon (;) after the closing curly bracket of class.
BUT I've never seen something like that, I suppose it's surely not commonly used and, in my opinion, it adds nothing to code readability (on contrary, I personally find it more cumbersome to read).

Breaking encapsulation in C++

Is there any way to break a class enacapsulation? A friend keyword can be used for the same. If i use a friend function or class, then I can access all public and private data members of it. I want to know is there any other way for the same.This is one of my interview question, I have googled much, but not found convincing answers, hope someone could help me. Thanks in advance.
I would say that friend does not break encapsulation. See https://isocpp.org/wiki/faq/Friends#friends-and-encap
Now let's ignore the issue of what "encapsulation" actually means. It is generally possible to access private members using a template specialization hack. The basic idea, for when the class has a member template, is explained in http://www.gotw.ca/gotw/076.htm.
This approach can be extended to access any private data member or private member function of a class, even if the class contains no templates. See http://bloglitb.blogspot.com/2010/07/access-to-private-members-thats-easy.html and http://bloglitb.blogspot.com/2011/12/access-to-private-members-safer.html.
It depends what you men by breaking encapsulation. Generally all operations perfomed on class members outside of the class may be considered as breaking class encapsulation.
For example getters that return non-const reference may be considered as breaking encapsulation because they expose private class members in such way, that you can freely modify them and there is little controll over this process.
Yes, there are. If the class has a public template member function, you can specialize it for a type of yours, and do whatever you want inside it.
There is a book by Herb Sutter that discusses this and other possibilities. IIRC, this is the only one that has standard conformance.
Anything you can do in C is also possible in C++.
You can take a pointer to the class, cast it to char *, treat it as an array and start overwriting the memory with whatever you like, adjusting all the private member variables. You can do this even if someone is using the pImpl idiom to try to hide those variables from you.
Doing things like that is generally a sign of code smell and great evil... the road to hell is paved with good intentions, they say. :)
But in general, when you make a variable or a function private, you are really saying "please don't touch this". The next programmer to come along can always do more or less whatever they want, without modifying your class definition. The features "private" and "public" really are just statements of intent, and a way to inconvenience someone who wants to go against your intent, and a guide to someone who isn't sure where they should be looking for something. It's like the locks on the door to your house -- anyone who is determined can get in anyways.
This is not for the meek and only use in extreme and temporary situations.
The following 3rd party header had private fields I needed to alter.
#define private public
#include "controllers/incremental_mapper.h"
#undef private
The was an experiment and if it worked I would modify the library properly which I knew would be a lot of work.

Should I use public or private variables?

I am doing a large project for the first time. I have lots of classes and some of them have public variables, some have private variables with setter and getter methods and same have both types.
I decided to rewrite this code to use primarily only one type. But I don't know which I should use (variables which are used only for methods in the same object are always private and are not subject of this question).
I know the theory what public and private means, but what is used in the real world and why?
private data members are generally considered good because they provide encapsulation.
Providing getters and setters for them breaks that encapsulation, but it's still better than public data members because there's only once access point to that data.
You'll notice this during debugging. If it's private, you know you can only modify the variable inside the class. If it's public, you'll have to search the whole code-base for where it might be modified.
As much as possible, ban getters/setters and make properties private. This follows the principle of information hiding - you shouldn't care about what properties a class has. It should be self-contained. Of course, in practice this isn't feasible, and if it is, a design that follows this will be more cluttered and harder to maintain than one that doesn't.
This is of course a rule of thumb - for example, I'd just use a struct (equivalent with a class with public access) for, say, a simple point class:
struct Point2D
{
double x;
double y;
};
Since you say that you know the theory, and other answers have dug into the meaning of public/private, getters and setters, I'd like to focus myself on the why of using accessors instead of creating public attributes (member data in C++).
Imagine that you have a class Truck in a logistic project:
class Truck {
public:
double capacity;
// lots of more things...
};
Provided you are northamerican, you'll probably use gallons in order to represent the capacity of your trucks. Imagine that your project is finished, it works perfectly, though many direct uses of Truck::capacity are done. Actually, your project becomes a success, so some european firm asks you to adapt your project to them; unfortunately, the project should use the metric system now, so litres instead of gallons should be employed for capacity.
Now, this could be a mess. Of course, one possibility would be to prepare a codebase only for North America, and a codebase only for Europe. But this means that bug fixes should be applied in two different code sources, and that is decided to be unfeasible.
The solution is to create a configuration possibility in your project. The user should be able to set gallons or litres, instead of that being a fixed, hardwired choice of gallons.
With the approach seen above, this will mean a lot of work, you will have to track down all uses of Truck::capacity, and decide what to do with them. This will probably mean to modify files along the whole codebase. Let's suppose, as an alternative, that you decided a more theoretic approach.
class Truck {
public:
double getCapacity() const
{ return capacity; }
// lots of more things...
private:
double capacity;
};
A possible, alternative change involves no modification to the interface of the class:
class Truck {
public:
double getCapacity() const
{ if ( Configuration::Measure == Gallons ) {
return capacity;
} else {
return ( capacity * 3.78 );
}
}
// lots of more things...
private:
double capacity;
};
(Please take int account that there are lots of ways for doing this, that one is only one possibility, and this is only an example)
You'll have to create the global utility class configuration (but you had to do it anyway), and add an include in truck.h for configuration.h, but these are all local changes, the remaining of your codebase stays unchanged, thus avoiding potential bugs.
Finally, you also state that you are working now in a big project, which I think it is the kind of field in which these reasons actually make more sense. Remember that the objective to keep in mind while working in large projects is to create maintainable code, i.e., code that you can correct and extend with new functionalities. You can forget about getters and setters in personal, small projects, though I'd try to make myself used to them.
Hope this helps.
There is no hard rule as to what should be private/public or protected.
It depends on the role of your class and what it offers.
All the methods and members that constitute the internal workings of
the class should be made private.
Everything that a class offers to the outside world should be public.
Members and methods that may have to be extended in a specialization of this class,
could be declared as protected.
From an OOP point of view getters/setters help with encapsulation and should therefore always be used. When you call a getter/setter the class can do whatever it wants behind the scenes and the internals of the class are not exposed to the outside.
On the other hand, from a C++ point of view, it can also be a disadvantage if the class does lots of unexpected things when you just want to get/set a value. People like to know if some access results in huge overhead or is simple and efficient. When you access a public variable you know exactly what you get, when you use a getter/setter you have no idea.
Especially if you only do a small project, spending your time writing getters/setters and adjusting them all accordingly when you decide to change your variable name/type/... produces lots of busywork for little gain. You'd better spend that time writing code that does something useful.
C++ code commonly doesn't use getters/setters when they don't provide real gain. If you design a 1,000,000-line project with lots of modules that have to be as independent as possible it might make sense, but for most normal-sized code you write day to day they are overkill.
There are some data types whose sole purpose is to hold well-specified data. These can typically be written as structs with public data members. Aside from that, a class should define an abstraction. Public variables or trivial setters and getters suggest that the design hasn't been thought through sufficiently, resulting in an agglomeration of weak abstractions that don't abstract much of anything. Instead of thinking about data, think about behavior: this class should do X, Y, and Z. From there, decide what internal data is needed to support the desired behavior. That's not easy at first, but keep reminding yourself that it's behavior that matters, not data.
Private member variables are preferred over public member variables, mainly for the reasons stated above (encapsulation, well-specified data, etc..). They also provide some data protection as well, since it guarantees that no outside entity can alter the member variable without going through the proper channel of a setter if need be.
Another benefit of getters and setters is that if you are using an IDE (like Eclipse or Netbeans), you can use the IDE's functionality to search for every place in the codebase where the function is called. They provide visibility as to where a piece of data in that particular class is being used or modified. Also, you can easily make the access to the member variables thread safe by having an internal mutex. The getter/setter functions would grab this mutex before accessing or modifying the variable.
I'm a proponent of abstraction to the point where it is still useful. Abstraction for the sake of abstraction usually results in a cluttered mess that is more complicated than its worth.
I've worked with complex rpgies and many games and i started to follow this rule of thumb.
Everything is public until a modification from outside can break something inside, then it should be encapsulated.(corner count in a triangle class for example)
I know info hiding principles etc but really don't follow that.
Public variables are usually discouraged, and the better form is to make all variables private and access them with getters and setters:
private int var;
public int getVar() {
return var;
}
public void setVar(int _var) {
var = _var;
}
Modern IDEs like Eclipse and others help you doing this by providing features like "Implement Getters and Setters" and "Encapsulate Field" (which replaces all direct acccesses of variables with the corresponding getter and setter calls).

Accessing private members [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Is it appropriate to access a class' private members by casting it to a void pointer and then to a struct?
I don't think I have permissions to modify the class that contains the data members that I need to access. I don't want to take a risk accessing the data members in an indirect way if it is not ethical.
EDIT: Had to edit this further... I am pretty sure the class wouldn't be modified, so it's ok to that extent... my only concern is, if the person who coded that class gets to know of this, it might not go down well with him :(.
Let's not consider ethics for a moment. Let's consider the standard.
What you are proposing to do is nonstandard. See section 9.2, clause 12 of the standard. "The order of allocation of nonstatic members separated by an access-specifier is unspecified." Therefore, if you have a class with private members, and a struct with no private members, the standard does not guarantee that the members will be in the same order.
Therefore, if your hack works, it works only by accident, that the compiler writers happened to do it that way. There is no guarantee that it will work on another compiler, a later version of the same compiler, or with different class layouts.
Not to mention that, if you don't have authority to modify the class (say, to provide a simple accessor function), you probably don't have authority to object if any implementation detail in the class changes. (One of the ideas behind public and private is to distinguish what is promised from what is freely changeable.) Therefore, the layout may change, or the member might come to mean something different, or be removed altogether.
Herb Sutter wrote a Guru of the Week column on this issue.
Oh, as far as the ethics go? If you really, really have to do something like this, and you can't get out of it, document it very carefully. If your coding standards have some sort of procedure to flag nonstandard behavior, use them. If not, be very careful to note it in a way it won't be overlooked when something goes wrong.
I'm not sure that "ethics" really come into it. It busts the heck out of encapsulation though.
EDIT: I would almost never accept this if I were performing a code review. You'd have to work really hard to convince me there's no way of designing around the need for this. It's possible you'd succeed, but there'd have to be major warnings all over the place, and rock hard unit tests to make sure that if anything changed to break it, you'd know quickly.
I've just added an entry to my blog that shows how it can be done in a completely conforming way. Here is an example on how you use it for the following class
struct A {
private:
int member;
};
Just declare a tag name and instantiate a robber like the following example shows (my post shows the implementation of the robber). You can then access that member using a member pointer
struct Amem { typedef int type; };
template class rob<Amem, &A::member>;
int main() {
A a;
a.*result<Amem>::ptr = 42; // Doh!
}
But actually, this doesn't show that c++'s access rules aren't reliable. The language rules are designed to protect against accidental mistakes - if you try to rob data of an object, the language by-design does not take long ways to prevent you.
The above is a way to access private and protected members in a conforming way. This one is another way to access protected members in a Standard conforming way. The basic idea is to use a member pointer
std::deque<int> &getAdapted(std::stack<int> &s) {
struct voyeur : stack<int>
{ using stack<int>::c; };
return s.*(&voyeur::c);
}
int main() {
std::stack<int> s;
std::deque<int> &adapted = getAdapted(s);
output(adapted); // print the stack...
}
No casting or type punning involved. It takes a pointer to a protected member of std::stack<int> through a class derived from it where that member name is public, so the compiler allows this. Then it uses it on a std::stack<int> object, which is allowed too.
I have had this happen to me since there was a very crappy source control system in place where for old versions of the application making changes to header files was pretty much impossible.
If some cases you just need to do a hack.
In the source file from which you need to access the private data member you can put in this as a first line:
#define private public
#define protected public
and access anything you want.
No. What you are doing is Pure Evil.
"Never say never". I'm sure somewhere in the universe, there's a situation that will force you to have to do this...
But I certainly would cringe if I had to do it. You truly need get lots of opinions on your situation before pulling the trigger. Can you describe your specific situation and maybe we could see if it makes sense or what better alternatives might exist?
In response to comment/question--
Define "permissions" -- institutional permission? That sounds like not a programming problem, but something to talk to whoever is asserting said permission. Maybe this is more of a political issue than a technical one? Again, I think we need more specifics--even if it was somewhat about the politics of the situation. That may or may not be deemed out of scope for the website, however.
If you feel the urge to do this, forget casting - just modify the class declaration in the header file:
class A {
private:
int x;
};
change that to:
class A {
public:
int x;
};
and you are good to go. Well, perhaps "good" is not quite the right word.
It's ethical, but it's usually lots of dirty code neighbouring with undefined behaviour and unportability. Do it only if you absolutely have to.
Ah, abstraction - you can't live without it and yet it is so painful to deal with sometimes :)
Anyway, ethics aside, what if the "owner" of the class decides to change the internal implementation, or simply reverses the order of the private data members?
The only "ethical" problem is what you are doing to the poor bastard who is going to have to figure out and maintain your code.
Private members are just that. He may, and most likely will, one day change that member. When that happens, you might not even notice as there most likely will still be memory there, just not the member you were expecting. Damn near any nearly impossible thing you can imagine might then start happening when your code is run. How is anybody ever going to be able to debug that?
Simple answer: No.
It is not ethical and it will turn into a maintenance nightmare at some point. The internal private members of a library can change and break your code. Developers of the library do not need to know (nor want to) that you are violating the encapsulation.
Classes usually have invariants over their methods that some times will not be documented, but accessing and changing the values from the outside can break those invariants. As an example, if you change the reserved space in a vector for a higher value, the vector will not allocate new space until it has filled the existing and that won't happen before hitting unallocated memory: your application will crash.
If the attribute is private, it is not for you to use it, only for the class itself or the the class' friends that know about the member, how to use it, how not to break it. If the programmer wanted you to change the field, it would be public.
I assume that this class is part of project you are working on.
There is one ethical problem here:
If in your company you see ownership of code as sacrum. Or worst you are disallowed to modify code that is not yours. Yes You may hurt feeling of person that maintain that class. Or angry him if his salary is related to his code.
so best is just to ask him for any help, and few suggestions eg. add getter function or change private to public - all based on your intuition of using that new code.
Hack that you have mention is really bed practice. If cant modify that code and maintainer dont wont to change anything. Consider using adapter design pattern.

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

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 public labels so that the operations can be kept separate from the constructors and so on? What issues should I take into account when making this decision?
I put the public interface first, but I didn't always do this. I used to do things backwards to this, with private, then protected, then public. Looking back, it didn't make a lot of sense.
As a developer of a class, you'll likely be well acquainted with its "innards" but users of the class don't much care, or at least they shouldn't. They're mostly interested in what the class can do for them, right?
So I put the public first, and organize it typically by function/utility. I don't want them to have to wade through my interface to find all the methods related to X, I want them to see all that stuff together in an organized manner.
I never use multiple public/protected/private sections - too confusing to follow in my opinion.
Google favors this order: "Typedefs and Enums, Constants, Constructors, Destructor, Methods, including static methods, Data Members, including static data members."
Matthew Wilson (Safari subscription required) recommends the following order: "Construction, Operations, Attributes, Iteration, State, Implementation, Members, and my favorite, Not to be implemented."
They offer good reasons, and this kind of approach seems to be fairly standard, but whatever you do, be consistent about it.
Coding style is a source for surprisingly heated conversation, with that in mind I risk providing a different opinion:
Code should be written so it is most readable for humans. I complete agree with this statement that was given here several times.
The deviation is which roll are we taking about.
To help the user of the class understand how to use it, one should write and maintain proper documentation. A user should never be needing to read the source code to be able to use the class. If this is done (either manually or using in-source documentation tools) then the order in which public and private class members are defined in the source does not matter for the user.
However, for someone who needs to understand the code, during code review, pull request, or maintenance, the order matters a great deal - the rule is simple:
items should be defined before they are used
This is neither a compiler rule not is it a strictly public v.s. private rule, but common sense - human readability rule. We read code sequentially, and if we need "juggle" back and forth every time we see a class member used, but don't know its type for example, it adversely affects the readability of the code.
Making a division strictly on private v.s. public violates this rule because private class members will appear after they have been used in any public method.
It's my opinion, and I would wager a guess that most people would agree, that public methods should go first. One of the core principles of OO is that you shouldn't have to care about implementation. Just looking at the public methods should tell you everything you need to know to use the class.
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.
I usually define first the interface (to be read), that is public, then protected, then private stuff. Now, in many cases I go a step forward and (if I can handle it) use the PIMPL pattern, fully hiding all the private stuff from the interface of the real class.
class Example1 {
public:
void publicOperation();
private:
void privateOperation1_();
void privateOperation2_();
Type1 data1_;
Type2 data2_;
};
// example 2 header:
class Example2 {
class Impl;
public:
void publicOperation();
private:
std::auto_ptr<Example2Impl> impl_;
};
// example2 cpp:
class Example2::Impl
{
public:
void privateOperation1();
void privateOperation2();
private: // or public if Example2 needs access, or private + friendship:
Type1 data1_;
Type2 data2_;
};
You can notice that I postfix private (and also protected) members with an underscore. The PIMPL version has an internal class for which the outside world does not even see the operations. This keeps the class interface completely clean: only real interface is exposed. No need to argue about order.
There is an associated cost during the class construction as a dynamically allocated object must be built. Also this works really well for classes that are not meant to be extended, but has some short comings with hierarchies. Protected methods must be part of the external class, so you cannot really push them into the internal class.
I tend to follow the POCO C++ Coding Style Guide.
i think it's all about readability.
Some people like to group them in a fixed order, so that whenever you open a class declaration, you quickly know where to look for e.g. the public data members.
In general, I feel that the most important things should come first. For 99.6% of all classes, roughly, that means the public methods, and especially the constructor. Then comes public data members, if any (remember: encapsulation is a good idea), followed by any protected and/or private methods and data members.
This is stuff that might be covered by the coding standards of large projects, it can be a good idea to check.
In our project, we don't order the members according to access, but by usage. And by that I mean, we order the members as they are used. If a public member uses a private member in the same class, that private member is usually located in front of the public member somewhere, as in the following (simplistic) example:
class Foo
{
private:
int bar;
public:
int GetBar() const
{
return bar;
}
};
Here, the member bar is placed before the member GetBar() because the former is used by the latter. This can result in multiple access sections, as in the following example:
class Foo
{
public:
typedef int bar_type;
private:
bar_type bar;
public:
bar_type GetBar() const
{
return bar;
}
};
The bar_type member is used by the bar member, see?
Why is this? I dunno, it seemed more natural that if you encounter a member somewhere in the implementation and you need more details about that (and IntelliSense is screwed up again) that you can find it somewhere above from where you're working.
In practice, it rarely matters. It's primarily a matter of personal preference.
It's very popular to put public methods first, ostensibly so that users of the class will be able to find them more easily. But headers should never be your primary source of documentation, so basing "best practices" around the idea that users will be looking at your headers seems to miss the mark for me.
It's more likely for people to be in your headers if they're modifying the class, in which case they should care about the private interface.
Whichever you choose, make your headers clean and easy to read. Being able to easily find whatever info I happen to be looking for, whether I'm a user of the class or a maintainer of the class, is the most important thing.
It is really helpful to the folks that will use your class to list the public interface first. It's the part they care about and can use. Protected and private can follow along after.
Within the public interface, it's convenient to group constructors, property accessors and mutators, and operators in distinct groups.
Note that (depending on your compiler and dynamic linker), you can retain compatibility with previous versions of a shared library by only adding to the end of the class (i.e. to the end of the interface), and not removing or changing anything else. (This is true for G++ and libtool, and the three part versioning scheme for GNU/Linux shared libraries reflects this.)
There's also the idea that you should order members of the class to avoid wasted space due to memory alignment; one strategy is to order members from smallest to largest size. I've never done this either in C++ or C though.
Overall, your public interface should come before anything, because that's the main/only thing that users of your classes should be interested in. (Of course, in reality that doesn't always hold, but it's a good start.)
Within that, member types and constants are best first, followed by construction operators, operations, and then member variables.
Put the private fields first.
With modern IDEs, people don't read the class to figure out what it's public interface is.
They just use intellisence (or a class browser) for that.
If someone is reading through the class definition, it's usually because they want to understand how it works.
In that case, knowing the fields helps the most. It tells you what the parts of the object are.
binary compatibility
There are a few concrete reasons for the ordering of class members.
These have to do with binary compatibility.
Binary compatibility mainly affects changes to system DLLs and device drivers.
If you're not interested in these, ignore this answer.
Public members must go before private members.
This is so you can mix and change private members without affecting the location of public data.
New public members must go last.
This again avoids affecting the position of existing public members.
The same ordering applies to vtable members.
Apart from this there's no reason to not to follow your own/your colleagues' preferences.
Depends entirely on your preference. There is no "the right way".
When doing C++ in my own pet projects I personally keep convention that I put access modifier before each member or method declaration.