0

I often see code examples where the constructor arguments have the same name as the class members. How does the compiler distinguish the function argument names from the class member names? Is this portable code? Is this bad practice?

Example:

class Box
{
public:
    Box(unsigned length, unsigned width, unsigned height)
        : length(length), width(width), height(height)
    {
        std::clog << length << std::endl;
        std::clog << width  << std::endl;
        std::clog << height << std::endl;
    }
private:
    unsigned length, width, height;
};
L.S. Roth
  • 447
  • 2
  • 14
  • _"Is this bad practice?"_ This is opinion based. I worked in teams where this was common practice and in teams where this was not allowed. _"Is this portable code?"_ Yes, the behavior well defined and specified. _"How does the compiler distinguish the function argument names from the class member names?"_ That's called shadowing. The arguments shadow the members. But there is a special rule member initializer lists since you can just initialize members. –  Apr 15 '21 at 09:44
  • imho it is good practice to not waste names when not needed (consider that everything that needs a name, needs a good name, ie it has a cost to give names), and the member initializer list is a good place to save some names. Though I only use it when the body is empty. Having debug output in the body is somewhat at the border. Anyhow, wether it is good practice is purely opinion based – 463035818_is_not_an_ai Apr 15 '21 at 09:46

1 Answers1

1

"How does the compiler distinguish the function argument names from the class member names?"

That's called shadowing. The parameters (function argument names) shadow the class member names. But there is a special rule for member initializer lists since you can only initialize members (and base classes), i.e. in

Box(unsigned length, unsigned width, unsigned height)
    : length(length), width(width), height(height)

the initialization

length(length)

initializes the member length with the parameter length.

"Is this portable code?"

Yes, the behavior well defined and specified.

"Is this bad practice?"

This is opinion based. I worked in teams where this was common practice and in teams where this was not allowed. Remember that this utilizes shadowing and some static code analyzers or compiler flags may disallow shadowing.