Virtual Functions, Rules For Declaring Virtual Function With Examples and Program
Virtual Functions :-
1. Virtual functions are defined using the keyword “virtual” before function definition.
2. If we desire to call the Child class function using the pointer of Parent class then :-
1) In both the classes we have to define the function with same prototype.
2) In the Parent class we need to use “virtual” keyword during defining the function.
3) Now when we assign the address of Child class object to the pointer of the Parent class and using arrow operator we can call the function of the Child class.
1. Polymorphism is the ability to refer to objects of different classes.
2. A single pointer variable may be used to refer (base class pointer) to the objects of different classes.
3. A base pointer even made to contain the address of a derived class, but it always executes (links) the functions in the base class.
4. By using virtual functions to make the compiler to ignore the type of the pointer and choose the member function that matches the type of the object.
5. When we use the same function name in both the base and derived classes the function in base class is declared as virtual C++ determines which function to use at run time, based on the type of the object pointed to by the base pointer rather than the type of the pointer.
Rules for declaring virtual function:
(1) The virtual function must be member of some class.
(2) It can not be static.
(3) They are accessed by using object pointer .
(4) A virtual function can be friend of another class.
(5) The prototype of the base class version of the virtual function and all the derived class version must be identical. If the two function with same name but different prototype , c++ consider them as overloaded function and the virtual mechanism is ignored.
(6) We can not have virtual constructor but we can have virtual destructor.
Example:
#include<iostream.h>
#include<conio.h>
class Base
{
public:
virtual void display ()
{cout << "\n Display base ";}
virtual void show()
{cout << "\n show base";}
};
class Derived : public Base
{
public:
void display()
{cout <<"\n Display derived";}
void show()
{cout <<"\n show derived" ;}
};
class Derived1 : public Derived
{
public:
void display()
{cout <<"\n Display derived1";}
void show()
{cout <<"\n show derived1" ;}
};
void main()
{
clrscr();
Base B;
Derived D;
Derived1 d1;
Base *bptr;
cout <<"\n bptr points to Base \n";
bptr = &B;
bptr ->display(); //calls Base version
bptr ->show(); //calls base version
cout <<"\n\n bptr points to Derived\n";
bptr = &D;
bptr -> display(); //calls derive version
bptr ->show(); //calls Derived version
cout <<"\n\n bptr points to Derived1\n";
bptr = &d1;
bptr ->display(); //calls derive version
bptr ->show(); //calls Derived version
getch();
}
OUTPUT:
bptr points to Base
Display base.
Show base
bptr points to Derived
Display Derived.
Show Derived.
bptr points to Derived1
Display Derived1
Show Derived1.
Labels: C++