Virtual Function
It’s a kind of member
function, declare within base class and
may be overrided in child class.
Used to get the
dynamic polymorphism.
* Static polymorphism (Early Binding): - what method has
to call , will decide at compile time.
* Dynamic polymorphism(Late Binding): - What method has to call, will decide at run time.
E.g.:
#include<iosream.h>
#include<conio.h>
class a
{
private:
virtual void display()
{
cout<<”base
class”;
}
};
class b: public a
{
public:
void display()
{
cout<<”child
class”;
}
};
void main()
{
clrscr();
a
*p;
b
x;
p=&x;
p->display();
getch();
}
*Rules : -
1.
Must be declare within
public.
2.
Can not be static and
friend function.
3.
Called by the use of
reference.
4.
It’s not mandatory to
override it.
5. A class can contain
virtual distructor but can’t be virtual construct.
6.
The prototype must be
same in child class, like base class.
*Abstract Class :-
There is two types of class :
i. Concreat class (by default) :
We can object it
contain concreat method (with Body)
i ii. Abstract Class :-
We can’t create object normally it contain pure virtual function or abstract method (only method declaration, not body)
We can’t create object normally it contain pure virtual function or abstract method (only method declaration, not body)
It can also contain
concreat method. This class is used to inherit.
The Child class need
to provide body for pure virtual. Function to create pure virtual function :-
Virtual void dispay ()
= 0;
The Class, that will
contain pure virtual function will be abstract class.
#include<iostream.h>
#include<conio.h>
class a
//abstract class
{
public:
virtual void
display()=0; //pure virtual
function
};
class b: public a
{
public:
void display()
{
cout<<”child
class”;
}
};
void main()
{
clrscr();
c
x;
x.display();
getch();
}
Abstract Class :-
Used to maintain
coding standard across the term or within the company.
class a
//abstract class
{
public:
virtual void
display()=0; //pure virtual
function
virtual void display2()
void display1() //concreat
{
Cout<<”hello”;
}
}
//Using function
return more than one value.
//without using return , you have o
return the value
#include<iostream.h>
#include<conio.h>
void sum(int x,int y)
{
int z=x+y;
cout<<z;
}
//call by reference
void sum1(int *x,int *y)
{
int z=*x+*y;
cout<<z;
}
void display(int *p,int *q)
{
*p=9999;
*q=4949;
}
void main()
{
clrscr();
int
a=20,b=30;
cout<<”a”<<a<<”b”<<b;
display(&a,&b);
cout<<endl<<a<<”
”<<b;
getch();
}
No comments:
Post a Comment