Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 914
Eduard Rostomyan Avatar asked Jun 10 '14 12:06

Eduard Rostomyan


People also ask

Do all classes have Vtables?

For every class that contains virtual functions, the compiler constructs a virtual table, a.k.a vtable. The vtable contains an entry for each virtual function accessible by the class and stores a pointer to its definition. Only the most specific function definition callable by the class is stored in the vtable.

Does C have virtual function?

You get the same runtime performance as a C++ member function call, but without any compile-time checking to enforce access control. In C, virtual function calls look unlike any other kind of function call.

Why does your class have a pure virtual function?

A pure virtual function makes it so the base class can not be instantiated, and the derived classes are forced to define these functions before they can be instantiated. This helps ensure the derived classes do not forget to redefine functions that the base class was expecting them to.

Can a copy constructor be virtual?

The duplicate object being created with the help of Clone() virtual function which is also considered as virtual copy constructor.


Video Answer


1 Answers

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

like image 184
user4815162342 Avatar answered Oct 16 '22 06:10

user4815162342