16.2 — Composition – Learn C++ (2023)

Object composition

In real-life, complex objects are often built from smaller, simpler objects. For example, a car is built using a metal frame, an engine, some tires, a transmission, a steering wheel, and a large number of other parts. A personal computer is built from a CPU, a motherboard, some memory, etc… Even you are built from smaller parts: you have a head, a body, some legs, arms, and so on. This process of building complex objects from simpler ones is called object composition.

Broadly speaking, object composition models a “has-a” relationship between two objects. A car “has-a” transmission. Your computer “has-a” CPU. You “have-a” heart. The complex object is sometimes called the whole, or the parent. The simpler object is often called the part, child, or component.

In C++, you’ve already seen that structs and classes can have data members of various types (such as fundamental types or other classes). When we build classes with data members, we’re essentially constructing a complex object from simpler parts, which is object composition. For this reason, structs and classes are sometimes referred to as composite types.

Object Composition is useful in a C++ context because it allows us to create complex classes by combining simpler, more easily manageable parts. This reduces complexity, and allows us to write code faster and with less errors because we can reuse code that has already been written, tested, and verified as working.

Types of object composition

There are two basic subtypes of object composition: composition and aggregation. We’ll examine composition in this lesson, and aggregation in the next.

A note on terminology: the term “composition” is often used to refer to both composition and aggregation, not just to the composition subtype. In this tutorial, we’ll use the term “object composition” when we’re referring to both, and “composition” when we’re referring specifically to the composition subtype.


(Video) LEARNING C++ with Java/C#/Python Experience // Code Review

To qualify as a composition, an object and a part must have the following relationship:

  • The part (member) is part of the object (class)
  • The part (member) can only belong to one object (class) at a time
  • The part (member) has its existence managed by the object (class)
  • The part (member) does not know about the existence of the object (class)

A good real-life example of a composition is the relationship between a person’s body and a heart. Let’s examine these in more detail.

Composition relationships are part-whole relationships where the part must constitute part of the whole object. For example, a heart is a part of a person’s body. The part in a composition can only be part of one object at a time. A heart that is part of one person’s body can not be part of someone else’s body at the same time.

In a composition relationship, the object is responsible for the existence of the parts. Most often, this means the part is created when the object is created, and destroyed when the object is destroyed. But more broadly, it means the object manages the part’s lifetime in such a way that the user of the object does not need to get involved. For example, when a body is created, the heart is created too. When a person’s body is destroyed, their heart is destroyed too. Because of this, composition is sometimes called a “death relationship”.

And finally, the part doesn’t know about the existence of the whole. Your heart operates blissfully unaware that it is part of a larger structure. We call this a unidirectional relationship, because the body knows about the heart, but not the other way around.

Note that composition has nothing to say about the transferability of parts. A heart can be transplanted from one body to another. However, even after being transplanted, it still meets the requirements for a composition (the heart is now owned by the recipient, and can only be part of the recipient object unless transferred again).

Our ubiquitous Fraction class is a great example of a composition:

class Fraction{private:int m_numerator;int m_denominator; public:Fraction(int numerator=0, int denominator=1): m_numerator{ numerator }, m_denominator{ denominator }{}};

This class has two data members: a numerator and a denominator. The numerator and denominator are part of the Fraction (contained within it). They can not belong to more than one Fraction at a time. The numerator and denominator don’t know they are part of a Fraction, they just hold integers. When a Fraction instance is created, the numerator and denominator are created. When the fraction instance is destroyed, the numerator and denominator are destroyed as well.

While object composition models has-a type relationships (a body has-a heart, a fraction has-a denominator), we can be more precise and say that composition models “part-of” relationships (a heart is part-of a body, a numerator is part of a fraction). Composition is often used to model physical relationships, where one object is physically contained inside another.

(Video) 16.2.1 Practice - Conversions Between Objects and Basic Types

The parts of a composition can be singular or multiplicative -- for example, a heart is a singular part of the body, but a body contains 10 fingers (which could be modeled as an array).

Implementing compositions

Compositions are one of the easiest relationship types to implement in C++. They are typically created as structs or classes with normal data members. Because these data members exist directly as part of the struct/class, their lifetimes are bound to that of the class instance itself.

Compositions that need to do dynamic allocation or deallocation may be implemented using pointer data members. In this case, the composition class should be responsible for doing all necessary memory management itself (not the user of the class).

In general, if you can design a class using composition, you should design a class using composition. Classes designed using composition are straightforward, flexible, and robust (in that they clean up after themselves nicely).

More examples

Many games and simulations have creatures or objects that move around a board, map, or screen. One thing that all of these creatures/objects have in common is that they all have a location. In this example, we are going to create a creature class that uses a point class to hold the creature’s location.

First, let’s design the point class. Our creature is going to live in a 2d world, so our point class will have 2 dimensions, X and Y. We will assume the world is made up of discrete squares, so these dimensions will always be integers.


(Video) Back to Basics: Debugging in C++ - Mike Shah - CppCon 2022

#ifndef POINT2D_H#define POINT2D_H#include <iostream>class Point2D{private: int m_x; int m_y;public: // A default constructor Point2D() : m_x{ 0 }, m_y{ 0 } { } // A specific constructor Point2D(int x, int y) : m_x{ x }, m_y{ y } { } // An overloaded output operator friend std::ostream& operator<<(std::ostream& out, const Point2D& point) { out << '(' << point.m_x << ", " << point.m_y << ')'; return out; } // Access functions void setPoint(int x, int y) { m_x = x; m_y = y; }};#endif

Note that because we’ve implemented all of our functions in the header file (for the sake of keeping the example concise), there is no Point2D.cpp.

This Point2d class is a composition of its parts: location values x and y are part-of Point2D, and their lifespan is tied to that of a given Point2D instance.

Now let’s design our Creature. Our Creature is going to have a few properties: a name, which will be a string, and a location, which will be our Point2D class.


#ifndef CREATURE_H#define CREATURE_H#include <iostream>#include <string>#include "Point2D.h"class Creature{private: std::string m_name; Point2D m_location;public: Creature(const std::string& name, const Point2D& location) : m_name{ name }, m_location{ location } { } friend std::ostream& operator<<(std::ostream& out, const Creature& creature) { out << creature.m_name << " is at " << creature.m_location; return out; } void moveTo(int x, int y) { m_location.setPoint(x, y); }};#endif

This Creature is also a composition of its parts. The creature’s name and location have one parent, and their lifetime is tied to that of the Creature they are part of.

And finally, main.cpp:

#include <string>#include <iostream>#include "Creature.h"#include "Point2D.h"int main(){ std::cout << "Enter a name for your creature: "; std::string name; std::cin >> name; Creature creature{ name, { 4, 7 } }; while (true) { // print the creature's name and location std::cout << creature << '\n'; std::cout << "Enter new X location for creature (-1 to quit): "; int x{ 0 }; std::cin >> x; if (x == -1) break; std::cout << "Enter new Y location for creature (-1 to quit): "; int y{ 0 }; std::cin >> y; if (y == -1) break; creature.moveTo(x, y); } return 0;}

Here’s a transcript of this code being run:

Enter a name for your creature: MarvinMarvin is at (4, 7)Enter new X location for creature (-1 to quit): 6Enter new Y location for creature (-1 to quit): 12Marvin is at (6, 12)Enter new X location for creature (-1 to quit): 3Enter new Y location for creature (-1 to quit): 2Marvin is at (3, 2)Enter new X location for creature (-1 to quit): -1

Variants on the composition theme

Although most compositions directly create their parts when the composition is created and directly destroy their parts when the composition is destroyed, there are some variations of composition that bend these rules a bit.

(Video) CppCon 2017: Bjarne Stroustrup “Learning and Teaching Modern C++”

For example:

  • A composition may defer creation of some parts until they are needed. For example, a string class may not create a dynamic array of characters until the user assigns the string some data to hold.
  • A composition may opt to use a part that has been given to it as input rather than create the part itself.
  • A composition may delegate destruction of its parts to some other object (e.g. to a garbage collection routine).

The key point here is that the composition should manage its parts without the user of the composition needing to manage anything.

Composition and class members

One question that new programmers often ask when it comes to object composition is, “When should I use a class member instead of direct implementation of a feature?”. For example, instead of using the Point2D class to implement the Creature’s location, we could have instead just added 2 integers to the Creature class and written code in the Creature class to handle the positioning. However, making Point2D its own class (and a member of Creature) has a number of benefits:

  1. Each individual class can be kept relatively simple and straightforward, focused on performing one task well. This makes those classes easier to write and much easier to understand, as they are more focused. For example, Point2D only worries about point-related stuff, which helps keep it simple.
  2. Each class can be self-contained, which makes them reusable. For example, we could reuse our Point2D class in a completely different application. Or if our creature ever needed another point (for example, a destination it was trying to get to), we can simply add another Point2D member variable.
  3. The outer class can have the class members do most of the hard work, and instead focus on coordinating the data flow between the members . This helps lower the overall complexity of the outer class, because it can delegate tasks to its members, who already know how to do those tasks. For example, when we move our Creature, it delegates that task to the Point class, which already understands how to set a point. Thus, the Creature class does not have to worry about how such things would be implemented.


A good rule of thumb is that each class should be built to accomplish a single task. That task should either be the storage and manipulation of some kind of data (e.g. Point2D, std::string), OR the coordination of its members (e.g. Creature). Ideally not both.

In this case of our example, it makes sense that Creature shouldn’t have to worry about how Points are implemented, or how the name is being stored. Creature’s job isn’t to know those intimate details. Creature’s job is to worry about how to coordinate the data flow and ensure that each of the class members knows what it is supposed to do. It’s up to the individual classes to worry about how they will do it.

Next lesson16.3AggregationBack to table of contentsPrevious lesson16.1Object relationships
(Video) From C ➡️ C++ ➡️ Rust


Does C++ have composition? ›

Composition in C++ is also referred to as object composition. The object composition concept work on the model of has-a relationship among two different objects. Complex objects are often referred to as parent components while objects which are simpler or smaller are often referred to as child components.

How to learn C++ fast? ›

How to Succeed in the Study of C++
  1. Learn the syntax.
  2. Master basics such as functions, arrays and strings.
  3. Take advantage of resources like online tutorials, books and lectures.
  4. Be persistent. Coding, like many skills, takes time to learn. Don't be afraid to make mistakes.
Nov 11, 2020

What is aggregation in C++ with example? ›

In C++, aggregation is a process in which one class defines another class as any entity reference. It is another way to reuse the class. It is a form of association that represents HAS-A relationship.

How to learn C C++ in online free? ›

LearnCpp.com is a free website that teaches the basics of C++. You'll explore the context around what C++ is, how it came about, how programs work, and what software you need to install to create your own programs, and then learn the steps of writing, compiling, and debugging C++ programs.

Is C++ hard than Python? ›

Is C++ Harder Than Python? Yes, C++ is harder to learn and work with than Python . The biggest difference is that C++ has a more complex syntax to work with and involves more memory management than Python, which is both simple to learn and use. Python is considered a better beginner programming language.

Is C++ stronger than Python? ›

C++ is faster than Python because it is statically typed, which leads to a faster compilation of code. Python is slower than C++, it supports dynamic typing, and it also uses the interpreter, which makes the process of compilation slower.

Can C++ be self taught? ›

The easiest way to learn C++ is to sign up for an in-depth course that can teach you everything you need to know to master C++. Can you teach yourself C++? Yes, you can teach yourself C++, especially if you're already familiar with coding. However, it may take longer than attending a course, for example.

Is C++ the hardest programming language? ›

The applications such as Google Chromium and a few Microsoft applications are developed using C++. It is one of the hardest programming languages because it has a complex syntax to support versatility. And it is best learned by those who have an understanding of C programming.

How long does it take to become fluent in C++? ›

Is C++ hard to learn?
Programming levelTime it'll take
Absolute beginnerAt least 3 months
Already a programmer1 - 3 months
Building mastery in C++2 years - forever
Feb 8, 2021

What are the 3 examples of aggregate? ›

Examples of aggregate materials include:
  • Crushed rock - These products are obtained by extracting rocks and crushing them to the desired size and texture. ...
  • Sand - Sand is found in nature. ...
  • Gravel - Gravel deposits are produced by a natural process of moisture and erosion.

What is the difference between composition and aggregation in C++? ›

Association between two objects that illustrate the “has-a” relationship is called Aggregation. A composition defines a part-of a relationship, and both the entities are connected to each other.

What is aggregation in OOP? ›

Aggregation in object oriented programming

Aggregation is a specialized form of association between two or more objects in which each object has its own life cycle but there exists an ownership as well. Aggregation is a typical whole/part or parent/child relationship but it may or may not denote physical containment.

Can I start learn C++ without knowing C? ›

There is no need to learn C before learning C++. They are different languages. It is a common misconception that C++ is in some way dependent on C and not a fully specified language on its own. Just because C++ shares a lot of the same syntax and a lot of the same semantics, does not mean you need to learn C first.

Can I learn C++ in a month? ›

It takes around 1 to 3 months to learn the basics and syntax of C++ programming. Gaining mastery in the C++ programming language can take around 2 years.

How can I practice C++ at home? ›

C++ Basic: Exercises, Practice, Solution
  1. Write a program in C++ to print a welcome text in a separate line. ...
  2. Write a program in C++ to print the sum of two numbers. ...
  3. Write a program in C++ to find Size of fundamental data types. ...
  4. Write a program in C++ to print the sum of two numbers using variables.
Aug 19, 2022

Can I get job with C++? ›

Job opportunities: C++ is a very popular coding language, and millions of programmers use it in companies all over the world. This means that there are often many work opportunities for skilled C++ programmers.

Why is C++ so tough? ›

C++ is hard to learn because of its multi-paradigm nature and more advanced syntax. While it's known to be especially difficult for beginners to learn, it's also difficult for programmers with no experience with low-level languages.

What is the No 1 programming language? ›

JavaScript is the most common coding language in use today around the world.
What this language is used for:
  • Web development.
  • Game development.
  • Mobile apps.
  • Building web servers.

Is C++ tougher than Java? ›

Most experts will tell you that Java is easier to learn. It's a newer language than C++ and isn't as complex in its principles or execution. However, there's more to consider than a language's learning curve. Selecting a programming language comes down to what you want to do with it.

What pays more C++ or Python? ›

C++ vs Python Salaries: C++

According to Indeed, C++ developer salaries average $117,000 a year. Python developer salaries average $109,000 a year. These salaries do vary, but in general, the top-paid C++ developer is likely to make more than the top-paid Python developer.

What is fastest programming language? ›

Go, also known as Golang, is a programming language developed by Google. It compiles to Assembly like most of the other languages here, but it has more modern features, simpler syntax, and is easier to write than the long-time leader of fast programming languages, C/C++.

Is studying C++ worth it? ›

It is a versatile language, so it remains in high demand amongst professionals, such as software developers, game developers, C++ analysts and backend developers, etc. As per the TIOBE index of 2022, C++ lies at 4th position in the world's most popular language.

Why is C++ so hard to learn for beginners? ›

C++'s syntax itself isn't hard to learn, especially if you already know C. However, the versatility that makes C++ such a powerful and interesting language is itself the reason why many people find it hard.

Is learning C++ profitable? ›

Yes, learning C++ is worth it. It is a good choice if you want to work with robotics, backend development, embedded systems, mobile development, finance, or algorithmic trading.

Is coding job stressful? ›

In general, coding is a fairly relaxing job. There is the flexibility of working remotely as a programmer, and in many cases there is the security of routine. However, as with any job, whether coding is stressful depends largely on the company you work with. Cultural pressures and tight deadlines can cause stress.

What is hardest code to learn? ›


Fun fact is two years were taken to the first Malbolge program, and with that, you can understand why some programmers consider this language the hardest programming language. It is said that Ben Olmstead has never written even a single Malbolge program.

Are C++ developers in demand? ›

C++ Developers are much in demand, and they enjoy some of the high-paying jobs in the industry. The average base pay of a C++ developer is about $103,035 per year.

How much does a C++ programmer make a year? ›

How much does a C++ Programmer make in the United States? The average C++ Programmer salary in the United States is $78,054 as of December 27, 2022, but the salary range typically falls between $70,077 and $82,457.

Is C++ high paying? ›

8 - C/C++ C/C++ holds a solid top 8 spot with an average salary of ~$109K per year. Its usage in the industry is widely extended, C++ can be found on video games, servers, databases, space probes and many others.

Is C++ easier to learn than Python? ›

Python's syntax is a lot closer to English and so it is easier to read and write, making it the simplest type of code to learn how to write and develop with. The readability of C++ code is weak in comparison and it is known as being a language that is a lot harder to get to grips with.

What are the 2 types of aggregates? ›

Types of aggregates include Coarse aggregate and fine aggregate. The aggregate of each type is further sub-divided into many types and classification based on its size.

What is the most commonly used aggregate? ›

The most commonly used aggregates—sand, gravel, crushed stone, and air-cooled blast-furnace slag—produce freshly mixed normal-weight concrete with a density (unit weight) of 2200 to 2400 kg/m3 (140 to 150 lb/ft3). Aggregates of expanded shale, clay, slate, and slag (Fig.

What is Type 1 aggregate? ›

MOT Type 1 aggregate is an approved granular sub-base material that is created using recycled crushed concrete and rubble. It's made up of a mix of larger 40mm pieces right down to dust which compacts well to form a solid base, making it a great option to use on: Roads.

Why composition is better than inheritance in C++? ›

Composition offers better test-ability of a class than Inheritance. If one class consists of another class, you can easily construct a Mock Object representing a composed class for the sake of testing. This privilege is not given by inheritance.

Why is composition better than inheritance? ›

One more benefit of composition over inheritance is testing scope. Unit testing is easy in composition because we know what all methods we are using from another class. We can mock it up for testing whereas in inheritance we depend heavily on superclass and don't know what all methods of superclass will be used.

Which is stronger aggregation or composition? ›

The composition is stronger than Aggregation. In Short, a relationship between two objects is referred to as an association, and an association is known as composition when one object owns another while an association is known as aggregation when one object uses another object.

What Cannot be used for polymorphism? ›

Which among the following can't be used for polymorphism? Explanation: Static member functions are not property of any object. Hence it can't be considered for overloading/overriding.

What is the difference between aggregation and abstraction? ›

Aggregation is an abstraction which turns a relationship between objects into an aggregate object. Generalization is an abstraction which turns a class of objects into a generic object.

What is polymorphism in oops? ›

Polymorphism is one of the core concepts of object-oriented programming (OOP) and describes situations in which something occurs in several different forms. In computer science, it describes the concept that you can access objects of different types through the same interface.

Does C++ have built in graphics? ›

C++ does not have any built-in functions to perform drawing as they have low-level programs to use; instead, we can use API to do graphics. Few Graphics attributes are: setcolor(color), setbkcolor(color), setlinestyle(style, pattern,thickness).

What is a composite class C++? ›

Composite in C++

Composite is a structural design pattern that allows composing objects into a tree-like structure and work with the it as if it was a singular object. Composite became a pretty popular solution for the most problems that require building a tree structure.

What is difference between composition and inheritance in C++? ›

The difference between inheritance and composition is that classes and objects in inheritance code are tightly coupled, meaning that they should not be changed because changing the parent or superclass risks changing the sub-class, or child class, thus breaking your code.

Does C# have composition? ›

Composition in C# is a way of creating a relationship between two classes that one or greater than one nested objects are a part of the related class, and the logical existence of class becomes impossible without the nested objects.

Do games still use C++? ›

C++ plays an important role in today's game development ecosystem. C++ is used in the source code of many major game engines, such as Unreal and Unity, allowing developers to build more high-performant games.

Are most games made in C++? ›

Most game engines are made with C++ because it provides a combination of the Object Oriented paradigm with the bare metal control of manual memory management. As far as game development goes, are the C++ and C# programming languages going to be around a while longer?

Why C++ is not used in development? ›

Since C++ is closer to C than high-level languages, the code is rather detailed. Therefore, it can be hard for developers to orient in large projects. Slower development times. It is reasonably faster to use high-level languages like Java and Python for creating applications.


1. Where CPP is Used, Why Learn C++ Programming Language | Video Tutorial
2. C++ Full Course for Beginners (Hindi) | Learn Coding
(Learn Coding)
3. Basic C++ for robotics: Arrays and Pointers, Part 1 | ROS Developers Live Class # 112
(The Construct)
4. C++ or Java | Which coding language to learn?
(Apna College)
5. Blueprints vs. C++: How They Fit Together and Why You Should Use Both
(Alex Forsythe)
6. OpenGL Course - Create 3D and 2D Graphics With C++
Top Articles
Latest Posts
Article information

Author: Msgr. Refugio Daniel

Last Updated: 10/15/2022

Views: 6337

Rating: 4.3 / 5 (54 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Msgr. Refugio Daniel

Birthday: 1999-09-15

Address: 8416 Beatty Center, Derekfort, VA 72092-0500

Phone: +6838967160603

Job: Mining Executive

Hobby: Woodworking, Knitting, Fishing, Coffee roasting, Kayaking, Horseback riding, Kite flying

Introduction: My name is Msgr. Refugio Daniel, I am a fine, precious, encouraging, calm, glamorous, vivacious, friendly person who loves writing and wants to share my knowledge and understanding with you.