Importance of Constructors while using User Defined Objects with std::vector

In this article we will see the importance of constructor while using user defined objects with std::vector.

In user defined classes in case both copy constructor and argument operator are public, only one of them can insert their object into std::vector. This happens due to the following reasons

  1. As the STl always stores the copy of the actual object and not the actual object. For this it uses a copy constructor that stores these values in the container.
  2. During inserting objects into the std::vector there might be cases where the space is not sufficient and storage relocation happens. In these cases the assignment operator is called and the objects inside the container are copied from one memory location to another.
#include <bits/stdc++.h>
class Example
    // The copy sconstructor should be made public if we are going to
    //  insert objects into the vector container
    Example(const Example &obj)
        std::cout << "Example Class Copy_Constructor" << std::endl;

        std::cout << "Example Class Default_Constructor" << std::endl;
    Example &operator=(const Example &obj)
        std::cout << "Example Class Assignment_Operator" << std::endl;
int main()
    std::vector<Example> vec;
    Example obj;
    return 0;

The above program will return error as we have made the copy constructor private while pushing values into the std::vector.

Also if here we are initializing the constructor by passing size as an argument, it will invoke the default constructor. In case it is not accessible it will throw an error.

To avoid this we have to make our copy constructor public while also keeping the default constructor by using the reserve( ) function to increase the vector capacity rather than increasing its size.