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!
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.
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.
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.
The duplicate object being created with the help of Clone() virtual function which is also considered as virtual copy constructor.
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>()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With