ProblemsUB & GotchasThe shadowed constructor parameter
NoviceUB & Gotchas

The shadowed constructor parameter

Context

The designer reports every card in the app has collapsed to a dot. QA confirms: any Rect has area zero. The code 'looks fine', review passed, nobody wrote constructor tests — it's a constructor, what could possibly break. w = w, that's what. The parameter shadowed the member. Fix it — and turn on -Wshadow while you're at it.

Task

The constructor parameters w and h shadow the members with the same names — w = w assigns the parameter to itself and the members stay 0. Every Rect has area 0. Fix the constructor; the member initializer list is the idiomatic tool.

Constraints

  • Use the member initializer list to set the members
  • Avoid shadowing: parameter names must not hide the members they initialize (rename one side)
  • area() returns width × height
  • No warnings under -Wall -Wshadow

Before you code

  • In w = w; inside the buggy constructor, which w is on each side, and why?
  • Why does the member initializer list sidestep the whole problem?
  • Why is -Wshadow not enabled by -Wall, and what is the cost of leaving it off?

Tests

  • #1Area reflects the constructor arguments
  • #2Different rectangles have different areas

Hints

Hint 1

Rename the parameters (width, height) and initialize the members in the initializer list: Rect(int width, int height) : w(width), h(height) {}.

Editorshadowed-member.cpp
Results

Hit Submit (or ⌘/Ctrl + ↵) — test results will show up here.