For User Defined classes if Copy Constructor and Assignment Operator are public then only one can insert it’s object in std::vector.

This is because of two reasons,

  • All STL contains always stores the copy of inserted objects not the actual one. So, whenever we insert any element or object in    container then it’s copy constructor is called to create a copy and then this copy is inserted in the container.
  • While insertion in std::vector it might be possible that storage relocation takes place internally due to insufficient space. In such cases assignment operator will be called on objects inside the container to copy them from one location to another.

Check out below example,

A part from this, if you are initializing the std::vector with default size by passing size as parameter i.e.

In such scenario 2 objects of NewSample will be created using default constructor. But if default constructor is not available then it will give compile error.

Check out the following example,

Here we have not Defined Default constructor but defined copy constructor, therefore default constructor will get hidden for this class. Hence, it will give compile error when vector will try to create two objects using default constructor.

This problem will not happen if we use reserver() member function to initialize the size of vector because reserver() just increases the capacity of vector not the size.

Click Here to Subscribe for more Articles / Tutorials like this.