VoidPointer VoidPointer - 1 month ago 5
C++ Question

Why use prefixes on member variables in C++ classes

A lot of C++ code uses syntactical conventions for marking up member variables. Common examples include


  • m_*memberName* for public members (where public members are used at all)

  • _*memberName* for private members or all members



Others try to enforce using this->member whenever a member variable is used.

In my experience, most larger code bases fail at applying such rules consistently.

In other languages, these conventions are far less widespread. I see it only occasionally in Java or C# code. I think I have never seen it in Ruby or Python code. Thus, there seems to be a trend with more modern languages to not use special markup for member variables.

Is this convention still useful today in C++ or is it just an anachronism. Especially as it is used so inconsistently across libraries. Haven't the other languages shown that one can do without member prefixes?

Answer

You have to be careful with using a leading underscore. A leading underscore before a capital letter in a word is reserved. For example:

_Foo

_L

are all reserved words while

_foo

_l

are not. There are other situations where leading underscores before lowercase letters are not allowed. In my specific case, I found the _L happened to be reserved by Visual C++ 2005 and the clash created some unexpected results.

I am on the fence about how useful it is to mark up local variables.

Here is a link about which identifiers are reserved: http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier

Comments