Aggregation in C++ (HAS-A Relationship)

Aggregation in C++ is the process of one class defining another as any entity reference. It’s a different technique for reusing the class. It is a type of association that denotes the existence of a HAS-A relationship.

Example of Aggregation in C++:

Let’s look at an aggregate example where the Employee class has a reference to the Address class as a data member. It will be able to reuse the members of the Address class in this fashion.

#include <iostream>  
using namespace std;  
class Address {  
    public:  
   string addressLine, city, state;    
    Address(string addressLine, string city, string state)    
    {    
        this->addressLine = addressLine;    
        this->city = city;    
        this->state = state;    
    }    
};  
class Employee    
    {    
        private:  
        Address* address;  //Employee HAS-A Address   
        public:  
        int id;    
        string name;    
        Employee(int id, string name, Address* address)    
       {    
           this->id = id;    
           this->name = name;    
           this->address = address;    
       }    
     void display()    
       {    
           cout<<id <<" "<<name<< " "<<     
             address->addressLine<< " "<< address->city<< " "<<address->state<<endl;    
       }    
   };   
int main(void) {  
    Address a1= Address("C-146, Sec-15","Noida","UP");    
    Employee e1 = Employee(101,"Nakul",&a1);    
            e1.display();   
   return 0;  
}  

Output:

101 Nakul C-146, Sec-15 Noida UP

Join Our Community

Join our WhatsApp Group To know more about Programming Language tips, tricks and knowledge about and how to start learning any programming language.

Default image
Lingaraj Senapati
Hey There! I am Lingaraj Senapati, the Co-founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.
Articles: 217

Newsletter Updates

Enter your email address below to subscribe to our newsletter

Leave a Reply