Conflicts between member names and constructor argument names

arguments, c++, class, naming-conventions

Solution

You can use initialization lists just fine with the same names:

A::A(int x, int y, int width, int height) :
    x(x),
    y(y),
    width(width),
    height(height)
{
}

An alternative is to use different names, if you don't want to have the same names. Some Hungarian-notation variation comes to mind (I might get some hate for this):

//data members
int x_;
int y_;
int width_;
int height_;
//constructor
A::A(int x, int y, int width, int height) :
    x_(x),
    y_(y),
    width_(width),
    height_(height)
{
}

But there's nothing wrong with the first suggestion.

Problem

Possible Duplicate: Members vs method arguments access in C++ I have a class that has some members, like `x`, `y`, `width` and `height`. In its constructor, I wouldn't do this: ``` A::A(int x, int y, int width, int height) { x = x; y = y; width = width; height = height; } ``` This doesn't really make sense and when compiled with g++ `x`, `y`, `width`, and `height` become weird values (e.g. `-1405737648`). What is the optimal way of solving these naming conflicts?

Original source

Related problems