1
#include <iostream>
#include <vector>
using namespace std;

class dog {
public:
    dog() {}
    dog(dog & d) {
    }
};

int main() {
    vector<dog> vec;
    dog d;
    vec.push_back(d);
    return 0;
}

I can not insert dog into the vector. The problem lies in the copy constructor. If I add const in the copy constructor, the code compiles. I just wonder why I have to add const in the copy constructor.

The error message is:

error: binding ‘const dog’ to reference of type ‘dog&’ discards qualifiers

M.M
  • 138,810
  • 21
  • 208
  • 365
Casualet
  • 295
  • 3
  • 12

1 Answers1

1

std::vector::push_back takes const T& as its parameter (for lvalue), that means when it's called the argument will be bound to the parameter with type const dog&, which will be used to construct dog inside the vector later (in push_back).

For such copy construction to be achieved, the appropriate copy constructor (i.e. dog::dog(const dog&) is needed; but the signature of the copy constructor is dog::dog(dog&), which can't take a const dog&, thus the compiler failed to find the appropriate copy constructor to perform the operation.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405