Prayagasoft - web designer India, Ecommerce developer india, Ecommerce design

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; B* bp = dynamic_cast<B*>(p); if (bp) bp->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 "really" points at a derived object instance.

 

India seo freelance web designer India web development ecommerce website developer India
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100