Aggregation in C++

Aggregation in C++ (commonly called as a has-a relationship), is a process in which one class defines a second class as an entity reference. It is a method of reusability of classes. In the simplest possible terms, it is when a class has an object of the other class.

Aggregation is a concept introduced within the object-oriented programming section of the language; It is a useful and practical tool that can be used while working with real-life models and projects.

Usage and Concept of Aggregation in C++

The concept of aggregation is based on real-world scenarios, which include many different classes sharing a common attribute. For example, consider the class ‘address,’ along with a group of classes of professions, like ‘student,’ ‘scientist,’ ‘programmer’ etc. Each of the objects of the classes would have an attribute for their address. Hence, each class would contain an object of the ‘address’ class. This, given below, is the basic concept’s usage.

class address{
        string city, state, locality;
        address( city_c, state_c, locality_c)
            {  city =  city_c; state = state_c; locality = locality_c; }

class student{
        int id; 
        string name;
        student( int i, string nm, address*ad)
        { id = i; name = nm; adrs = ad; }
        void display()
        { cout<<id<< "  "<<name<< "  "<<adrs->locality<< "  "<<adrs->city<< "  "<<adrs->state;}
void main()
    address a1= address("C-146, Sec-15","Noida","UP");    
    student s1 = student(101,"Nakul",&a1);    

The output is given by :

101 Nakul C-146, Sec-15 Noida UP

This example shows you how it is possible to relate two classes using the aggregation method.  Characteristics of the embedded class can also be accessed using pointers, as is shown in the example.

This article shows you how to use classes and aggregation to be applied in real-world situations, having a practical effect upon the project. Hopefully, you have learned and understood the concept of aggregation and will be able to implement it in your projects.


You may also like:

How to detect a loop in a linked list in C++

Destructors in Object Oriented Programming ( OOPS) – C++

One response to “Aggregation in C++”

  1. Abdul waheed says:

    very useful sir it’s really clear my concept

Leave a Reply

Your email address will not be published. Required fields are marked *