Virtual Function

Virtual Function

I’m surprised the following code doesn’t compile:

class C1{public:  virtual void f() { /* ... */ }  void f(bool) { /* ... */ }};class C2 : public C1{public:  void f() { /* ... */ }};main(){  C2 c2;  c2.f(true);}

I found that adding “using C1::f;” in C2 class solves the problem; however, I see no ambiguity in the call to f.

Actually, your compiler is right. The C++ standard says that “a name can be hidden by an explicit declaration of that same name in a […] derived class” (3.3.7/1). Thus, the f() defined in the derived class hides the one defined in the base class, although the two functions have different signatures. As you said, an explicit using-declaration in the derived class is needed to bring C1::f(bool)?as well as any other member named ‘f’?into the scope of the derived class.


Share the Post: