Consider this example code:
#include <iostream>
class base {
public:
base() {
std::cout << "base constructed" << std::endl;
}
base(const base & source) {
std::cout << "base copy-constructed" << std::endl;
}
};
class derived : public base {
public:
derived() {
std::cout << "derived constructed" << std::endl;
}
derived(const derived &) = delete;
derived(const base & source) : base(source) {
std::cout << "derived copy-constructed from base" << std::endl;
}
};
int main() {
derived a;
base b(a);
derived c(a);
return 0;
}
Why is it that the call to base::base(const base &) is okay, but the call to derived::derived(const base &) is not? Both expect a base reference, and both are given a derived reference. It’s my understanding that derived ‘is a’ base.
Why does the compiler insist on using derived::derived(const derived &) when it has no problem using base::base(const base &) when supplied with a reference to an object of type derived?
Apparently ‘deleting’ one of the default things doesn’t have the effect of actually deleting it exactly. Some grisly ghoulish vestige of the once proud default copy constructor is left lying around to pop up and tell you in a sepulchral voice “I’m deeeeaaaaaad!“.
This is not an altogether surprising fact to me, though I was unaware of it in specific before you asked this question. I could not quote you the relevant section of the standard (and I’m certain that the relevant section makes no mention of ghouls, though it should). And I’m also fairly certain there is some reason why this is the case that turns out to be perfectly sensible once you follow some incredibly convoluted story about some horrible case that would work in a terrible way if it weren’t.
And, unfortunately for you, if there’s something lying around that’s a better match than a conversion to a base class, it’s what will be used. For example, in this code:
will result in this output:
Which is exactly as you’d expect. The compiler does not treat the situation as ambiguous. And if you made
void foo(const B &)into a private or protected member, then the compiler would still match it in preference to the other, and tell you you tried to access something that had an access specifier that said you couldn’t.Think of setting something to be ‘deleted’ as simply declaring it with a special access specifier that’s even more restricted than private.