Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using underscore suffix for members beneficial?

class C {  private:   int member_; // here is the underscore I refer to. } 

This underscore is recommended by Google Style Guide and Geosoft's C++ Style Guide.

I understand that there are different opinions and tastes.

I want to ask people who used it or were forced to use it whether they found it beneficial, neutral or harmful for them. And why?

Here is my answer:

I understand ask motivation behind it, but it does not convince me. I tried it and all I got was a little bit of clutter all over the class, but simpler initialization of members in constructor. I haven't encountered situation where underscore helped to differ between private member variable and other variable (except in mentioned initialization).

In that light I consider this style harmful.

like image 548
Łukasz Lew Avatar asked Oct 27 '09 12:10

Łukasz Lew


People also ask

Should private variables have underscore?

In C++, an underscore usually indicates a private member variable. In C#, I usually see it used only when defining the underlying private member variable for a public property. Other private member variables would not have an underscore.

Why put an underscore in front of a variable?

A single leading underscore in front of a variable, a function, or a method name means that these objects are used internally. This is more of a syntax hint to the programmer and is not enforced by the Python interpreter which means that these objects can still be accessed in one way on another from another script.

What is a trailing underscore?

Single trailing underscore naming convention is used to avoid conflicts with Python keywords. When the most fitting name for a variable is already taken by a keyword, appending a single underscore convention is followed to break the naming conflict. Typical example includes using class or other keywords as variables.

What does an underscore before a variable mean in C?

The underscores are often used to show that the variables are instance variables. It is not really necessary, as ivars can have the same name as their properties and their accessors.


2 Answers

Well since no one mentioned it: adding an underscore to member variable allows you to name your getter and setter with the 'conceptual' name of the variable.

ex:

class MyClass {    int someMember_;  public:    int someMember() const { return someMember_; }    void someMember( int newValue ) { someMember_ = newValue; } }; 

not that I use this style though.

like image 115
n1ckp Avatar answered Sep 22 '22 05:09

n1ckp


I use "m_" as prefix for normal member variables and "s_" for static member variables. So the scope is directly visible.

like image 39
swegi Avatar answered Sep 24 '22 05:09

swegi