A vector
often needs to move elements around. Every time a vector needs to grow when you call push_back()
it reallocates memory to keep itself contiguous, and copies all the existing elements into the new space. Also if you call insert()
or remove()
elements must
be shifted. For vector
to be able to do all that the elements must be copy-assignable, which means that the type you store in the vector must have the assignment operator defined.
Generally, if you define a class, the compiler will generate the assignment operator for that class for you. However, there are cases when the compiler is unable to do that. One of these cases is when the class has constant members (note that pointers-to-const are ok).
So, in your case, the problem is the const string name
. It prevents the compiler from generating operator=()
, which in turn prevents vector
from compiling, even though you do not actually use assignment on its elements yourself.
One solution is to make name
non-const. The other is to write your own Student::operator=()
, in some way that makes sense. The third way is, as you have pointed out, to use a vector of pointers rather than a vector of objects. But then you have to handle their allocation and de-allocation.
P.S. The other case when the compiler cannot generate operator=
is when your class has members that are references.