Skip to content

Instantly share code, notes, and snippets.

@dgodfrey206
Last active August 29, 2015 14:19
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(); };
struct Child : private virtual Parent { };
int main()
{
Child aa;
Parent& pp = (Parent&)(aa); // OK ( [expr.cast]/p4.6 ), chooses static_cast
Child& aa = (Child&)(pp) // FAILS, chooses static_cast, but that would fail
// because Parent is a virtual base ( [expr.static.cast]/p2 )
// (NOT because it is inaccessible)
Child& aa = dynamic_cast<Child&>(pp); // OK, dynamic_cast can be used with a virtual base,
// but 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