Normally, a C++ class is written with public:
and private:
applying to a series of members:
class Foo {
private:
int x;
int y;
int z;
public:
int getX();
int setY(int val);
void print();
}
An alternative coding style is to explicitly prefix every member with public
/private
. Is this a good or bad idea in C++? Here is the previous example altered in this way:
class Foo {
private: int x;
private: int y;
private: int z;
public: int getX();
public: int setY(int val);
public: void print();
}
I couldn't find any opinions or advice on this topic from searching the web, Software Engineering SE, or Stack Overflow. Here is my brainstorm:
Advantages of the first, traditional way:
- It's the idiomatic style when reading and writing C++ code.
- It reduces redundancy when a large batch of members are all public or all private.
Advantages of the second, explicit way:
- The
public
/private
designation is immediately visible at the point where each member is declared. There is no need to scan upwards a potentially large amount of code to find the most recent visibility modifier. - When rearranging the order of members, this technique reduces noise in diffs, and eliminates the possibility of accidentally moving a public variable into a private section or vice versa. (However, it is debatable whether these problems are common or uncommon in the traditional style.)
- It is the mandatory style in closely related languages like Java and C#.