Composition

The concept of building (more complex) objects from other objects is known as composition.

 

Smaller specialised objects are created that perform one specific task and are then used as members of the complex object.

 

Composition creates objects that have the 'Has-A' relationship, such as a motorbike has an engine, or a plane has a wing, or a pub has a bar.

 

Composition also implies ownership, since when the complex object is created so are the subclasses, and accordingly die when the complex object dies.

 

 

Here we have an (RaceTeam) object called owner that uses another (Championship) object to keep track of the points accumulated:

#include <iostream>
#include <string>
using namespace std;
class Championship {
	private:
		int points;
	public:
		Championship() : points(0) {}
		Championship(int a) : points(a) {}
		//overload operator<< for object
		friend ostream& operator<<(ostream& out, const Championship &pts) {
			out << pts.getChampionship() ;
			return out;
		}
		void setChampionship(int b) { points += b; }
		int getChampionship() const {return points;}
};
class RaceTeam {
	private:
		string team;
		Championship total;
	public:
		RaceTeam() {}
		RaceTeam(string teamName, const Championship &here) : team(teamName), total(here) {}
		//overload operator<< for object
		friend ostream& operator<<(ostream& out, const RaceTeam &owner) {
			out << owner.team << " has " << owner.total << " points." ;
			return out;
		}
		void goChampionship(int c) { total.setChampionship(c); }
};
int main() {
	string name;
	int myPoints=0;

	cout << "What team do you ride for?" << endl ;
	cin >> name;

	RaceTeam owner(name, Championship(0));

	do {
		cout << owner << endl;
		cout << "How many points did you get in the last race (-1 to exit) : " << endl ;
		cin >> myPoints;
		owner.goChampionship(myPoints);
		} while (myPoints != -1) ;
	cout << "Thanks!" << endl ;
	return 0;
}

Compile & Run:

What team do you ride for?
Honda
Honda has 0 points.
How many points did you get in the last race (-1 to exit) :
20
Honda has 20 points.
How many points did you get in the last race (-1 to exit) :
25
Honda has 45 points.
How many points did you get in the last race (-1 to exit) :
25
Honda has 70 points.
How many points did you get in the last race (-1 to exit) : 
-1
Thanks!

Leave a Reply