Friday, November 20, 2015

Virtual Functions

Virtual Function
A Virtual function is a function which is declared in base class using the keyword virtual. We write the body of virtual function in the derived classes. Its purpose is to tell the compiler that what function we would like to call on the basis of the object of derived class. C++ determines which function to call at run time on the type of object pointer to.
=============
The way to retain the behavior of the object’s instantiated type is through the use of virtual functions. To declare a method to be a virtual function, you simply use the virtual keyword when declaring the method in the class definition. When you call a function, it will check the dynamic type of the object before choosing which function to call—this process is called reification.

It is important that you declare the function to be virtual throughout your class hierarchy, or its behavior will be quite unexpected. A virtual method can call a nonvirtual method and vice-versa. Overloaded operator functions can be virtual functions, but static methods can’t be.
A constructor cannot be a virtual function because it needs to know the exact type to create. However, a destructor can be declared as virtual, and generally should be. virtual functions may not seem significant at first, but they enable a ton of code reuse when using class hierarchies. und Circle, Shape, and Rectangle objects, the client doesn’t have to as long as all of the relevant functions are virtual==========
===================

No comments:

Post a Comment