Skip to content

Instantly share code, notes, and snippets.

@dgodfrey206
Last active October 25, 2025 21:39
Show Gist options
  • Save dgodfrey206/3a4d4715b72c6f3d2ec5 to your computer and use it in GitHub Desktop.
Save dgodfrey206/3a4d4715b72c6f3d2ec5 to your computer and use it in GitHub Desktop.
Explicit type conversion (cast notation)
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
}
@dgodfrey206
Copy link
Author

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_cast can be used to convert a base class to a derived class (downcast), but not if the base class is virtual.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment