{"id":4910,"date":"2025-02-26T09:00:00","date_gmt":"2025-02-26T04:00:00","guid":{"rendered":"https:\/\/afzalbadshah.com\/?p=4910"},"modified":"2024-12-31T08:43:14","modified_gmt":"2024-12-31T03:43:14","slug":"composition-and-aggregation-in-c","status":"publish","type":"post","link":"https:\/\/afzalbadshah.com\/index.php\/2025\/02\/26\/composition-and-aggregation-in-c\/","title":{"rendered":"Composition and Aggregation in C++"},"content":{"rendered":"\n<p>In Object-Oriented Programming (OOP), <strong>Composition<\/strong> and <strong>Aggregation<\/strong> describe relationships between classes, specifically how objects are associated with one another. Both are forms of the &#8220;has-a&#8221; relationship, but they differ in strength and dependency. So in this article we will see the concept of Composition and Aggregation in C++ and also check the difference between Composition and Aggregation.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>What is Composition?<\/strong><\/h3>\n\n\n\n<p>Composition represents a <strong>strong relationship<\/strong> between two classes. It is used when an object (child) is a part of another object (parent), and the child object <strong>cannot exist independently<\/strong> of the parent. The lifecycle of the child object is tied to the lifecycle of the parent. If the parent object is destroyed, the child object is also destroyed.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Key Characteristics of Composition:<\/strong><\/h4>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Strong Dependency:<\/strong>\n<ul class=\"wp-block-list\">\n<li>The parent object owns the child object. The child cannot exist without the parent.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Lifecycle Management:<\/strong>\n<ul class=\"wp-block-list\">\n<li>The lifecycle of the child object is bound to the parent. Destroying the parent automatically destroys the child.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Real-World Example:<\/strong>\n<ul class=\"wp-block-list\">\n<li>A car and its engine. The engine is a part of the car, and without the car, the engine serves no purpose.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Example Code: Composition in C++<\/strong><\/h4>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>#include &lt;iostream&gt;<br>#include &lt;string&gt;<br>using namespace std;<br>\/\/ Engine class representing a part of a Car<br>class Engine {<br>private:<br>    string type;<br>public:<br>    \/\/ Constructor to initialize the engine type<br>    Engine(const string&amp; type) : type(type) {}<br>    void start() const {<br>        cout &lt;&lt; \"Engine of type \" &lt;&lt; type &lt;&lt; \" is starting.\" &lt;&lt; endl;<br>    }<br>    string getType() const {<br>        return type;<br>    }<br>};<br>\/\/ Car class using Composition<br>class Car {<br>private:<br>    Engine engine; \/\/ Car \"has-an\" Engine (composition relationship)<br>public:<br>    \/\/ Constructor to initialize the car with an engine<br>    Car(const string&amp; engineType) : engine(engineType) {}<br>    void startCar() const {<br>        cout &lt;&lt; \"Car is starting.\" &lt;&lt; endl;<br>        engine.start(); \/\/ Car depends on the engine's functionality<br>    }<br>    void showDetails() const {<br>        cout &lt;&lt; \"Car with engine type: \" &lt;&lt; engine.getType() &lt;&lt; endl;<br>    }<br>};<br><br>int main() {<br>    \/\/ Create a car with an engine<br>    Car car(\"V8\");<br>    \/\/ Start the car and display its details<br>    car.startCar();<br>    car.showDetails();<br>    return 0;<br>}<br><\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Explanation of Composition Code:<\/strong><\/h4>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong><code>Engine<\/code> Class:<\/strong><br>Represents an engine with:<br>A <code>type<\/code> property to store the type of engine.<br>Methods <code>getType()<\/code> and <code>start()<\/code> to provide engine-specific functionalities.<\/li>\n\n\n\n<li><strong><code>Car<\/code> Class:<\/strong><br>Represents a car containing an <code>Engine<\/code> object. It has:<br>A constructor to initialize the <code>Car<\/code> object with an <code>Engine<\/code>.<br>A method <code>startCar()<\/code> to start the car, which also starts the engine.<br>A method <code>showDetails()<\/code> to display the car&#8217;s engine type.<\/li>\n\n\n\n<li><strong>Key Points:<\/strong><br>The <code>Car<\/code> class fully owns the <code>Engine<\/code> object.<br>The <code>Engine<\/code> object is created when the <code>Car<\/code> object is initialized and destroyed when the <code>Car<\/code> object is destroyed.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>What is Aggregation?<\/strong><\/h3>\n\n\n\n<p>Aggregation represents a <strong>weaker relationship<\/strong> between two classes. It is used when an object (child) is associated with another object (parent), but the child object <strong>can exist independently<\/strong> of the parent. The lifecycle of the child object is not tied to the lifecycle of the parent.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Key Characteristics of Aggregation:<\/strong><\/h4>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Weak Dependency:<\/strong>\n<ul class=\"wp-block-list\">\n<li>The parent object holds a reference to the child object, but the child can exist without the parent.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Independent Lifecycle:<\/strong>\n<ul class=\"wp-block-list\">\n<li>The child object\u2019s lifecycle is independent of the parent. Destroying the parent does not affect the child.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Real-World Example:<\/strong>\n<ul class=\"wp-block-list\">\n<li>A house and its residents. The residents can exist independently of the house.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Example Code: Aggregation in C++<\/strong><\/h4>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>#include &lt;iostream&gt;<br>#include &lt;vector&gt;<br>#include &lt;string&gt;<br>using namespace std;<br>\/\/ Person class representing a resident<br>class Person {<br>private:<br>    string name;<br>public:<br>    \/\/ Constructor to initialize the person's name<br>    Person(const string&amp; name) : name(name) {}<br>    string getName() const {<br>        return name;<br>    }<br>};<br>\/\/ House class containing a list of residents (Aggregation)<br>class House {<br>private:<br>    vector&lt;Person&gt; residents; \/\/ A house \"has-a\" list of residents<br>public:<br>    \/\/ Method to add a resident to the house<br>    void addResident(const Person&amp; person) {<br>        residents.push_back(person);<br>    }<br>    \/\/ Method to display all residents<br>    void showResidents() const {<br>        cout &lt;&lt; \"House residents:\" &lt;&lt; endl;<br>        for (const auto&amp; person : residents) {<br>            cout &lt;&lt; person.getName() &lt;&lt; endl;<br>        }<br>    }<br>};<br>int main() {<br>    \/\/ Create Person objects<br>    Person p1(\"Alice\");<br>    Person p2(\"Bob\");<br>    \/\/ Create a House object<br>    House house;<br>    \/\/ Add residents to the house<br>    house.addResident(p1);<br>    house.addResident(p2);<br>    \/\/ Display residents of the house<br>    house.showResidents();<br>    return 0;<br>}<br><\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Explanation of Aggregation Code:<\/strong><\/h4>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong><code>Person<\/code> Class:<\/strong><br>Represents a person with a <code>name<\/code>. It has:<br>A constructor to initialize the name.<br>A method <code>getName()<\/code> to retrieve the person&#8217;s name.<\/li>\n\n\n\n<li><strong><code>House<\/code> Class:<\/strong><br>Represents a house containing multiple residents (a collection of <code>Person<\/code> objects). It has:<br>A method <code>addResident()<\/code> to add a <code>Person<\/code> object to the house.<br>A method <code>showResidents()<\/code> to display the names of all residents.<\/li>\n\n\n\n<li><strong>Key Points:<\/strong><br>The <code>House<\/code> class does not own <code>Person<\/code> objects. It merely stores references (in this case, values) to existing <code>Person<\/code> objects.<br><code>Person<\/code> objects (<code>p1<\/code>, <code>p2<\/code>) exist independently of the <code>House<\/code> object.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Benefits of Using Composition and Aggregation<\/strong><\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Flexibility:<\/strong><br>Both approaches provide flexibility in structuring relationships between classes, promoting modular design.<\/li>\n\n\n\n<li><strong>Reusability:<\/strong><br>Classes designed with Composition or Aggregation can be reused in different contexts without modification.<\/li>\n\n\n\n<li><strong>Encapsulation:<\/strong><br>Composition and Aggregation encourage encapsulating functionality in smaller classes, improving code readability.<\/li>\n\n\n\n<li><strong>Maintainability:<\/strong><br>Breaking down systems into smaller, related components makes them easier to maintain and extend.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Difference in Composition and Aggregation<\/strong>:<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th><strong>Aspect<\/strong><\/th><th><strong>Composition<\/strong><\/th><th><strong>Aggregation<\/strong><\/th><\/tr><\/thead><tbody><tr><td><strong>Ownership<\/strong><\/td><td>The parent object owns the child object.<\/td><td>The parent object holds a reference to the child object.<\/td><\/tr><tr><td><strong>Lifecycle Dependency<\/strong><\/td><td>The child object\u2019s lifecycle is tied to the parent.<\/td><td>The child object\u2019s lifecycle is independent of the parent.<\/td><\/tr><tr><td><strong>Strength of Relationship<\/strong><\/td><td>Strong<\/td><td>Weak<\/td><\/tr><tr><td><strong>Example<\/strong><\/td><td>A car &#8220;has-an&#8221; engine.<\/td><td>A house &#8220;has-a&#8221; resident.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Key Differences:<\/strong><\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Ownership:<\/strong>\n<ul class=\"wp-block-list\">\n<li>In <strong>Composition<\/strong>, the parent object owns the child object.<\/li>\n\n\n\n<li>In <strong>Aggregation<\/strong>, the parent object does not own the child object, and the child can exist independently.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Lifecycle Management:<\/strong>\n<ul class=\"wp-block-list\">\n<li>In <strong>Composition<\/strong>, when the parent object is destroyed, the child object is also destroyed automatically.<\/li>\n\n\n\n<li>In <strong>Aggregation<\/strong>, the child object\u2019s lifecycle is independent, and destroying the parent object does not affect the child object.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Relationship Strength:<\/strong>\n<ul class=\"wp-block-list\">\n<li><strong>Composition<\/strong> is a <strong>stronger<\/strong> relationship, indicating that the child is an integral part of the parent.<\/li>\n\n\n\n<li><strong>Aggregation<\/strong> is a <strong>weaker<\/strong> relationship, suggesting that the child can exist on its own without the parent.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Real-World Analogies:<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Composition<\/strong>: A <strong>heart<\/strong> is a part of the <strong>human body<\/strong>. Without the body, the heart cannot exist.<\/li>\n\n\n\n<li><strong>Aggregation<\/strong>: A <strong>book<\/strong> belongs to a <strong>library<\/strong>, but it can be removed from the library and still exist as an independent object.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Choosing Between Composition and Aggregation:<\/strong><\/h3>\n\n\n\n<p>The choice between Composition and Aggregation depends on the level of dependency between the objects. If the child object\u2019s lifecycle depends on the parent, then <strong>Composition<\/strong> is the right choice. If the child object can exist independently of the parent, then <strong>Aggregation<\/strong> is more appropriate.<\/p>\n\n\n\n<p>By understanding and correctly implementing Composition and Aggregation, developers can create more flexible, maintainable, and logically structured software systems. These concepts help in modeling real-world scenarios accurately and ensure better code organization and reuse.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Summary<\/strong><\/h3>\n\n\n\n<p>In object-oriented programming (OOP), <strong>Composition<\/strong> and <strong>Aggregation<\/strong> are two key concepts that describe how classes relate to each other. Both represent a &#8220;has-a&#8221; relationship, but they differ in the strength of the relationship and how objects are dependent on one another.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Composition<\/strong> represents a strong relationship where one object (the parent) completely owns and controls the lifecycle of another object (the child). The child object cannot exist without the parent object. For example, a <strong>Car<\/strong> &#8220;has-an&#8221; <strong>Engine<\/strong>, and the engine\u2019s existence is tightly bound to the car.<\/li>\n\n\n\n<li><strong>Aggregation<\/strong>, on the other hand, represents a weaker relationship. While the parent object holds a reference to the child object, the child object can exist independently of the parent. For example, a <strong>House<\/strong> &#8220;has-a&#8221; <strong>Resident<\/strong>, but the resident can live elsewhere, independent of the house\u2019s existence.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Key Takeaways<\/strong><\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Composition<\/strong> is used when objects are tightly coupled, and their lifecycles are interdependent.<\/li>\n\n\n\n<li><strong>Aggregation<\/strong> is used when objects are loosely coupled and can exist independently.<\/li>\n\n\n\n<li>Understanding the differences between Composition and Aggregation helps design better and more flexible class relationships, leading to cleaner and more maintainable code.<br><\/li>\n<\/ol>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In Object-Oriented Programming (OOP), Composition and Aggregation describe relationships between classes, specifically how objects are associated with one another. Both are forms of the &#8220;has-a&#8221; relationship, but they differ in strength and dependency. So in this article we will see the concept of Composition and Aggregation in C++ and also check the difference between Composition and Aggregation. What is Composition? Composition represents a strong relationship between two classes. It is used when an object (child) is a part of another&#8230;<\/p>\n<p class=\"read-more\"><a class=\"btn btn-default\" href=\"https:\/\/afzalbadshah.com\/index.php\/2025\/02\/26\/composition-and-aggregation-in-c\/\"> Read More<span class=\"screen-reader-text\">  Read More<\/span><\/a><\/p>\n","protected":false},"author":197,"featured_media":5200,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"enabled":false},"version":2}},"categories":[351,637],"tags":[],"class_list":["post-4910","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-courses","category-oop-with-c"],"aioseo_notices":[],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/12\/Understanding-Composition-and-Aggregation-in-C.png?fit=1920%2C1080&ssl=1","jetpack_sharing_enabled":true,"jetpack_likes_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/pf3emP-1hc","jetpack-related-posts":[],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/4910","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/users\/197"}],"replies":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/comments?post=4910"}],"version-history":[{"count":4,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/4910\/revisions"}],"predecessor-version":[{"id":5201,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/4910\/revisions\/5201"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/media\/5200"}],"wp:attachment":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/media?parent=4910"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/categories?post=4910"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/tags?post=4910"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}