Does class have a virtual function? c++ [duplicate]
Asked Answered
S

1

6

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!

Sacrosanct answered 10/6, 2014 at 12:27 Comment(6)
See here: #1108448 std::is_polymorphic is what you want.Competitor
See std::is_polymorphic.Profound
this is supported since c++11 if I am not mistaken, what to do if I have not got such support?Sacrosanct
Do you have boost ? boost.org/doc/libs/1_55_0/libs/type_traits/doc/html/…Puma
You should specify such requirements in the question.Profound
@EduardRostomyan How did you do it?Benefactress
B
8

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

Bloodfin answered 10/6, 2014 at 12:42 Comment(7)
What if the type T has no public constructor?Sacrosanct
@EduardRostomyan No problem at all - has_virtual<T> never actually attempts to construct T.Bloodfin
Please could you explain why it is not constructed?Sacrosanct
It doesn't work with VC++ (at least not if the class to be tested has virtual inheritance), and probably not with a lot of other compilers.Clifton
@EduardRostomyan Could you please explain why it is constructed? Where is it constructed?Clifton
@JamesKanze I guess has_virtual is then a well-chosen name. Seriously, this is a hack that should never be used in production. I've now amended the answer with a sentence to that effect.Bloodfin
@EduardRostomyan To "construct" a type means to create an instance, with a construct such as T() or new T(), or by invoking a template library function that invokes such a construct. has_virtual<T> is doing none of these, it is only invoking sizeof on T, and on a type that inherits T.Bloodfin

© 2022 - 2024 — McMap. All rights reserved.