ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Object Oriented Programming
    CC-211
    Progress0 / 24 topics
    Topics
    1. Object-Oriented Design: History and Advantages2. Object-Oriented Programming: Terminology and Features3. Classes and Objects4. Data Encapsulation5. Constructors and Destructors6. Access Modifiers7. Const vs Non-Const Functions8. Static Data Members and Functions9. Function Overloading10. Operator Overloading11. Identification of Classes and Their Relationships12. Composition13. Aggregation14. Inheritance15. Multiple Inheritances16. Polymorphism17. Abstract Classes18. Interfaces19. Generic Programming Concepts20. Function Templates21. Class Templates22. Standard Template Library23. Object Streams: Data and Object Serialization24. Exception Handling
    CC-211›Composition
    Object Oriented ProgrammingTopic 12 of 24

    Composition

    6 minread
    1,017words
    Intermediatelevel

    Composition in Object-Oriented Programming (OOP)

    Composition is a design principle in object-oriented programming (O O P) that represents a "has-a" relationship between two classes. It is a special type of aggregation, where one class owns or contains objects of another class, and the contained objects typically cannot exist without the containing class. In other words, when the parent class (or the container) is destroyed, the contained objects are also destroyed.

    Composition is used when the contained object lifecycle is dependent on the lifecycle of the container object.

    Composition vs. Aggregation

    • Aggregation is a looser relationship, where the part can exist independently of the whole. For example, a Library can contain Books, but the Books could exist independently of the Library.

    • Composition, on the other hand, represents a stronger relationship, where the part cannot exist without the whole. For example, a Car has an Engine, and the Engine cannot exist independently of the Car. If the Car is destroyed, the Engine will also be destroyed.

    Key Characteristics of Composition

    • "Has-a" relationship: The class that owns the other is said to "have" the other object.
    • Lifetime dependency: The lifetime of the contained object is bound to the lifetime of the container object.
    • Stronger ownership: The owner (container) is responsible for creating and destroying the contained objects.
    • Containment: The objects within a composed class are directly tied to that class.

    When to Use Composition

    • When one object cannot meaningfully exist without the other.
    • When you want to model real-world entities where a part is integral to the whole, and it wouldn't make sense to have that part in isolation.
    • When you want to express that the child objects should be destroyed when the parent object is destroyed.

    Example of Composition in C++

    Let's take an example of a Car and an Engine to demonstrate composition.

    In this case, a Car has an Engine, and an Engine cannot exist without the Car. If the Car object is destroyed, its Engine should also be destroyed.

    Example Code:

    #include <iostream>
    #include <string>
    using namespace std;
    
    class Engine {
    public:
        string engineType;
        
        // Constructor
        Engine(const string& type) : engineType(type) {
            cout << "Engine created: " << engineType << endl;
        }
        
        // Destructor
        ~Engine() {
            cout << "Engine destroyed: " << engineType << endl;
        }
    };
    
    class Car {
    private:
        Engine engine;  // Composition: Car has an Engine
    
    public:
        // Constructor that initializes the Engine
        Car(const string& engineType) : engine(engineType) {
            cout << "Car created!" << endl;
        }
        
        // Destructor
        ~Car() {
            cout << "Car destroyed!" << endl;
        }
        
        // Function to display car information
        void display() {
            cout << "This car has an " << engine.engineType << " engine." << endl;
        }
    };
    
    int main() {
        // Creating a Car object will also create an Engine object
        Car car("V8");
    
        car.display();
    
        // When the car object goes out of scope, both car and engine are destroyed.
        return 0;
    }
    

    Explanation:

    1. Composition Relationship: The Car class has an Engine as a member variable. This is the composition relationship, meaning that the Car is responsible for the Engine's creation and destruction.
    2. Constructor and Destructor:
      • When a Car object is created, it initializes the Engine object via the Car constructor. The Engine's constructor prints a message indicating the engine type.
      • When the Car object goes out of scope, its destructor is called, which implicitly calls the Engine's destructor (since the Engine is a part of the Car). This leads to the destruction of the Engine object.
    3. Automatic Cleanup: When the Car is destroyed at the end of the program (i.e., when it goes out of scope), the Engine is also destroyed automatically.

    Output:

    Engine created: V8
    Car created!
    This car has an V8 engine.
    Car destroyed!
    Engine destroyed: V8
    

    Advantages of Composition

    1. Clearer Ownership: Composition clearly indicates that one object owns or contains another object. This helps with managing the relationships and the lifetime of objects.
    2. Flexibility: With composition, you can easily create objects with a variety of contained objects (e.g., a Car object could have a V6 engine or a V8 engine).
    3. Encapsulation: The contained object is typically hidden from external classes. This promotes better encapsulation since external classes can only interact with the containing class, not directly with the contained objects.
    4. Destruction Management: Since the owner is responsible for managing the lifecycle of the contained objects, memory management becomes more straightforward. The contained object is destroyed when the containing object is destroyed.

    Disadvantages of Composition

    1. Increased Complexity: Sometimes, composition can lead to more complex relationships, especially when many objects are composed together. This can make the system more difficult to maintain.
    2. Tight Coupling: The classes become tightly coupled because one class depends on another's existence. Changes to the contained class can affect the containing class.
    3. Memory Usage: In cases where an object contains many other objects, the memory usage can increase, especially when dealing with large objects.

    Composition vs. Inheritance

    While both composition and inheritance are used to establish relationships between classes, they differ in their intent and use cases:

    • Inheritance models an "is-a" relationship (e.g., a Dog is an Animal), whereas composition models a "has-a" relationship (e.g., a Car has an Engine).
    • Inheritance should be used when there is a clear hierarchy between objects, and composition is preferred when objects are composed of other objects without necessarily having a direct hierarchical relationship.

    Summary

    • Composition is a strong "has-a" relationship where one class contains an object of another class.
    • The lifetime of the contained object is typically dependent on the container object's lifetime.
    • It is a more appropriate choice than aggregation when the contained object should not exist independently of the containing class.
    • Composition enhances modularity, reusability, and clarity of object ownership in a system.

    In object-oriented design, knowing when to use composition is crucial for building flexible, maintainable, and effective systems.

    Previous topic 11
    Identification of Classes and Their Relationships
    Next topic 13
    Aggregation

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time6 min
      Word count1,017
      Code examples0
      DifficultyIntermediate