Defining variables after class methods

Viewed 66

I keep seeing code where class variables are declared after methods at the bottom like

class Observer
{
public:
    int getstate();
    void update(int state);
private:
    int state;
};

Is this a common practice I should adapt to? Is there a reason for ordering them like this?

3 Answers

Is this a common practice I should adapt to? Is there a reason for ordering them like this?

You don't have to. Either order works. The choice is subjective. I don't think there's a significant reason to prefer one order over the other myself.

However, I do recommend ordering public members - whether variables or functions - before protected and those before private. This is because public interface of the class is more likely to be important to a programmer who reads the class definition. Ordering the important parts first potentially reduces the time that the reader has to spend to find what they're looking for.

I also recommend getting used to a variety of different orders, as each programmer has their own preferences and there won't be consitency between different projects, nor even necessarily within a project.

It is a commonly used way to structure the code but it is not mandated by the language. You are free to format your code as you wish. The most important thing to remember is:

Code is written for people, not for machines.

Keep that in mind and put yourself in the shoes of the next person who will be reading your code. It should be crystal clear.

Most people choose to put public first because developers and editors generally need the more important information. It also makes the code easier and clearer.

Related