C++: vector of arrays

In C++ arrays cannot be stored in vectors. This restriction is due to the fact that arrays cannot be copy constructed or assigned. For example, this won’t compile in c++

To work around this limitation, c++11 has introduced a new container called std::array. std::array is just a template class that encapsulates a static array. It cannot be resized and its size should be know at compile time. Here is a small example on how to create a vector of arrays.

C++: Copy constructor and assignment constructor

Usually C++ beginners confuse between copy constructor and assignment operator. Though they do almost the same thing, they have their own purposes and understanding it is very important. While copy constructor is a constructor, assignment operator is an operator. This means that copy constructor is used to create new objects from existing objects, while assignment operator is used to assign content of an existing object to another existing object.

We will use the class Assignable defined in the code snippet below for illustration purposes throughout the article.

Copy constructor

Copy constructor is a constructor used by the compiler to create new instances of a class from existing instances.

Copy constructor is usually called(not necessarily because c++ allows compilers to optimize the copy away when it is posible)
1) When an instance of a class is passed as value to a function

2) When a new instance is created by passing a reference to an existing instance

3) When an instance of a class is returned by value from a function

Note: Some compilers are smart enough to identify this situation and avoid copy construction and destruction of temporary object. This optimization is called Return Value Optimization.

Assignment operator

Assignment operator is an operator that is invoked when an instance of a class is assigned to another.

This is the entire code to simulate all these behaviors of copy constructor and assingnment operator.