Search code examples
c++standards

Naming function parameters the same as class members


This is something I do quite commonly when I program C++, and I've been wondering for a while if its a "bad" habit (Is this behaviour standardized?)

Lets say I have a class:

Class Foo {
  public:
    Foo(int x) {
      //this->x is the member "x" of Foo
      //x is the paramater "x" to the function
      this->x = x; //Sets Foo::x to x (parameter x)
    }

  private:
    int x;


};

Notice how in Foo::Foo(int x), the parameter is named x which is the same name as a member variable for Foo.

I commonly just use use this->x = x; to assign the member variable the value of the parameter, which seems to work for me (I commonly use MSVC). In MSVC (and GCC I think), accessing x will access the parameter named x rather than the member named x. Is this standardized behaviour across all c++ compilers? Is there anything stopping compilers from associating just x with the member variable instead of the parameter variable? (eg: this->x; would be equivalent to this->x = this->x;)


Solution

  • Yes, using any compliant compiler, the parameter x will hide the member x. However a more interesting alternative to what you've written is this:

    class Foo {
    public:
        Foo(int x) : x(x) {}
    private:
        int x;
    };
    

    which, aside from being unreadable, will actually do precisely what you want it to.