Misusing RTTI
RTTI has many vocal critics within the C++ community. They view RTTI as unnecessary, a potential source of program inefficiency, and a possible contributor to bad programming practices. Without delving into the debate over RTTI, let’s look at the sort of programming that you should avoid.
Consider the core of Listing 15.17:
Grand * pg;Superb * ps;for (int i = 0; i < 5; i++){ pg = GetOne(); pg->Speak(); if( ps = dynamic_cast<Superb *>(pg)) ps->Say();}
By using typeid and ignoring dynamic_cast and virtual functions, you can rewrite this code as follows:
Grand * pg;Superb * ps;Magnificent * pm;for (int i = 0; i < 5; i++){ pg = GetOne(); if (typeid(Magnificent) == typeid(*pg)) { pm = (Magnificent *) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access