views:

521

answers:

11
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.

+6  A: 

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

swegi
eww, hungarian warts!
workmad3
Yes, visibility of the scope is primary motivation for using those prefixes/suffixes. But do you have an example of a situation where knowing variable scope from variable name helps?
Łukasz Lew
that's easy - you are in some kind of large method and you inherited from some other guy. You need to find out, what it does. It's a lot easier, if you know the scope of the variable. A local change of a value has much less importance than a change of the class state. That's why you need to know the scope.
Tobias Langner
@Luke there is always the case of member setter functions where the incoming parameter can then just be the member name minus the underscore. That kind of style aids in overall comprehension.
Peter M
I also use "m_" and "s_" for C++. One benefit is that Intellisense can distinguish members and other identifiers then. Therefore I don't think, a trailing "_" is useful.
ur
For an alternative to hungarian notation you can check my answer here (although the answer is not directly related to it): http://stackoverflow.com/questions/469696/what-is-your-most-useful-c-c-snippet/1609496#1609496 although it probably add a small overhead but the compiler should be able to optimize it away (citation needed for both claim).
n1ck
I really hate the m_ convention. Member variables are too normal an occurrence for such a startling convention that tends to obscure the variable's actual name.
Omnifarious
I wonder how it comes that a trailing underscore is ranted at for being ugly, distracting and whatnot, while the leading `m_`, which is much more of a wart (and _wasn't even asked about_), is up-voted so much by a silent crowd. So much for rational arguments. `:)`
sbi
A: 

I agree with you that the underscore variable suffix is not the ideal coding style, and that adding a little complexity into the constructor is better than adding more complexity throughout the entire class.

The other day, I took a look at one of my old Java projects where I had applied the underscore suffix to variable names, and I found that it did make reading the code more difficult. It wasn't too hard to get used to, but I found it to be slightly distracting without adding any real benefit.

Kaleb Brasee
You find it distracting because it's an old project and you are now working with a different convention. The same is true for any convention, when you change, you're distracted until you adapt.
Matthieu M.
I find it distracting because it adds unnecessary characters to a variable name. I would have probably omitted the underscores on that original project, but had to use them due to forced conventions.
Kaleb Brasee
+4  A: 

If you need this underscore in order to tell class members from other variables, you probably have to large member functions to instantly see what's a variable/parameter.

I still like it because it often simplifies member function parameter naming:

class person
{
public;
  person(const std::string& first_name, const std::string& last_name)
    : first_name_(first_name), last_name_(last_name) {}

  // ...

private:
  std::string first_name_;
  std::string last_name_;
};
sbi
i do it this way also, good style
Matt Joiner
You could of course avoid the hungarian warts by appending the _ to the parameters instead of the members.
digitalarbeiter
@digitalarbeiter: Yes, I could. But then I would have to either always add a `_` suffix to parameters (and what would that buy me except for having my own convention that's backwards to everybody else's) or I am back to ad-hoc parameter renaming due to clashes with class members (which to avoid is the reason why I append a `_` to class members).
sbi
+2  A: 

I think it's important to distinguish between class variables and local ones (and global ones if really needed). How you do it, is not important - just be consistant.

class Foo
{
  int mMember;
  int member_;
  int _member;
  int m_Member;
};

All styles give you the information you need. As long as you stay with the same style all of the time, no problem. Sometimes other people need to work with your code (e.g. when you create a library, or you work with a community). Then it might be a good idea to stick with the most used style in the C++ community.

Sorry - I can't answer what style that is.

Tobias Langner
Avoid leading underscores, there are situations when you should not use them (followed by a upper case letter for example) and it's such a headache to remember exactly what they are... and just too confusing in the end.
Matthieu M.
+1  A: 

We follow possibility.com's C++ coding standard, which says to prefix member variables with an 'm', but I've also done some work under Google's style guide.

Like you say, it's not strictly necessary, especially if you have an IDE that assigns different syntax highlighting to member variables. However, I think that some kind of consistent naming scheme, to let you tell at a glance whether or not a variable is a member variable, is very worthwhile:

  • Simplified parameter naming, as in sbi's answer, is one benefit.
  • A consistent coding style is important, regardless of which style you pick. Ideally, everyone on the team would use the same coding style, so that you can't tell at a glance who wrote a given section of code. This helps helps when bringing new developers onto the team and with agile practices such as no code ownership and is even more important with open source projects that may attract a variety of contributions.
  • Most importantly, readability can greatly benefit from having all of the code follow a fairly strict style that makes clear the types of identifiers like this. The difference between being able to tell at a glance that a variable is a member and being able to tell from looking at local variables' declarations may be small, but following a good coding standard will make numerous small differences like this throughout a body of code, and it can make a huge difference in how easy the code is to follow and how easy it is to get started in an unfamiliar section of code.

(You mentioned that you gave this style a try, but if it was only for a part of code and only for code that you were already familiar with, then it's harder to see the readability benefit that following a coding style like this for the entire codebase can bring.)

All of this is in my experience, your mileage may vary, etc.

Josh Kelley
+4  A: 

Well since noone mentioned it: adding an underscore to member variable permit to call your getter/setter the 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.

n1ck
+1. This is the style I use. I find it very convenient to give the getter/setter the same name.
Rob
The question is why you need getters/setters at all. They buy you very little over non-encapsulated, direct member access. If you have that low an abstraction, what's the class for? To me they seem pseudo-OO.
sbi
Well I agree that having both a getter and setter is usually a smell but this can apply for only a getter (which I think is more justified). Also we don't live in an ideal world and maybe you just need to transition from a public member to using getter and setter before refactoring everything to be "ideal oop". If you want a discussion about getter and setter I think there is a lot of them on this site ;o)
n1ck
A: 

there is one more "style" which suggests declaring class members as below:

class Foo{
    int m_value;
public:
     //...
};

i found it usable. but it is just my point of view.

varnie
The difference between m_value and value_ is a single keystroke... Does this really add up to enough time savings to wage battles over it? :-)
MaxVT
the tastes differ;)
varnie
@MaxVT, it's not the extra keystroke, it's that the m_ prefix has a lot more visual impact and, IMHO, tends to de-emphasize the variable's name, which I think is more important.
Omnifarious
+1  A: 

To me the benefit of this style of decorating member variables is it works well with auto complete functionality of text editors. Having a prefix decoration requires you to type more characters before a solid guess on what you mean can be made.

Andrew Khosravian
A: 

I agree with Tobias that there's a benefit to some convention -- whatever it may be -- to highlighting class variables. On the other hand, I invariably find that such conventions make the code "flow" less well. It's just easier to read "totalPrice = productPrice + salesTax" then "m_totalPrice = l_productPrice + l_salesTax" or whatever.

In the end, I prefer to just leave all the field names undecorated, and have few enough class variables that keeping track of them is not a problem. In constructors and setters, I put a prefix or suffix on the parameter, or in Java I typically distinguish the class variable with "this.", like:

public Foo(int bar)
{
  this.bar=bar;
}

(Can you do that in C++? It's been so long I don't remember.)

Jay
It would be this->bar=bar, but yes.
Kylotan
You can do this (albeit the syntax is a little bit different, as Kylotan already noted), but if `bar` is a string, you wouldn't want to.
sbi
l_ for local and a_ for arguments were used by one of my former co-workers. It made refactoring a b!tch because it ended up producing a delta of almost all lines, due to the names.
Tom
Kylotan: My question was about the syntax, but rather, would C++ recognize this->bar as referencing the member value and an unadorned bar as the parameter? That's how it works in Java. Or maybe you intended to convey that the answer to that question is yes.
Jay
+1  A: 

I came up with this style independently early in my C++ coding days (late 80s, early 90s) because I encountered several confusing situations in which I had to keep going back to the class header to figure out which variable was really a member variable.

Once I started seeing other people's C++ code that did the same thing I was rather gratified that I had noticed a problem that other people had and that the solution I adopted for myself was something other people also thought of.

It's not frequently useful, but it's fairly innocuous and when it is useful, it's very useful.

This is also why I really hate the m_ style. It's not innocuous, and I think the added ugliness is not worth the benefit.

I do use an S_ prefix for file scope static variables and class static variables that aren't constants. They are sort of like global variables, and I think their use should be signaled loudly.

Omnifarious
A: 

This is basically a religious argument so you're never going to reach a consensus on this style. FWIW, I use this style for my member variables for reasons already stated by others, e.g.:

class Foo
{
public:
  Foo(std::string name, int age) :
    name_(name),
    age_(age)
  {
  }

  std::string name() const { return name_; }
  void name(const std::string& name) { name_ = name; }

  int age() const { return age_; }
  void age(int age) { age_ = age; }
private:
  std::string name_;
  int age_;
};

Just adopt something you're happy with and stick with it.

Rob