TITLE: appropriate uses of static_cast (Newsgroups: comp.lang.c++.moderated, 31 May 99) BRUGALIERES: sebastien brugalieres > I would like to understand when the static_cast operator is usefull NARAN: Siemel Naran One may use static_cast in recursive-like derivation. The static_cast is for casting from the base class to the derived class. Normally this cast is dangerous, but below, this is not so. template class Impl { public: void action() const { const T& me=static_cast(*this); ... }; }; class Base { virtual ~Base(); ... }; class Derived : public Base, private Impl { ... }; Here is another case where the static_cast is usually safe. class Base { protected: virtual bool equal(const Base&) const = 0; public: virtual ~Base(); ... friend bool operator==(const Base& lhs, const Base& rhs) { if (typeid(lhs)!=typeid(rhs)) return false; return lhs.equal(rhs); }; class Derived : public Base { protected: bool equal(const Base& that) const { const Derived& me=*this; const Derived& you=static_cast(that); ... }; public: ... }; One needs static_cast to go from void* to T*. Eg: int * array=static_cast(std::malloc(3*sizeof(int))); But it rare that one will use this cast in high level code. Finally, the error messages when you try to static_cast between two unrelated types is useful. Eg, signed * s; unsigned * u=static_cast(s); // error unsigned * u=(unsigned*)s; // ok, uses reinterpret_cast --------------------------------------------------------------------- (Newsgroups: comp.lang.c++.moderated, 1 Jun 99) PHLIP: Phlip > 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.