Search code examples
c++castingvirtualvirtual-functions

Does class have a virtual function? c++


Hence I have a class, and want to determine whether it has a virtual function or not.

The first way to do I considered by dynamic cast.

 class A
 {
// hidden details..
 };

 class B:public A{};

 int main()
 {
    A *a = new A;;
    B* b = dynamic_cast<B*>(a);
 }

So in this case if there is a virtual function in class A, the compile will succeed, otherwise, this error will occur:

error: cannot dynamic_cast \u2018a\u2019 (of type \u2018class A*\u2019) to type \u2018class B*\u2019 (source type is not polymorphic)

Is there a way to check this without compile error? NOTE: I have no c++11 or boost support!


Solution

  • You could test for existence of virtual methods by comparing the size of type with the size of type with a virtual method added. This type of check is not guaranteed by the standard, and can be fooled by virtual inheritance, so it should not be used in production code. However, it can still be useful for simple cases where C++11 std::is_polymorphic is unavailable. Tested under g++ 4.6:

    template<typename T>
    class VirtualTest: private T {
        virtual void my_secret_virtual();
    };
    
    template<typename T>
    bool has_virtual() {
        return sizeof(T) == sizeof(VirtualTest<T>);
    }
    

    Invoke the test as has_virtual<A>().