简体   繁体   中英

Is using the same variable in a class ok to use in the constructor C++?

If I have a class:

class className{
    int i;
public:
    className(int value);
};

What is considered as the best practise for initializing the class variable 'i' from the constructor as per the below choices?

1) Use the actual field name with an underscore:

className::className(int i_){
    i = i_;
}

2) Use the actual field name with "this":

className::className(int i){
    this->i = i;
}

3) Completely inconsistent things like:

className::className(int value){
    i = value;
}

I have seen this question being directly addressed for Java but not so much for C++. I ask because I would favor number 2 as I would personally prefer less variable names being made. However I would like to know what further considerations this could mean for the compiler or linker etc. I would also like to stick with the C++ norm.

Many Thanks!

Yes that's ok.

Some people actually think it idiomatic.

However, your samples all lack the use of initializer lists :)

class className{
    int i;
public:
    className(int value) : i(value) {};
};

I suggest to avoid the confusion with duplicate names. It makes the compiler complain if you accidentally mess up.

The best practice is to initialize your member variables in the initializer list:

className::className(int i_) : i(i_){}
                               ^^^^^

Reasons :

  1. Performance : You avoid unnecessary calls to members' default constructors.
  2. Having Members not default constructible: If you have member variables that aren't default constructible (ie, they don't have a default constructor), you are obliged to initialize them in the initializer list.
  3. Having Members const -qualified: Same as 2.
  4. Having Members references to objects: Same as 2.
  5. Readability : Opinion based.
  6. Extensibility : Opinion based.

As far as it concerns the naming issue: IMHO, it's primarily opinion based. Personally, for parameters of a constructor I use the suffix underscore as well.

I am in agreement with @sehe, to clarify on his context of initializer lists:

className::className(int i_) : i(i_) {}

However! I think the identifier names are backwards in terms of appropriateness. i_ should be the private member variable, and i should be the constructor parameter.

My notes on each "choice": 1) It's easy to see which parameters correspond with one another here 2) It's explicitness here 3) I think you've already concluded your opinion on this one by wording it 'Completely Inconsistent' :).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM