struct base
{
virtual void func(){
std::cout << "base";
}
};
struct derived : base
{
void func(){
std::cout << "derived";
}
};
int main(){
void (base::*pfun)() = &base::func;
base* pbase = new derived;
(pbase->*pfun)();
}
I was expecting this to call the base class member function, but it seems the virtual function mechanism works on member function pointers too. Is there a way to call the base class function, without making it unvirtual.
Member function pointers
Is it possible to call a virtual member function of a base class, that has been overriden in a derived class, from a base class function pointer.
I just tried the following and it actually works:
Note that the :: operator has the highest precedence, so it is evaluated before the arrow, dot, and parentheses operators, so the above code is equivalent to b->(base::foo)().
int main(void){ base *b; derived d; b = &d b->foo(); // Prints "derived" as expected b->base::foo(); // Prints "base" return 0;}
Note that the :: operator has the highest precedence, so it is evaluated before the arrow, dot, and parentheses operators, so the above code is equivalent to b->(base::foo)().
quote:Original post by quant
Is there a way to call the base class function, without making it unvirtual.
Nope, this is actually a semi-gripe I have with the language, though only semi-gripe because it should rarely logically make sense for you to do such a thing. It would be nice if you could choose between dynamic binding and static binding of member function pointers, possibly by having a non-virtual member function pointer type (convertable to the standard member function pointer type) which would be more similar to a regular function pointer in addition to also having the standard member function pointer type we have now.
Instead, your only solution is to make a separate non-virtual function which is called by the virtual function, and then make the poitner point to the nonvirtual function.
[edited by - Polymorphic OOP on May 19, 2004 12:03:55 PM]
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement