Can I use identical names for fields and constructor parameters?

C++ParametersConstructor

C++ Problem Overview



class C {
T a;
public:
C(T a): a(a) {;}
};

Is it legal?

C++ Solutions


Solution 1 - C++

Yes it is legal and works on all platforms. It will correctly initialize your member variable a, to the passed in value a.

It is considered by some more clean to name them differently though, but not all. I personally actually use it a lot :)

Initialization lists with the same variable name works because the syntax of an initialization item in an initialization list is as follows:

<member>(<value>)

You can verify what I wrote above by creating a simple program that does this: (It will not compile)

class  A
{

   A(int a)
   : a(5)//<--- try to initialize a non member variable to 5
   {
   }
};

You will get a compiling error something like: A does not have a field named 'a'.


On a side note:

One reason why you may not want to use the same member name as parameter name is that you would be more prone to the following:

class  A
{

   A(int myVarriable)
   : myVariable(myVariable)//<--- Bug, there was a typo in the parameter name, myVariable will never be initialized properly
   {
   }
   int myVariable;
};

On a side note(2):

One reason why you may want to use the same member name as parameter name is that you would be less prone to the following:

class  A
{

   A(int myVariable_)
   {
     //<-- do something with _myVariable, oops _myVariable wasn't initialized yet
     ...
     _myVariable = myVariable_;
   }
   int _myVariable;
};

This could also happen with large initialization lists and you use _myVariable before initializing it in the initialization list.

Solution 2 - C++

One of the things that may lead to confusion regarding this topic is how variables are prioritized by the compiler. For example, if one of the constructor arguments has the same name as a class member you could write the following in the initialization list:

MyClass(int a) : a(a)
{
}

But does the above code have the same effect as this?

MyClass(int a)
{
    a=a;
}

The answer is no. Whenever you type "a" inside the body of the constructor the compiler will first look for a local variable or constructor argument called "a", and only if it doesn't find one will it start looking for a class member called "a" (and if none is available it will then look for a global variable called "a", by the way). The result is that the above statment "a=a" will assign the value stored in argument "a" to argument "a" rendering it a useless statement.

In order to assign the value of the argument to the class member "a" you need to inform the compiler that you are referencing a value inside this class instance:

MyClass(int a)
{
    this->a=a;
}

Fine, but what if you did something like this (notice that there isn't an argument called "a"):

MyClass() : a(a)
{
}

Well, in that case the compiler would first look for an argument called "a" and when it discovered that there wasn't any it would assign the value of class member "a" to class member "a", which effectively would do nothing.

Lastly you should know that you can only assign values to class members in the initialization list so the following will produce an error:

MyClass(int x) : x(100) // error: the class doesn't have a member called "x"
{
}

Solution 3 - C++

if the formal parameter and the member is named same then beware of using this pointer inside constructor to use the member variable

class C {
  T a;
public:
  C(T a): a(a) {
this->a.sort ;//correct
a.sort();//will not affect the actual member variable
}
};

Solution 4 - C++

Legal: yes, as explained by Brian, compiler knows the name to expect in the initializer list must be a member (or a base class), not anything else.

Good style: most likely not - for a lot of programmers (including you, it seems) the result is not obvious. Using a different name for the parameter will keep the code legal and make it a good style at the same time.

I would prefer writing some of:

class C {
  T a_;
public:
  C(T a): a_(a) {}
};


class C {
 T a;
 public:
 C(T value): a(value) {}
};

Solution 5 - C++

The problem with this practice, legal though it may be, is that compilers will consider the variables shadowed when -Wshadow is used, and it will obfuscate those warnings in other code.

Moreover, in a non-trivial constructor, you make make a mistake, forgetting to put this-> in front of the member name.

Java doesn't even allow this. It's bad practice, and should be avoided.

Solution 6 - C++

Hey guys this is a great question. If you want to identical names for fields and constructor parameters / methods parameter you have to use scope resolution ( :: ) operator or you can use this ( this-> ) to map the parameter value with member like this please check the code snippet carefully you can understand easyly.

class Student{
    private :
        string name;
        int rollNumber;

    public:
        Student()
        {
           // default constructor
        }

        // parameterized constructor
        Student(string name, int rollNumber)
        {
            this->name = name;
            Student::rollNumber = rollNumber;
        }

        void display()
        {
            cout<<"Name: "<<name <<endl;
            cout<<"Roll Number: "<<rollNumber<<endl;
        }

        void setName(string name)
        {
            this->name = name;
        }

        void setrollNumber(int rollNumber)
        {
            Student::rollNumber = rollNumber;
        }

};

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSergey SkoblikovView Question on Stackoverflow
Solution 1 - C++Brian R. BondyView Answer on Stackoverflow
Solution 2 - C++DragonionView Answer on Stackoverflow
Solution 3 - C++yesraajView Answer on Stackoverflow
Solution 4 - C++SumaView Answer on Stackoverflow
Solution 5 - C++RickView Answer on Stackoverflow
Solution 6 - C++Soumadip DeyView Answer on Stackoverflow