A function call with the correct function definition at compile time. This is called static binding. You can specify that the compiler match a function call with the correct function definition at run time; this is called dynamic binding. You declare a function with the keyword virtual if you want the compiler to use dynamic binding for that specific function.
A virtual function is a member function you may redefine for other derived classes, and can ensure that the compiler will call the redefined virtual function for an object of the corresponding derived class, even if you call that function with a pointer or reference to a base class of the object.
A class that declares or inherits a virtual function is called a polymorphic class.
The following example demonstrates this:
#includeusing namespace std;
struct A { virtual void f() { cout << "Class A" <<>struct B: A { void f(int) { cout << "Class B" <<>struct C: B { void f() { cout << "Class C" <<>int main() { B b; C c; A* pa1 = &b; A* pa2 = &c; pa1->f(); pa2->f();}
The following is the output of the above example:
Class A Class CThe function B::f is not virtual. It hides A::f. Thus the compiler will not allow the function call b.f(). The function C::f is virtual; it overrides A::f even though A::f is not visible in C.
If you declare a base class destructor as virtual, a derived class destructor will override that base class destructor, even though destructors are not inherited.
No comments:
Post a Comment