Archived

This topic is now archived and is closed to further replies.

quant

Member function pointers

Recommended Posts

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.
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.

Share this post


Link to post
Share on other sites
I just tried the following and it actually works:
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)().

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites