Run Time Polymorphism is usually achieved through the
use of inheritance and virtual functions.
Virtual functions essential and capable of supporting
run-time polymorphism whenever utilized by using a pointer.
Example:
#include<iostream.h>
#include<conio.h>
class A
{
Public:
virtual
void show ();
};
void A :: show ()
{
cout<<”Base
Class”;
}
class B public A
{
Public:
void
show ();
};
void B :: show ()
{
cout<<”Derived
Class”;
}
void main ()
{
clrscr
();
A *ptr;
A
ab;
B
ba;
ptr
= &ab;
ptr -> show ();
ptr = &ba;
ptr -> show ();
getch ();
}
Pure Virtual
Function and Abstract class with Example
Pure Virtual
Function
A
Pure Virtual Function is a type of function which has only a function
declaration. It does not have the function definition. The virtual function may
be equated to zero.
In
other words, any virtual function which is defined in the following manner in
the base class is known as Pure Virtual Function.
virtual return_datatype functionname () = 0;
Abstract class
An
abstract class is a class that is designed to be specifically used as a base
class. Any class which has a pure virtual function is known as Abstract class
and we cannot create the object of this class.
Example:
#include<iostream.h>
#include<conio.h>
class
media //class media
is Abstract class
{
public:
virtual void show () =
0;
};
class
book : public media
{
char
title[20];
char
tag[20];
double
price;
public:
void
get ();
void
show ();
};
void
book :: get ()
{
cout<<”Enter Book Title”;
cin>>title;
cout<<”Enter Book Tag”;
cin>>tag;
cout<<”Enter Book Price”;
cin>>price;
}
void
book :: show ()
{
cout<<”Title =”<<title<<”\n”;
cout<<”Tag =”<<tag<<”\n”;
cout<<”Price =”<<price<<”\n”;
}
class
tape : public media
{
char t[20];
char ta[20];
double pri;
public:
void getdata ();
void show ();
};
void
tape :: getdata ()
{
cout<<”Enter Tape Title”;
cin>>t;
cout<<”Enter Tape Tag”;
cin>>ta;
cout<<”Enter Tape Price”;
cin>>pri;
}
void
tape :: show ()
{
cout<<”Title =”<<t<<”\n”;
cout<<”Tag =”<<ta<<”\n”;
cout<<”Price =”<<pri<<”\n”;
}
void main ()
{
clrscr
();
media
*m;
book
b;
tape
t;
m
= &b;
b.get
();
m
-> show ();
m
= &t;
t.getdata
();
m
-> show ();
getch ();
}
No comments:
Post a Comment