Container Class In C++ | Container Class Explained With Real Life Examples

 Container Class In C++





What is a container class?

A container class is that class in which you can create an object of any other class and use it like you use it in your main() function.

To understand containers more quickly suppose you have a house and a hotel class. So a house class may have data members like a number of rooms, bedroom_size, bedroom_color. And a hotel class may have the same data member as a house but it may have some more functionality like checkin_time, checkout_time, etc.
So in this case you can create a hotel as a class container so you can use house data members inside that also.


Here is an example of how you can create a container class in C++ - 



#include <iostream>
using namespace std;

class house
{
    public:
    int no_of_rooms = 5;
    int bedroom_size = 1200;//1200 sq.ft.
    char bedroom_color[100] = "red"; //red,green,blue
};

class hotel
{
    public:
    //As i defined object of house class then 
    //now hotel class becomes container class
    //which containes house class
    house h1;
    void details()
    {
        cout<<"No Of Rooms Is: "<<h1.no_of_rooms<<endl;
        cout<<"Color Of Bedroom Is: "<<h1.bedroom_color<<endl;
    }
};

int main()
{

    hotel H1;
    H1.details();
    return 0;
}

Output - 

No Of Rooms Is: 5
Color Of Bedroom Is: red

So Here you can see a hotel class's object can access the data member or even methods of house class.

Comments

Popular posts from this blog

Array Of Objects In C++ | Array Of Objects Explained With Real Life Example

Pointers In C++ | Pointer Explained With Real Life Examples | Pointers In OOPs C++

Destructor In C++ | Destructor Explained With Real Life Examples