Container to store Different Object Type in C++

In this tutorial, we will learn about the Container to store Different Object Type in C++.

We will learn about the container to store Different Object Type in a very cool and easy way. If you don’t know anything about this. It’s OK, you are in the right place, let’s go through it.

Firstly, we want a container that can able to store all different types of data like int, float, char, double, etc. On the other hand, The standard container like vector and list that comes with C++ is already generic. The main problem with them is they can be the container for any data type but they must be of the same type. In other words, they cannot contain multiple data types.

Therefore, to deal with this kind of problem you can use structure or classes or std::pair for storing different object types in C++.

Let’s take a close look at each of them.

  • Firstly, Class is a user-defined data type. It consists of data members ( variables of different datatype) and member functions ( function present inside the class). Data members and member functions of a class can be accessed by creating an object of that class only.
    class MyClass 
    public: int myNum; 
            string myString;


  • Secondly, The structure is a collection of variables having different data types. It is a similar concept to a class but provide less feature than the class, and holds a collection of data of different data types. Here, in the given code below struct contains different types of data, name is character type data as age is of integer type, whereas salary is of float type.
    struct Person 
    char name[50]; 
    int age; 
    float salary;
  •  Lastly, std::pair class couples together with a pair of values having different types as T1 or T2.
        class T1, 
        class T2 
    struct pair;


I think these are the option to store Different Object Type in a container.

I hope this will help you!

Thank you…

Also, read:

Leave a Reply

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