Zeenobit Zeenobit - 3 months ago 17
C++ Question

C++ Virtual Function Overriding and Overloading

I have the following class structure:

class X
{
// ...
};

class Y : public X
{
// ...
};

class IA
{
public:

virtual void Foo(X* x) = 0;
};

class A : public IA
{
public:

void Foo(Y* y)
{
Foo(static_cast<X*>(y));
}
};

class B : public A
{
public:

virtual void Foo(X* x) override
{
// ...
}
};


However, this code generates compiler errors:

error C2664: 'void A::Foo(Y *)': cannot convert argument 1 from 'X *' to 'Y *'


The way to fix it is to replace A::Foo(Y*) with this:

void Foo(Y* y)
{
static_cast<IA*>(this)->Foo(static_cast<X*>(y));
}


I have trouble understanding why this cast is necessary, and would appreciate some insight. I'm not quite sure if this is guaranteed to be a safe cast either.

To my understanding during overload resolution, the compiler should select the function that requires the least amount of implicit casting for the parameters. But that doesn't seem to be the case here.

Answer

A::Foo hides IA::Foo

to fix it, use using:

class A : public IA
{
public:
    using IA::Foo;

    void Foo(Y* y)
    {
        Foo(static_cast<X*>(y));
    }
};
Comments