Overriding:
If a function is declared as virtual
in the base class, it is virtual in all the derived classes. The redefinition
of a virtual function in a derived class is usually called overriding.
Requirement :
Provide a menu to the
user for the selection of shape and create the correspoding shape
#include "stdafx.h"
#include "conio.h"
#include <iostream>
using namespace std;
class Shape
{
public:
void
draw(){cout<<"Shape draw"<<endl;}
};
class Rectangle:public Shape
{
public:
void draw(){cout<<"Rectangle
draw"<<endl;}
};
class Circle:public Shape
{
public:
void draw()
{
cout<<"Circle draw"<<endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
int choice = 0;
cout<<"enter 1 for rectangle ,2 for circle"<<endl;
cin>>choice;
if(choice == 1)
{
Rectangle
R;
R.draw();
}
else if(choice == 2)
{
Circle
C;
s.draw();
}
else
cout<<"wrong selection"<<endl;
return 0;
}
In the above program,a
menu is provided to the user and based on selection,the draw method is called
using the corresponding object.
Requirement change:
Take all the inputs from
the user once and print the dimensions of all shapes in the same order.
#include <vector>
#include <string>
#include <iostream>
using namespace std;
class Shape
{
public:
void
draw(){cout<<"Shape draw"<<endl;}
};
class Rectangle:public Shape
{
public:
void draw(){cout<<"Rectangle
draw"<<endl;}
};
class Circle:public Shape
{
public:
void draw()
{
cout<<"Circle draw"<<endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
vector<Shape
*> shapelist;
Shape *s;
int choice = 1;
cout<<"enter 1 for rectangle ,2 for circle,0 for
exit"<<endl;
while(choice>0)
{
cin>>choice;
if(choice == 1)
{
Rectangle
R;
s=&R;
shapelist.push_back(s);
}
else if(choice == 2)
{
Circle
C;
s=&C;
shapelist.push_back(s);
}
else
break;
}
for(int i =0;i<shapelist.size();i++)
{
shapelist[i]->draw();
}
return 0;
}
In the above program,a call is made to the draw method using
the upcasted pointer.If a call is made to a non-virtual member of a class which
exists both in base and derived classes,the type of pointer decides the
method to be called.In this case,in both the occasions,a call to the base class
method is called.
To call methods of derived classes,add a keyword virtual in the base class.
0 comments:
Post a Comment