Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameters Naming for Constructor

Tags:

c++

In Java, usually, I can have my constructor's parameters same name as member variables.

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

private int x;

In C++, I can't. Usually, I have to do it this way.

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

private:
    int x;

Is there any better way? As the constructor parameters name look ugly, when IDE IntelliSense pop up the constructor parameters windows.

like image 830
Cheok Yan Cheng Avatar asked Aug 24 '26 09:08

Cheok Yan Cheng


1 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
  }
};

Though I also commonly use stylistic names for members (e.g. _x), I do it for non-public members. If x is public as in this example, I would do it like this, and look at renaming the ctor's parameter if I thought it would be more readable.

Edit: Since people seem to be getting sidetracked, I'll clarify on _x. The standard reserves some 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 at global scope

Since members are scoped to the class, they do not fall in the third category. That said, it would be nice to not continue getting sidetracked. :) Feel free to ask a question about reserved identifiers in C++ and post a link to it in the comments if you want.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!