4

I'm a little confused about the second constructor. I would have assumed that the parameters to the constructor would overshadow the instance variables and thus that this initialization would not work. It seems to work correctly though. Can someone explain why this works? Also is this considered bad practice?

class Box {
private:
    int l;
    int b;
    int h;

public:
    Box(): l(0), b(0), h(0) {}  // this I understand
    Box(int l, int b, int h): l(l), b(b), h(h) {} // why does this work?
};
bw0248
  • 711
  • 5
  • 19
  • 1
    I'm not sure if other people consider it bad practice but I use it all the time (using real variable names though and not single letter variables). – NathanOliver Feb 26 '19 at 18:43
  • @NathanOliver true, but that could quickly get out of hand, for example `Foo(A a1) : a1(std::move(a1)), a2(a1)` (provided a1 and a2 are data members of struct Foo). – SergeyA Feb 26 '19 at 18:48
  • @SergeyA How? Whatever is inside the `()` is looked up first as a parameter. That means in `Foo(A a1) : a1(std::move(a1)), a2(a1)` we know we are copying from a moved from object. – NathanOliver Feb 26 '19 at 18:49
  • 1
    @NathanOliver **we** might be an overstatement. People might read it as copying from class member. On any rate, I personally liked this style more before C++11, when there were no moves. I am still using it, but I am more cautious. I also tend not to use it when there are any transformations applied to the arguments (but than the names would be likely different) – SergeyA Feb 26 '19 at 18:52

0 Answers0