In this code assigning to b1 works, but it won't allow assigning to b2 (with or without the static cast). I was actually trying to solve the opposite problem, public inheritance but not implicitly converting to the base. However the cast operator never seems to be used. Why is this?
struct B {};
struct D1 : private B {
operator B&() {return *this;}
B& getB() {return *this;}
};
struct D2 : public B {
explicit operator B&() {return *this;}
};
struct D3 : public B {
operator B&() = delete;
};
void funB(B& b){}
int main () {
D1 d1;
funB(d1.getB()); // works
// funB(d1); // fails to compile with 'inaccessible base class
D2 d2;
funB(d2); // works
D3 d3;
funB(d3); // works
return 0;
}
A cast is a special operator that forces one data type to be converted into another. As an operator, a cast is unary and has the same precedence as any other unary operator. The most general cast supported by most of the C++ compilers is as follows − (type) expression.
This chapter discusses the new cast operators in the C++ standard: const_cast , reinterpret_cast , static_cast and dynamic_cast . A cast converts an object or value from one type to another.
From [class.conv.fct]:
A conversion function is never used to convert a (possibly cv-qualified) object to the (possibly cv-qualified) same object type (or a reference to it), to a (possibly cv-qualified) base class of that type (or a reference to it), or to (possibly cv-qualified) void.
So in your first example:
struct D1 : private B {
operator B&() {return *this;}
B& getB() {return *this;}
};
operator B&
will never be used because it converts to a base class. It doesn't matter that it's a private base class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With