Is shadowing a member variable from a base class a bad thing? Maybe, but maybe not. -- Raymond Chen

RaymondChen_5in-150x150.jpgIn 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 to a in the Wrench class will refer to Wrench::a, even if the author meant to access Tool::a.

Meanwhile, you have another customer who writes this...

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.