TITLE: examples of using static cast (Newsgroups: comp.lang.c++.moderated, 4 Jun 99) PHILIP: > > > Now here's one reason to use 'static_cast<>' to down-cast: Profiling > > > your app revealed that virtual RTTI was too expensive for a > > > time-critical section of code. BECKER: Pete Becker > > Plus one other condition: you know that the conversion will always be > > valid. If you don't, then you must have the checking that dynamic_cast > > does. PHILIP: > Well, that's the thing now. One example of "time critical" code is that > inside an inner loop. > > But if the conversion is "always valid", then it might also be "always > the same". So move it out of the loop, take the (negligible) performance > hit, and use 'dynamic_cast<>'. > > Now if it's "always valid", but _not_ "always the same", you can still > move it out of the loop; just validate all the casts outside the loop > with 'dynamic_cast<>', and use 'static_cast<>' inside the loop. BECKER: Pete Becker There's a much simpler case: you've written a container that holds pointers to a base type, and you have used that container inside a wrapper that only accepts pointers to objects of a derived type. In that wrapper, you can access base pointers from the container with assurance that they will always in fact point to objects of the derived type. class Base { }; class Derived : public Base { }; class Wrapper { public: void insert(Derived *dp) { data[n++] = dp; } Derived *get(int i) { return static_cast(data[i]); } private: Base *data[20]; }; The static_cast is always valid, because the only objects that elements of data can point to are objects of type Derived. Having virtual functions in Base and Derived doesn't affect this.