




MAIN.CXX
One of the most powerful tools of Object Oriented Programing is called polymorphism.
Polymorphism allows you to point to any object derived from the type of your pointer.
This means that we can derive another class from ball and handle it similiarly in our vector.
#include <vector.h>
#include <iostream.h>
#include "gravityBall.h"
int main (void)
{
sphere mySphere;
mySphere.setRadius(10.0);
cout << "mySphere has radius: " << mySphere.getRadius() << endl;
sphere myOtherSphere;
myOtherSphere.copy(mySphere);
myOtherSphere.setPosition(3.0,4.0,10.0);
cout << "myOtherSphere has radius: " << myOtherSphere.getRadius() << endl;
cout << "myOtherSphere has X position: " << myOtherSphere.getXPosition() << endl;
vector<ball*> myBallArray;
//create a new ball
myBallArray.push_back(new ball);
//initialize the ball position
myBallArray.front()->setPosition(3.0,4.0,10.0);
myBallArray.front()->setRadius(20.0);
myBallArray.front()->setVelocity(0.2,0.0,1.0);
while (1)
{
//report the ball position and velocity of the last ball created
cout << "ballNumber: " << myBallArray.size()-1 << endl;
cout << "myBall has position X: " << myBallArray.back()->getXPosition();
cout << " Y: " << myBallArray.back()->getYPosition();
cout << " Z: " << myBallArray.back()->getZPosition() << endl;
cout << "myBall has velocity X: " << myBallArray.back()->getXVelocity();
cout << " Y: " << myBallArray.back()->getYVelocity();
cout << " Z: " << myBallArray.back()->getZVelocity() << endl;
vector<ball*>::iterator i;
for (i=myBallArray.begin(); i!=myBallArray.end(); i++)
{
//simulate the ball flight
(*i)->fall();
//delete the ball if resting
if ((*i)->getZPosition() <= 0.0)
{
//delete the ball from memory
delete (*i);
//delete the ball from the vector
myBallArray.erase(i);
}
}
//generate a random number between 0 and 100
int randomNumber = random()%100;
//create a new ball 25 percent of the time
if (randomNumber < 25)
{
//create a new ball
myBallArray.push_back(new ball);
//initialize the ball position
myBallArray.back()->setPosition(3.0,4.0,10.0);
myBallArray.back()->setRadius(20.0);
myBallArray.back()->setVelocity(0.2,0.0,1.0);
}
//and, create a new gravity ball 25 percent of the time
else if (randomNumber < 50)
{
//create a new ball
myBallArray.push_back(new gravityBall);
//initialize the ball position
myBallArray.back()->setPosition(3.0,4.0,10.0);
myBallArray.back()->setRadius(20.0);
myBallArray.back()->setVelocity(0.2,0.0,1.0);
}
}
};