Академический Документы
Профессиональный Документы
Культура Документы
Functions
And
Polymorphism
By
Bhagwant Singh
Contents
Virtual
Functions
Pure Virtual Functions
Virtual Constructor and Destructor.
Polymorphism
Runtime Or Dynamic Polymorphism
Virtual Function
In object-oriented programming, a virtual
function or virtual method is a function or
method whose behavior can be overridden
within an inheriting class by a function
with the same signature.
If the base class pointer has the address of
the derived class pointer will execute the
function in the base class.
The complier simply ignore the contents of
the pointer choose the member function
that matches the type of the pointer.
Example
Include<iostream>
Using namespace std
Class Bass
{
Public:
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(){ \n show Derived
};
Int main()
{
Base B;
Derived D;
Base *bptr;
Cout<<\n bptr points to base \n;
bptr = &B;
bptr-> display();
bptr->show();
Cout<<\n bptr points to derived \n;
bptr = &D;
bptr-> display();
bptr->show();
Return 0;
}
Output
bptr points to base
Display Base
show Base
bptr points to derived
Display Base
show derived
void
return type
display() =
function
Declaration
Definition
Example
#include<iostream>
Using namespace std;
Class Bala
{
public:
virtual void example()=0;
};
Class C: public Bala
{
Public:
Void example()
{
Cout<<This is derived one
\n;
}
};
Example
#include<iostream>
Using namespace std;
Class A
{
Public:
~A();
};
Class B
{
Public:
~B();
};
Void Main()
{
A *ptr = new B();
..
..
.
..
Delete ptr;
}
Output
Only
base class
destructor will be
called and it will
result in waste
memory.
If
we made base
class destructor as
virtual both the
destructor will be
called in the same
manner as that of
constructor
created