Virtual Function In C++
A
virtual function is a member function which is declared within a base class and
is re-defined(Overriden) by a derived class. When you refer to a derived class
object using a pointer or a reference to the base class.
·
Functions are declared with a virtual keyword in base class.
·
The resolving of function call is
done at Run-time.
Fig: Virtual Function In C++ |
Rules for Virtual Functions
1.
Virtual functions cannot be static
and also cannot be a friend function of another class.
2.
Virtual functions should be accessed
using pointer or reference of base class type to achieve run time polymorphism.
3.
The prototype of virtual functions
should be same in base as well as derived class.
4.
They are always defined in base
class and overridden in derived class
5.
A class may have virtual
destructor but it cannot have a virtual constructor.
Program:
#include<iostream.h>
#include<conio.h>
Class abc
{
public:
virtual void input()
{
cout<<”example of
virtual function”;
}
};
class bca: public abc
{
public:
void input()
{
Cout<<”derived
class of virtual function”;
}
};
Void main()
{
abc *a1;
bca a2;
a1=&a2;
getech();
}
Output:
Derived class of
virtual function
No comments:
Post a Comment