pintarj
pintarj

Reputation: 75

C++ 11 Implemented interface's method is not available. Why?

I have a specific problem, that is described in the example below. My problem is the line number 34 (the commented one): why does this line give me error message?

test.cpp: In function ‘int main()’:
test.cpp:34:13: error: no matching function for call to ‘C::func(int)’
  c.func( 33 );  // Line 34
         ^
test.cpp:23:24: note: candidate: virtual void C::func(int, int)
  public : virtual void func( int x, int y ) override
                    ^
test.cpp:23:24: note:   candidate expects 2 arguments, 1 provided

Class C extends class B and class B implements method func(int). But why isn't that method available? And why is then available if I cast C to A?

#include <cstdio>


class A
{
    public : virtual void func( int x ) = 0;
};


class B : public A
{
    public : virtual void func( int x, int y ) = 0;

    public : virtual void func( int x ) override
    {
        func( x, 0 );
    }
};


class C : public B
{
    public : virtual void func( int x, int y ) override
    {
        printf( "x: %d y:%d\n", x, y );
    }
};


int main()
{
    C c;
    c.func( 4, 6 );     
    c.func( 33 );       // Line 34

    A* a = &c;
    a -> func( 33 );

    return 0;
}

Upvotes: 0

Views: 324

Answers (2)

dutiona
dutiona

Reputation: 481

The detailed explanation is there : https://isocpp.org/wiki/faq/strange-inheritance#hiding-rule .

In this case it doesn't matter wether func is virtual. The fact is that C::func(int, int) hides B::func(int) instead of overloading it.

You need to bring back B::func(int) in C's scope so that you can use it with an instance of C object. This way, there will be two overloads available in C's scope.

If your compiler support using :

class C : public B
{
    public :
    using B::func;
    virtual void func( int x, int y ) override
    {
        printf( "x: %d y:%d\n", x, y );
    }
};

If your compiler doesn't :

class C : public B
{
    public :
    virtual void func(int x) { B::func(x); }
    virtual void func( int x, int y ) override
    {
        printf( "x: %d y:%d\n", x, y );
    }
};

Upvotes: 2

W.F.
W.F.

Reputation: 13988

This is a problem with scope... in class C the method func is defined and as such the compiler obviously does not try to find overload of the method in upper class... To give compiler a hint which method is in your interest you could use a syntax:

c.B::func(33);

You can also try to avoid the issue by give these two overloads different name...

Upvotes: 2

Related Questions