C++ provides a solution to invoke the exact version of the member function, which has to be decided at runtime using virtual functions. They are the means by which functions of the base class can be overridden by the functions of the derived class. The keyword virtual provides a mechanism for defining virtual functions. When declaring the base class
member function, the keyword virtual is used with those functions, which are to be bound dynamically.
The general syntax to declare a virtual function uses the following format:
class class_name //This denotes the base class of C++ virtual function
{
public:
virtual return_type member_function_name(arguments) //This denotes the C++
virtual function
{
…
…
}
};
Virtual functions should be define in the public section of a class to realize its full potential benefits. When such a declaration is made, it allows to decide which function to be used at runtime, based on the type of object, pointed to by the base pointer rather than the type of the pointer. The examples of virtual functions provided in this unit illustrate
the use of base pointer to point to different objects for executing different implementations of the virtual functions.
0 comments:
Post a Comment
Let us know your responses and feedback