Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convention of using underscores in C++ class member names

The large majority of my programming knowledge is self-taught, so I was never taught proper design patterns, conventions, and so on and so forth.

I've been digging through a lot of my company's software libraries lately, and I notice that a lot of class data members have underscores in their names.

For example:

class Image
{
// various things

// data members
char* _data;
ImageSettings* _imageSettings;
// (and so on...)
};

I see this in a lot of online example code as well. Is there a reason behind this convention? Sorry I couldn't provide better examples, I'm really trying to remember off the top of my head, but I see it a lot.

I am aware of Hungarian notation, but I am trying to get a handle on all of the other conventions used for C++ OOP programming.

like image 565
8bitcartridge Avatar asked Dec 07 '22 20:12

8bitcartridge


2 Answers

It is simply intended to make it clear what variables are members, and which are not. There is no deeper meaning. There is less possibility for confusion when implementing member functions, and you are able to chose more succinct names.

void Class::SomeFunction() {
    int imageID;
    //...
    SetID(imageID + baseID); //wait, where did baseID come from?
}

Personally, I put the underscore at the end instead of the begining [if you accidently follow a leading underscore with a capital letter, your code becomes ill formed]. Some people put mBlah or m_Blah. Others do nothing at all, and explicitly use this->blah to indicate their member variables when confusion is possible. There is no global standard; just do what you want for private projects, and adhere to the existing practices elsewhere.

like image 127
Dennis Zickefoose Avatar answered Jan 03 '23 09:01

Dennis Zickefoose


I have seen _ typing in front of the member, just to notify the reader that it's a class member variable.

More conventional way I have seen is putting m_; i.e. m_data;

like image 39
iammilind Avatar answered Jan 03 '23 07:01

iammilind