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 *) ...
Get C++ Primer Plus now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.