YaoveiD
YaoveiD

Reputation: 11

Problems with copy constructor and vector

I met a problem with copy constructor and vector.

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

class B {
private:
    int val;
};

class A {
private:
    B b;
public:
    A() {}
    A(A& a) {}
};

int main(int argc, char const *argv[])
{
    A aa;
    A a2 = aa;//it works well
    //addA(va, aa);
    return 0;
}

But when I do something like this:

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

class B {
private:
    int val;
};

class A {
private:
    B b;
public:
    A() {}
    A(A& a) {}
};

void addA(std::vector<A>& va, A a) {
    va.push_back(a);
}

int main(int argc, char const *argv[])
{
    std::vector<A> va;
    A aa;
    A a2 = aa;
    addA(va, aa); // I got a compile error
    return 0;
}

there is a compiler error.

But if I change the args in class A's copy constructor to const A&, it works well.

Why is this so?

Upvotes: 1

Views: 85

Answers (1)

Caleth
Caleth

Reputation: 62636

The argument to std::vector<A>::push_back is const A &, so when the vector tries to copy that into the storage it allocated for the element, it requires a constructor that takes const A &. Because yours doesn't, it can't be used.

Upvotes: 1

Related Questions