
CS2370 Prog 4
By:
mattfong on
May 2nd, 2011 | syntax:
None | size: 2.20 KB | hits: 32 | expires: Never
//Matthew Fong
//Program 4: Inheritance/polymorphism
//Description: Using inheritance and polymorphism to show an array of ships
#ifndef SHIP_H_INCLUDED
#define SHIP_H_INCLUDED
#include <iostream>
#include <string>
using namespace std;
class Ship
{
protected:
string name;
string year;
public:
Ship(string n, string y)
{
name = n;
year = y;
}
virtual void print()
{
cout << "Ship's name: " << name << endl;
cout << "Year built: " << year << endl;
cout << endl;
}
};
class CruiseShip : public Ship
{
private:
int maxPassenger;
public:
CruiseShip(int m, string n, string y) : Ship(n, y)
{
maxPassenger = m;
}
void print()
{
cout << "Ship's name: " << name << endl;
cout << "Year built: " << year << endl;
cout<< "Maximum Passengers: " << maxPassenger << endl;
cout << endl;
}
};
class CargoShip : public Ship
{
private:
int tons;
public:
CargoShip(int t, string n, string y) : Ship(n, y)
{
tons = t;
}
void print()
{
cout << "Ship's name: " << name << endl;
cout << "Year built: " << year << endl;
cout << "Maximum capacity: " << tons << " tons" << endl;
cout << endl;
}
};
#endif // SHIP_H_INCLUDED
#include "ship.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
Ship *array[3]; //creates an array of pointers
Ship *fishing = new Ship ("Northwestern", "1977"); //Creates a pointer to the Ship
Ship *cruise = new CruiseShip(1500, "Carnival Dream", "2009"); //Creates a pointer to the CruiseShip
Ship *cargo = new CargoShip(250000, "APM-Maersk", "2003"); //Creates a pinter to the CargoShip
array[0] = fishing; //Puts in the pointer to Ship
array[1] = cruise; //Puts in the pointer to CruiseShip
array[2] = cargo; //Puts in the pointer to CargoShip
for(int i = 0; i < 3; i++)
{
array[i]->print();
}
}