The title is maybe not very descriptive, but it's hard to describe what I want in a short sentence.
So I have a base class like this:
class IBase
{
public:
virtual void f(int) = 0;
virtual void f(float) = 0;
}
then I create an abstract class which defines f for floats only:
class HelpBase: public IBase
{
public:
virtual void f(float arg) override
{
f(static_cast<int>(arg));
}
}
My goal is to provide an abstract class HelpBase which then will be inherited by other classes which will implement f(int);
In my HelpBase I want to use f(int) which at runtime will be provided by one of those classes, but I don't know how to call it.
In example above, compiler (gcc) complians that "f(int)" is unknown for HelpBase.
I cannot write it as IHelpBase::f() as It would force usage of pure virtual member of IHelpBase (gcc also complains). How to use a function which is declared in base class, but actually defined in some of inheriting ones?
There is no problem if I use two different names like f for floats and g for ints. Then I can call g(static_cast(arg)); in my HelpBase and it works as expected.
I think you missed to add using
declarations to lift the base classes' overload sets of f
:
#include <iostream>
class IBase
{
public:
virtual void f(int) = 0;
virtual void f(float) = 0;
};
class HelpBase: public IBase
{
public:
using IBase::f;
virtual void f(float arg) override
{
std::cout << 1 << std::endl;
f(static_cast<int>(arg));
std::cout << 3 << std::endl;
}
};
class X: public HelpBase
{
public:
using HelpBase::f;
virtual void f(int) override
{
std::cout << 2 << std::endl;
}
};
int main()
{
X x;
x.f(0.1f);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With