Does casting a pointer to an instance of a dervived class to the instances base class have any run-time overhead in C++, or is it resolved at compile-time?
If it does have any, what exactly has to be computed in the casting operation?
Example:
class Foo;
class Bar : public Foo;
Bar* y = new Bar;
Foo* x = (Foo*) y;
(I know I should use C++-style casts and that the answer is probably the same for them)
Yes, though it's negligible.
In this case, a C-Style cast is interpreted as a static_cast
, which may incur a pointer adjustment.
struct Base {};
struct Derived: Base { virtual ~Derived(); } // note: introduced a virtual method
int main()
{
Derived derived;
Base* b = &derived;
Derived* d = (Derived*) b;
void* pb = b;
void* pd = d;
printf("%p %p", pb, pd);
return 0;
}
This overhead happens whenever the base subobject is not aligned at the same address that the derived object, which happens when:
Of course, pointer adjustment is usually counted as negligible, and the compiler shall be smart enough to eliminate it if it's unnecessary anyway (an adjustment of 0).
Note: this is implementation dependent, not mandated by the standard
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