FAQ 5.09 What is the purpose of composition?

Composition allows software to be developed by assembling existing components rather than crafting new ones.

Composition (sometimes called aggregation) is the process of putting an object (a part) inside another object (the composite). It models the has-a relationship. For example, a FordTaurus can be composed of, among other things, an Engine, Transmission, InstrumentPanel, and so on. In other words, a FordTaurus has an Engine (equivalently, an Engine is part-of a FordTaurus):

 #include <iostream> using namespace std; class Engine { public:   virtual void start(); }; void Engine::start() {   cout << "starting Engine\n"; } class FordTaurus { public:   virtual void start(); protected:   Engine engine_;    // An Engine is part of a FordTaurus }; void FordTaurus::start() {   cout << "starting FordTaurus\n";   engine_.start(); } int main() {   FordTaurus taurus;   taurus.start(); } 

Sometimes developers incorrectly use inheritance (kind-of) when they should use composition. For example, they might make FordTaurus inherit from Engine, which confuses kind-of with part-of.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net