I am trying to use std::bind() to create a function that will call the base class version of a virtual function rather than calling the derived class's version.
struct Base
{
virtual void foo() { cout << "Base\n"; }
};
struct Derived : public Base
{
virtual void foo() { cout << "Derived\n"; }
};
int main(int argc, const char * argv[])
{
Base* base = new Derived;
auto baseMethodHopefully = std::bind( &Base::foo, base );
baseMethodHopefully(); // Want call to Base::foo(), but get call to Derived::foo().
return 0;
}
I understand from elsewhere that you can't normally call a base function in an "anti-virtual" way such as this. The obvious exception is the common paradigm:
void Derived::bar() { Base::bar(); }
Since the expression Base::bar()
is recognized as "anti-virtual" (in the sense I'm alluding to) within Derived's methods, is it possible to bind to Base::bar()
in the desired way from within one of Derived's methods? E.g. something like:
void Derived::bar()
{
auto baseMethod = std::bind( &Base::foo, this );
baseMethod();
}
If so, what is the syntax?
Base::bar()
as a non-virtual member function? – Pendentive