Const and not const in copy constructor?

When I wrote my copy constructor that: (HocSinh is a class)

HocSinh::HocSinh(HocSinh &a)
{
    hoTen = a.hoTen;
    diemVan = a.diemVan;
    diemToan = a.diemToan;
}

      

then

HocSinh hocSinh("abc", 1, 2);
vector <HocSinh> dsHSCanTim;
dsHSCanTim.push_back(hocSinh);

      

I got the error: "No copy constructor or copy constructor is declared" explicit. "But when I wrote:

HocSinh::HocSinh(const HocSinh &a)
{
    hoTen = a.hoTen;
    diemVan = a.diemVan;
    diemToan = a.diemToan;
}

      

There were no mistakes. Can someone explain this to me please. Thank you all and sorry if my english is that bad.

+3


source to share


1 answer


Because it std::vector::push_back

is defined as

void push_back (const value_type& val);
void push_back (value_type&& val);

      



For an lvalue like this hocSinh

, the template std::vector::push_back

will use the former. Internally, the std::vector::push_back

copy constructor is used to construct an object in the allocated memory segment std::vector

. The implementation must use const value_type& val

this copy as its source, so a const

signed copy constructor is required to create it val

.

+4


source







All Articles