dynamic_cast is primarily used to perform “safe downcasting,”i.e., to determine whether an object is of a particular type in an inheritance hierarchy.
class Window {.. };
class SpecialWindow: public Window {
public:
void blink();
};
typedef
std::vector<std::tr1::shared_ptr<Window> > VPW;
VPW winPtrs;
...
for (VPW::iterator iter = winPtrs.begin(); iter != winPtrs.end(); ++iter) {
if (SpecialWindow *psw = dynamic_cast<*SpecialWindow>(*iter)) {
psw->blink;
}
}
try to do this instead
I.
typedef std::vector<std::tr1::shared_ptr<SpecialWindow> > VSPW;
VSPW winPtrs;
...
for (VSPW::iterator iter = winPtrs.begin(); iter != winPtr.end(); ++iter) {
(*iter)->blink();
}
II.
provide virtual functions
class Window {
public:
virtual blink() { }
...
};
class SpecialWindow: public Window {
public:
virtual blink() { ... }
};
typedef std::vector<std::tr1<shared_ptr<Window> > VPW;
VPW winPtrs;
for (VPW::iterator iter = winPtrs.begin(); iter != winPtrs.end(); ++iter) {
(*iter)->blink();
}