Hi Everybody
I wrote this program to experiment with dynamic binding. One class inherits from another which inherits from another. The user creates a new object of their choice at run time and 2 functions within that object should be called but it doesn't seem to be working out that way. Maybe the problem is with the pointer?
Can anyone help?
Thanks for your time!
#include <iostream>
using namespace std;
class shape
{
public:
shape(){cout << "Shape Constructor\n" ;}
~shape(){cout << "Shape Destructor\n" ;}
int calcArea();
void speak();
void setArea(int);
void nameOfShape();
protected:
int itsArea;
};
int shape::calcArea(){return itsArea;}
void shape::speak() {cout << "How can a shape speak?\n";}
void shape::setArea(int Area){itsArea=Area;}
void namOfShape(){cout << "shape\n";}
class rectangle : public shape
{
public:
rectangle(){cout << "Rectangle Constructor\n" ;}
~rectangle(){cout << "Rectangle Destructor\n" ;}
int calcArea();
void nameOfShape();
};
void namOfShape(){cout << "rectangle\n";}
int rectangle::calcArea()
{ int Area, width, length;
cout << "What's the width?\n";
cin >> width;
cout << "What's the length?\n";
cin >> length;
Area = width * length;
return Area;
}
class square:public rectangle
{
public:
square(){cout << "Square Constructor\n" ;}
~square(){cout << "Square Destructor\n" ;}
int calcArea();
void nameOfShape();
};
void namOfShape(){cout << "square\n";}
int calcArea()
{int c, side;
cout << "How long is the side of this square?\n";
cin >> side;
c = side * side;
return c;}
int callCalcArea(shape*);
void callNameShape(shape*);
int main ()
{
shape* ptr=0;
int choice;
while(1)
{
bool fQuit = false;
cout << "(0)Quit (1)Shape (2)Rectangle (3)Square:\n";
cin >> choice;
switch (choice)
{
case 0: fQuit = true;
break;
case 1: ptr = new shape;
break;
case 2: ptr = new rectangle;
break;
case 3: ptr = new square;
default: break;
}
if (fQuit == true)
break;
cout << "The area of the new " << callNameShape(ptr) << "is " << callCalcArea(ptr) << ".\n";
}
return 0;
}
int callCalcArea(shape *pShape1)
{pShape1->calcArea();}
void callNameShape(shape *pShape2)
{pShape2->nameOfShape();}