5

How does static_cast work? If you are doing something like...

If D inherits from B via some unspecified hierarchy (not necessarily directly), and you do:

B* b = new D(); D* d = static_cast<D*>(b); 

what is happening? Is it simply calculating an offset at compile time and applying that offset to the pointer? Or is there something happening at runtime in order to do the cast?

3
  • 4
    static_cast is always resolved using compile-time type info. (This may involve a runtime action). If it's not an appropriate cast you either get a compile error or undefined behaviour. In your snippet it is OK because b is a D; however if b were new B() then the cast compiles but causes undefined behaviour if run. Commented Dec 9, 2014 at 11:57
  • 3
    Yes, it's just calculating an offset at compile time and adding it. And unless there is multiple and/or virtual inheritance going on (or you have an extremely strange compiler) that offset will be 0 anyway, so no extra code will actually be emitted. Commented Dec 9, 2014 at 12:10
  • See Effective C++ Item 27 Minimize Casting. Commented Jul 25, 2018 at 13:20

1 Answer 1

5

what is happening?

The compiler assumes that you know what you're doing, so that the pointer really does point to a D object, and changes the pointer type accordingly, adjusting the value if necessary to point to the complete D object rather than the B sub-object.

If you get it wrong, and use a D* pointer that doesn't really point to a D object, then you'll get undefined behaviour; so be careful.

Is it simply calculating an offset at compile time and applying that offset to the pointer?

Yes.

Or is there something happening at runtime in order to do the cast?

No; "static" implies that it uses only compile-time information. The only runtime activity is adding the fixed offset if necessary.

Use dynamic_cast if you want a runtime check that the conversion is valid (as long as the types are polymorphic). It will give a null pointer (or throw a bad_cast exception if you're casting a reference rather than a pointer) if there isn't really a D object there.

Sign up to request clarification or add additional context in comments.

2 Comments

To have a complete answer here, can you complete your answer with explaining the difference of these two with simply writing D* d = ((D*)b);.
@Emadpres: A C-style cast will do exactly the same thing as static_cast in this case; the difference is that it can fall back to more dubious conversions in cases where static_cast would fail. But the question was specifically about static_cast, so that's not particularly relevant.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.