Re: How to find out if a function is overridden
On 5/23/07 5:46 AM, in article
1179913886.865805.253200@m36g2000hse.googlegroups.com,
"chris@mnemosyne.demon.co.uk" <chris@mnemosyne.demon.co.uk> wrote:
I have a base class, let's call it Base, and a number of publicly
derived classes, let's call them Derived1, Derived2 etc. although
actually we don't know what they are called, how many of them there
are and so on. This is the standard "as a" usage, so Base has virtual
functions, virtual destructor etc. Base may be abstract. However in
the case of interest base has a function, let's call it foo, that is
virtual but isn't abstract and has an implementation. Inheritance by
the Deriveds might be virtual (and might not be direct, there may be a
deeper hierarchy).
Now I have a pointer to Base that actually points to one of the
Deriveds. This Derived may or may not have overridden foo. My question
is, has it? - i.e. can I, and if so how, write some code to find out
if whichever Derived a particular Base * points to (you can assume it
points to some Derived) has implemented foo.
If you are using gcc, then it is possible to compare bound member function
pointers via a language extension. Furthermore, this capability needs to be
enabled with the -Wno-pmf-conversions compiler option, like so:
g++ -Wno-pmf-conversions test.cc
And here is an example test.cc source file to demonstrate this technique:
// test.cc
#include <iostream>
class A
{
public:
virtual void f() {}
};
class B : public A
{
public:
virtual void f() {}
};
class C : public A
{
};
typedef void (*fptr)(A *);
int main()
{
A * a = new A;
A * b = new B;
A * c = new C;
void (A::*fp)();
fp = &A::f;
fptr ap = (fptr)(*a.*fp);
fptr bp = (fptr)(*b.*fp);
fptr cp = (fptr)(*c.*fp);
if ( bp != ap )
std::cout << "b overrides A::f()\n";
if ( cp != ap )
std::cout << "c overrides A::f()\n";
}
Program Output:
b overrides A::f()
Greg
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]