Professional Documents
Culture Documents
×
login | about | faq
• Questions
• Tags
• Users
• Badges
• Unanswered
• Ask Question
// A has a virtual
destructor (i.e. is
polymorphic)
// B has a virtual
destructor (i.e. is
polymorphic)
// B does (or does
not ... pick your
poison) inherits
from A
void
doSomething(A *
{
//
t ype id ( ) : : name( )
re tu rns the
"name" o f the
std::cout <<
typeid(*a).name()
/ / the
dynamic_cas t o f a
po in te r t o
another will
return NULL is
// the
conversion is not
possible
if(B * b =
dynamic_cast<B
*>(a))
std::cout
std::endl ;
else
std::cout
<< std::endl ;
30% accept
rate
You could start by
posting your 1.5
examples. – Ben Collins
Oct 26 '08 at 19:00
Martin York
21k●1●18●6
4
link|flag answered
Oct 26 '08 at
19:40
fizzer
3,172●4●22
I agree. This again what I called
above the "contract" programming.
+1 – paercebal Oct 26 '08 at 20:17
class base
// dynamic on the
};
{...}
if (B1
*b1=dynamic_cast<B1*>(b))
doFoo(b1);
else if (B2
*b2=dynamic_cast<B2*>(b))
doFoo(b2);
};
1800
INFORMATION
24.1k●2●17●55
SimModel*
SimDatabase::FindModel<type*>(char*
name="")
{
foreach(SimModel* mo in
ModelList)
name)
if(dynamic_cast<type*>mo !=
NULL)
return
dynamic_cast<type*>mo;
return NULL;
public:
void RunModel()=0;
};
An example interface might be "EngineModel":
SimModel
public:
float RPM()=0;
float FuelFlow()=0;
void SetThrottle(float
setting)=0;
};
EngineModelInterface
public:
float RPM()
return rpm;
float FuelFlow()
{
return throttleSetting *
10.0;
void SetThrottle(float
setting)
throttleSetting =
setting
if(throttleSetting >
0.5)
rpm += 1;
else
rpm -= 1;
private:
EngineModelInterface
public:
float RPM()
return rand();
float FuelFlow()
return rand;
void SetThrottle(float
setting)
}
};
EngineModelInterface * eng =
simDB.FindModel<EngineModelInterface
*>();
>FuelFlow();
link|flag answered
Oct 26 '08 at
19:50
keysersoze
1,158●2●10
Effectively, I tried, too, the decoupling of interfaces
and implementations, and code using defined
interfaces worked quite well with implementation
types coded time after, without needing
recompilation... +1 – paercebal Oct 26 '08 at 20:05
link|flag answered
Oct 27 '08 at
2:22
Nick
3,029●2●13
You're right: This is an awful switch/RTTI
combination, but then, you are using XML, and this
is a good solution to strong-type again what was a
string XML <element /> into a full fledged object. +1.
– paercebal Oct 27 '08 at 10:32
Sometimes s ta t i c _casand
t C-style
2 casts just aren't enough and you
need dynamic_cas t, an example
of this is when you have the
dreaded diamond shaped hierarchy
(image from Wikipedia).
struct top {
};
int i;
left() : i(42)
{}
};
std::string
name;
right() :
name("plonk") { }
};
right {
};
bottom b;
left* p = &b;
//right* r =
static_cast<right*>(p);
// Compilation error!
//right* r = (right*)p;
// Gives
right* r =
dynamic_cast<right*>(p);
// OK
link|flag answered
Oct 27 '08 at
14:51
Motti
5,816●9●36
Example:
D* obj =
dynamic_cast<D*>(base);
if (obj) {
for(unsigned i=0;
i<1000; ++i)
f(obj-
>D::key(i));
} else {
for(unsigned i=0;
i<1000; ++i)
f(base->key(i);
itsmatt
8,297●12●30
link|flag answered
Oct 27 '08
at 7:47
Johann
Gerell
1,482●1●9
Your Answer
•
•
•
•
community wiki
OpenID Login o
Name Email never shown Home Page
Get an OpenID r
Not the answer you're looking for? Browse other questions tagged
c++ rtti design polls or ask your own question.
Hello World!
Stack Overflow is a collaboratively edited question and answer site for programmers – regardless
of platform or language. It's 100% free, no registration required.
about » faq »
tagged
c++ × 14361
design × 2023
polls × 585
rtti × 36
asked
11 months ago
viewed
2,103 times
latest activity
11 months ago
Wanted: IT Technologist at Space Telescope Science Institute (Baltimore, MD 21218). See this
and other great job listings at jobs.stackoverflow.com.
Related
To RTTI or not RTTI…
On how many multiple projects do you work?
What field of software engineering do you work in?
Poll: Does your CTO actually Code?
Mixing RTTI flags in C++
How expensive is RTTI?
Is it allowed to link rtti enabled DLL within rtti disabled application?
How do I access Delphi Array Properties using RTTI
How can I assign an interface variable to a variable of type Rtti.TValue
Qt RTTI trouble
How to set event handlers via new RTTI? [D2010]
What’s a good way to serialize Delphi object tree to XML--using RTTI and not custom code?
How to call GetEnumerator on arbitrary type?
Delphi call method based on RTTI information
What is the simplest RTTI implementation for C++?
C++ RTTI Inheritance causes class size to increase
Delphi OTA and RTTI bug
Extract C++ template parameters
How to check if a Delphi class is declared abstract?
question feed
about | faq | blog | podcast | privacy policy | advertising info | contact us | feedback always welcome
Runtime Type Information (RTTI) was created more than a decade ago, yet most
developers remain unaware of its functions and benefits. This month's solution
explains when and how you can use RTTI for dynamic type detection.
by Danny Kalev
++ creators introduced Runtime Type Information (RTTI) more than a decade ago. Yet even today many
programmers arent fully aware of its benefits and perils. In the following sections, I will show when and how
you should use RTTI.
Object-oriented pundits claim that with a proper design and judicious use of virtual member function, you
won't need to use RTTI. However, under certain conditions, for example, when using heterogeneous
containers and root-based class hierarchies (MFC for example), dynamic type detection is sometimes
unavoidable. How can you detect an objects dynamic type?
class File
public:
//
};
Classes derived from File implement the pure virtual functions and provide additional operations. For
example, a DiskFile class may add the flush() and defragment() operations:
public:
// specialized operations
};
You then derive additional classes from DiskFile such as TextFile and MediaFile, for files that contain audio
and video clips:
//
int sort_by_words();
};
//..
};
if(some_condition)
else
pfile = new DiskFile; //dynamic type is DiskFile
Suppose you're developing a GUI-based file manager that displays files as icons. When you pass your
mouse over such an icon and click, the file manager opens a menu that adjusts itself dynamically according
to the marked file. The menu lists a set of operations such as "copy", "paste," and "open." In addition, it
displays specialized operations for the particular file. Thus, for a text file, it adds the "edit" operation whereas
for a multimedia file it displays the "play" operation instead.
Using RTTI
To customize the menu dynamically, the file manager has to probe each files dynamic type.
Operator typeid
Operator typeid retrieves the runtime type information associated with a certain object. typeid takes an
object or a type name as its argument. Thus, to determine if the dynamic type of x is Y, check whether the
expression typeid(x) == typeid(Y) is true:
if (typeid(*pfile)==typeid(TextFile))
add_option("edit");
else if (typeid(*pfile)==typeid(MediaFile))
add_option("play");
TIP: Certain compilers, such as Visual C++, disable RTTI by default to eliminate performance
overhead. If your program does use RTTI, remember to enable RTTI before compilation.
The use of typeid might introduce maintenance problems in the future. Suppose you decide to extend the
class hierarchy and derive another class from MediaFile called LocalizedMedia that represents a media file
with subtitles in various languages. Yet in essence, a LocalizedMedia file is a MediaFile. Therefore, the file
manager should display the "play" option when the user right clicks on a LocalizedMedia file. Unfortunately,
the build() member function will fail to do so because you didnt include a test for this particular file type. To
fix this, you can patch it like this:
//..
else if (typeid(*pfile)==typeid(LocalizedMedia))
add_option("play");
Alas, this function will have to be patched every time you add a new class. Clearly, this isn't an ideal
solution.
Operator dynamic_cast
You need a way to determine whether a certain object is a MediaFile or any class derived from it. This is
exactly what operator dynamic_cast does. dynamic_cast takes two arguments: a type name and a pointer or
a reference to a polymorphic object. It attempts to cast at runtime the object to the target type and returns
the result. Put differently, if the function succeeds in casting *pfile to MediaFile dynamically, then pfile's
dynamic type is MediaFile or a class derived from it. Otherwise, pfile is a different beast:
add_option("play");
add_option("edit");
}
}
Moderation is Advised
Although the use of dynamic_cast solves this problem neatly, it exacts a toll. As opposed to typeid, a
dynamic cast isn't a constant time operation. In order to determine whether the cast can be performed,
dynamic_cast must traverse the derivation lattice of its argument at runtime. Therefore, use dynamic_cast
judiciously.
Danny Kalev is a system analyst and software engineer with 13 years of experience, specializing in C++
and object-oriented analysis and design. He was a member of the ANSI C++ standardization committee
between 1997-2001. Danny is the author of ANSI/ISO C++ Professional Programmer's Handbook (Que,
1999, ISBN: 0789720221). Check out the DevX review here. He can be reached at dannykk@inter.net.il.
Snow.
C++ Programming/RTTI
From Wikibooks, the open-content textbooks collection
< C++ Programming
Jump to: navigation, search
Contents
[hide]
[edit] dynamic_cast