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.

See also  How College Students Can Shape the Future of Tech Responsibility

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist