cppBeginner
cppBeginner

Reputation: 1212

runtime-check whether an instance (Base*) override a parent function (Base::f())

How to determine whether a pointer of base (B) class is (polymorphism-ly) override a certain virtual function of the base class?

class B{
    public: int aField=0;
    virtual void f(){};
};
class C : public B{
    public: virtual void f(){aField=5;};
};
class D: public B{};

int main() {
    B b;
    C c;
    D d;
    std::vector<B*> bs;
    bs.push_back(&b);
    bs.push_back(&c);
    bs.push_back(&d);
    for(int n=0;n<3;n++){
        //std::cout<<(bs[n]->f)==B::f<<std::endl;
        //should print "true false true"
    }
}

I tried to compare the address of function pointer bs[n]->f against B::f, but it is uncompilable.

Demo

I feel that this question might be duplicated, but I can't find (sorry).

Upvotes: 2

Views: 109

Answers (1)

Justin
Justin

Reputation: 25377

GCC has an extension that allows you to get the address of a virtual member function.

This can be used like so:

#include <vector>
#include <iostream>

class B{
    public: int aField=0;
    virtual void f(){};
};
class C : public B{
    public: virtual void f(){aField=5;};
};
class D: public B{};

int main() {
    B b;
    C c;
    D d;
    std::vector<B*> bs;
    bs.push_back(&b);
    bs.push_back(&c);
    bs.push_back(&d);
    for(int n=0;n<3;n++){
        // This might need to be: (void*) B{}.*&B::f == (void*) (...)
        std::cout << ((void*) &B::f == (void*)(bs[n]->*&B::f)) << '\n';
    }
}

Demo

You may find this QA to be interesting.

Naturally, this is nonstandard behavior. If you wanted similar behavior in standard C++, you might actually be looking for pure virtual functions:

class B{
    public: int aField=0;
    virtual void f() = 0;
};

Otherwise, you'd have to have some other mechanism to communicate, such as a bool return type on f().

Upvotes: 2

Related Questions