Polymorphism - Sample tutorials
/* A base class of Shape gives rise to
two derived classes - Circle and Square.
An application called Polygon sets up an
array of Circles and Squares, and uses a
getarea method to find the area of each.
This getarea method is defined as a virtual
method in the base class, so that an array
of shapes CAN be defined on which two
different getarea methods can be run
depending on which type of shape is the
current one at the time. */
::::::::::::::
shape.h
::::::::::::::
#ifndef SHAPE
#define SHAPE 1
class Shape {
public:
void setsize(int owbig);
virtual float getarea() {};
protected:
int givensize;
};
#endif
::::::::::::::
shape.cpp
::::::::::::::
#include "shape.h"
void Shape::setsize(int sv) {
givensize = sv;
}
::::::::::::::
square.h
::::::::::::::
#include "shape.h"
class Square: public Shape {
public:
float getarea();
};
::::::::::::::
square.cpp
::::::::::::::
#include "square.h"
float Square::getarea() {
float result = givensize * givensize;
return (result);
}
::::::::::::::
circle.h
::::::::::::::
#include "shape.h"
class Circle: public Shape {
public:
float getarea();
};
::::::::::::::
circle.cpp
::::::::::::::
#include "circle.h"
float Circle::getarea() {
float result = 3.14159265f * givensize;
return result;
}
::::::::::::::
polygon.cpp
::::::::::::::
#include <iostream.h>
#include "circle.h"
#include "square.h"
main () {
int np = 10;
Shape *jigsaw[np];
for (int k=0; k<np; k+=2) {
jigsaw[k] = new Square();
jigsaw[k+1] = new Circle();
}
for (int k=0; k<np; k++) {
jigsaw[k]->setsize(10+k);
}
for (int k=0; k<np; k++) {
float syze = jigsaw[k]->getarea();
cout << "this is sq " << syze << endl;
}
return (0);
}
Reference:
//http://www.wellho.net/resources/ex.php4?item=c234/PMdemo
|
Submitted By:
Prof: Software Engineer
Tech: C ,Cpp
|