Last active
October 25, 2025 21:39
-
-
Save dgodfrey206/3a4d4715b72c6f3d2ec5 to your computer and use it in GitHub Desktop.
Explicit type conversion (cast notation)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| struct Parent { virtual ~Parent() = default; }; | |
| struct Child : private virtual Parent { }; | |
| int main() | |
| { | |
| Child c0; | |
| Parent& p0 = static_cast<Parent&>(c0); // FAILS, Parent is inaccessible | |
| Parent& p1 = (Parent&)(c0); // OK ( [expr.cast]/p4.6 ), chooses static_cast | |
| Child& c1 = (Child&)(p1) // FAILS, chooses static_cast, but that fails | |
| // because Parent is a virtual base ( [expr.static.cast]/p2 ) | |
| // (NOT because it is inaccessible) | |
| Child& c2 = dynamic_cast<Child&>(p1); // FAILS, dynamic_cast can be used with a virtual base, | |
| // but Parent is still private and so the downcast | |
| // is not allowed. | |
| // Also, cast notation doesn't consider dynamic_cast | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you're casting to a reference through cast notation and it chooses
static_cast, the cast can be successful even if the target type is an inaccessible base.static_castcan be used to convert a base class to a derived class (downcast), but not if the base class isvirtual.