07. Polimerphism
07. Polimerphism
Oriented
Programming
Using
C ++
Polymorphism
Abdul Wahab
Lecturer
University of Science and Technology Bannu
[email protected]
1
Polymorphism
2
Pointers to Base & Derived class objects.
A base class pointer can point to objects of Base class as well as to objects of Derived
class.
But a pointer to Derived class objects can not point to object of Base class as shown:
3
Example
class W
class X : public W
{
{
protected:
int x;
int w;
public:
public:
X (int j, int k): W(j)
W(int k)
{
{
x=k;
k = w;
}
}
void show()
void show ( )
{
{
cout<<“\n in class X”;
cout<<“\n in Base class W”;
cout<<“W= ”<<w;
cout<<“\n W= ”<<w;
cout<<“X= ”<<x;
}
}
};
}; Next slide
4
void main()
{
clrscr();
W objw(20), * b;
b = &objw;
b -> show();
X objx1(5,2);
b = &objx1;
b -> show();
X objx2(3,4);
X *d = &objx2;
d -> show();
// d = &objw will cause error
}
5
Virtual Function
We can define a virtual function in base class & can use the same function name
in any derived class, even if the number & type of argument are same.
Then the matching function of derived class “overrides” the base class function.
This is known as “Function overriding” .
6
Rules for virtual function
1. The virtual function should not be static & must be member of a class.
2. Constructor can not be declared as virtual.
3. Virtual function must be defined in public section.
4. In case the virtual function is defined outside the class, the “virtual” keyword is used in the
declaration & not in function declarator.
5. The prototype of virtual function in the base & derived classes should be exactly the same. In
case of mismatch, the compiler neglects the virtual function mechanism & treats them as
overloaded functions.
7
-
6. If a base class contains virtual function and if the same function is not redefined in the
derived class , in that case the base class function is invoked.
8
Example
class super
{
int b;
public:
super( ) {b = 10;}
virtual viod display( )
{
cout<<“In function display( ) class super”;
cout<<“\n B = ”<<b<<endl;
}
}; Next slide
9
class sub : public super
{
int d;
public:
sub( ) {d = 20;}
void display ( )
{
cout<<“In function display( ) class sub”;
cout<<“\n d = ”<<d<<endl;
}
}; Next slide
10
void main ( )
{
clrscr( );
super S, *p;
sub A; Try it practically
p = &S; p-> display( );
p = &A; p-> display( );
}
11
Have a Good Day!