From Wikibooks, open books for an open world
Jump to navigation Jump to search

C++ Programming/Programming Languages/Introducing C++/Examples/Hello World


In computer science, object composition (not to be confused with function composition) is a way and practice to combine simple objects or data types into more complex ones. Compositions are a critical building block of many basic data structures, including the tagged union, the linked list, and the binary tree, as well as the object used in object-oriented programming.

Composition is contrasted with subtyping, which is the process of adding detail to a general data type to create a more specific data type. In composition, the composite type "has an" object of a simpler type, while in subtyping, the subtype "is an" instance of its parent type. Composition does not form a subtype but a new type.

A real-world example of composition may be seen in an automobile: the objects wheel, steering wheel, seat, gearbox and engine may have no functionality by themselves, but if you compose them, they may form an automobile object, which has a higher function, greater than the sum of its parts in a trite sense.

Composited (composed) objects are called fields, items, members or attributes, and the resulting composition a structure, storage record, tuple, user-defined type (UDT), or composite type. The terms usually vary across languages. Fields are given a unique name so that each one can be distinguished from the others. Sometimes an issue of ownership arises: when a composition is destroyed, should objects belonging to it be destroyed as well? If not, the case is sometimes called aggregation. For more, see the aggregation section below.