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.

Python Recommendations:

C++ & C++11 Recommendations:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Subscribe with us to join 1500+ Python & C++ developers, to get more Tips &  Tutorials like this.