dimanche 8 mars 2015

Copy-constructor from superclass

I have the following code:



#include <iostream>
#include <utility>

class A {
public:
A() { }
A(const A&, int i) { std::cout << "A copy" << std::endl; }
A(A&&, int i) { std::cout << "A move" << std::endl; }
A(const A&) = delete;
A(A&&) = delete;
};

class B : public A {
public:
B(int i) { std::cout << "B construct" << std::endl; }
B(const A& a) : A(a, 1) { std::cout << "B copy" << std::endl; }
B(A&& a) : A(std::move(a), 1) { std::cout << "B move" << std::endl; }
};


B make_b() {
return B(1);
}

int main() {
B b = make_b();
}


The compiler error reports the error that B cannot be copy-constructed (for return from make_b), because it has no copy-constructor, because A's copy-constructor is deleted.





  • Does B(const A&) not qualify as copy-constructor, and what is the rule that applies here?

  • Does the copy and move constructor always have to take one argument of the same type (and not a superclass)?

  • Can it have additional parameters with default values?

  • Can it be templated so that it can resolve to a valid copy constructor?

  • To allow implicit copy and move construction, is it necessary to explicitly add copy and move-constructors B(const B&) and B(B&&)?


Aucun commentaire:

Enregistrer un commentaire