Constructor Naming Options

In Java, as a rule, I can have my constructor parameters with the same name as member variables.

public A(int x) { this.x = x; } private int x; 

In C ++, I cannot. Usually I have to do it this way.

 public: A(int x_) : x(x_) { } private: int x; 

Is there a better way? Because the constructor parameter name looks ugly when the IntelliSense IDE pops up constructor parameter windows.

+3
c ++
source share
6 answers

In C ++, you can if you want:

 struct A { int x; A(int x) : x(x) { foo(this->x); // if you want the member instead of the parameter here } }; 

Although I also often use stylistic names for members (e.g. _x ), I do this for non-public members. If x is publicly available, as in this example, I would do it this way and look at renaming the ctor parameter if I thought it would be more readable.

Edit: Since people seem to be distracted, I will clarify on _x . The standard reserves several identifier names:

  • any name with two adjacent underscores in any namespace
  • any name with a leading underscore followed by an uppercase letter in any namespace
  • any name with a leading underscore in the global area

Since members are limited to a class, they do not fall into the third category. Nevertheless, it would be nice not to be distracted. :) Feel free to ask a question about reserved identifiers in C ++ and post a link to it in the comments if you want.

+5
source share

You can actually do this in Java in C ++:

 public: A(int x) { this->x = x; } 

But then you can also simply say x (x):

 public: A(int x) : x(x) { } 
+3
source share

C ++ is smart enough to figure out which x you mean, you can write:

 class A { int x; A( int x ) : x(x) {}; }; 
+3
source share

Google's style is to make underscores:

 public: A(int x) : x_(x) { } private: int x_; 

Much prettier.

+1
source share

I do not think that's possible. However, I would strongly recommend using a consistent naming convention for member variables to distinguish them from parameters and local variables.

In my company, we usually designate member variables with the prefix "m", for example:

 int mMyMemberVariable; 

or

 int m_MyMemberVariable; 

This is just an example of style. Consistency is the key.

+1
source share

One way (and some may argue that this is the C ++ path) is to prefix the fields of your class m_ to disambiguate between the field and the name of the constructor argument.

0
source share