Dynamic Casts - B* bp =...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Dynamic Casts In the last issue we discussed runtime type identification, a mechanism for obtaining the type of an object during program execution. There is another aspect of this that we need to mention, the dynamic_cast<> feature. If we have an expression: dynamic_cast<T*>(p) then this operator converts its operand p to the type T*, if *p really is a T or a class derived from T; otherwise, the operator returns 0. What does this mean in practice? Suppose that you have a pointer or reference to a base class, and you want to know whether you "really" have a base class pointer, or instead a pointer to some class object derived from the base class. In this case, you can say: #include <typeinfo.h> #include <iostream.h> class A { public: virtual void f() {cout << "A::f\n";} }; class B : public A { public: virtual void f() {cout << "B::f\n";} }; void f(A* p) { //cout << (void*)(B*)p << endl;
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: B* bp = dynamic_cast&lt;B*&gt;(p); if (bp) bp-&gt;f(); } int main() { A* ap = new A(); B* bp = new B(); f(ap); f(bp); return 0; } Here we have a program that creates A and B objects, and passes pointers to them to a function f(). f() checks whether p is really a pointer to a B, and if so, calls B::f(). Note that we could use the technique shown in the last issue if all we want to do is check the type. But there are advantages to combining the check and the cast. One is that a combined operator makes it difficult to mismatch the test and the cast. Another advantage is that a static cast, for example as illustrated in the commented-out line above, doesn't always give the correct result. That is, it relies on static information and doesn't know whether a base class pointer &quot;really&quot; points at a derived object instance....
View Full Document

This note was uploaded on 02/27/2012 for the course CS 251 taught by Professor Staff during the Fall '08 term at Purdue University-West Lafayette.

Page1 / 2

Dynamic Casts - B* bp =...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online