2

Possible Duplicate:
Why does an overridden function in the derived class hide other overloads of the base class?

I am having a problem with using an inherited method in a class used as a template parameter. like the below:

class D
{
};

class A
{
public:
        void f( D &d ){};
};

class B: public A
{
public:
        void f( int ) {};
};

template<typename F>
class C
{
public:
        void doit() { D d; f->f(d); };
        F *f;
};

int main()
{
        C<B> cb;
        cb.doit();
}

This is what I get trying to compile it:

g++ testtemplate.cpp 
testtemplate.cpp: In member function ‘void C<F>::doit() [with F = B]’:
testtemplate.cpp:28:   instantiated from here
testtemplate.cpp:21: error: no matching function for call to ‘B::f(D&)’
testtemplate.cpp:14: note: candidates are: void B::f(int)

However, if I remove the void f( int ) {} method, the compiler finds the original method f( D &d ). Looks like the original method is shadowed by the new one. I want to know why.

Community
  • 1
  • 1

3 Answers3

1

You can do this

class B: public A
{
public:
    using A::f;
    void f( int ) {};
};

Basically re-declaring the base class method with a different signature hides all base class methods with the same name.

Community
  • 1
  • 1
parapura rajkumar
  • 24,045
  • 1
  • 55
  • 85
1

Yes indeed, the method B.f hides A.f. If you want it to be available in B, you need an using directive :

class B: public A
{
public:
    using A::f;
    void f( int ) {};
};
slaphappy
  • 6,894
  • 3
  • 34
  • 59
0

A member of a derived class will hide any base-class members with the same name. In order to make A::f available in B, you need a using declaration:

class B: public A
{
public:
    using A::f;         // <--- add this
    void f( int ) {};
};
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644