Is shadowing a member variable from a base class a bad thing? Maybe, but maybe not. -- Raymond Chen
In C++, shadowing occurs when a name in one scope hides an identical name in another scope, sparking debate over its merit. This article explores scenarios where shadowing can either protect code integrity or hinder its evolution, highlighting its dual nature and impact on code maintenance. Join Raymond as he unravels the complexities of shadowing in C++, revealing its intricate balance between benefit and drawback.
Is shadowing a member variable from a base class a bad thing? Maybe, but maybe not.
by Raymond Chen
From the article:
What is shadowing? In C++, shadowing is the name given to the phenomenon when a name in one scope hides an identical name in another scope.
Is shadowing bad? That’s a harder question.
Whether shadowing is good or bad depends on the order in which the conflicting names were introduced.
Suppose you have a class library, and one of the classes is this:
struct Tool { int a; };And suppose some customer uses your class like this:
class Wrench : public Tool { private: int a; };In this case, shadowing is probably unintended. The customer has accidentally shadowed
Tool::a
, and any references toa
in theWrench
class will refer toWrench::a
, even if the author meant to accessTool::a
.Meanwhile, you have another customer who writes this...