liveBook · Manning

Shadowing

As explained in 100 C++ Mistakes and How to Avoid Them

Variable shadowing occurs when a declaration in an inner scope uses the same name as a declaration in an outer scope, hiding the outer declaration within the inner scope.

Variable shadowing occurs when an inner scope declares a name already used by an outer scope. The inner declaration hides the outer one, making assignments and computations easy to misread. section 9.1

Mistake: assigning a parameter to itself

In Listing 9.1, setRadius(double rad) contains rad = rad;. Both names refer to the parameter, so the Circle member never changes. The constructor uses the same naming pattern safely through its initializer, but the setter needs this->rad = rad or clearer names. Naming conventions and namespaces can reduce similar maintenance hazards.

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Defines overlapping scopes, demonstrates a setter failure, and recommends explicit qualification and naming; it does not develop formal scope internals.
Examples
Uses Circle radius members and parameters, namespace-qualified globals, and an Analyzer constructor with similarly named values.
What it assumes
Teaches declaration scope and overlapping names from basic examples without assuming advanced language theory.
What you can do after
Diagnose shadowing by tracing scopes and correct it with clearer names, this qualification, or namespace qualification.
How it connects
Connects variable shadowing to variable scope, global variables, namespaces, and the scope resolution operator.

Also explained in

Compare how 4 books explain shadowing →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.