[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CppDynamicCast

(C++) dynamic_cast

keyword enabling you to cast pointers-to-X to a pointer-to-Y, in which X and Y are related classes.

Casting from a pointer-to-base class to a pointer-to-derived class is called downcasting. Casting from a pointer-to-derived class to a pointer-to-base class is called upcasting.

  Base * b = new Derived;
  const Derived * d = dynamic_cast<const Derived*>(b); //Downcast
  const Base * b2 = dynamic_cast<const Base*>(d); //Upcast


If this conversion is successfull, dynamic_cast returns the pointer, else it returns 0.

Other standard casts are: dynamic_cast is not supported in C.

Example

In the example below I create a std::vector of base class pointers. I initialize these with two types of derived classes, after which I shuffle these. From then on, I do not know anymore which is which. Using dynamic_cast I can find out at run-time.

  1. include <stdlib>
  2. include <vector>
  3. include <algorithm>
  4. include <iostream>
  5. include <assert>
class Base { public: Base() : mB(std::rand()) {} virtual void sayHello() const = 0; const int mB; }; class Derived1 : public Base { public: Derived1() : Base(), mD1(std::rand()) {} const int mD1; void sayHello() const { std::cout << "Hello from Derived1" << std::endl; } }; class Derived2 : public Base { public: Derived2() : Base(), mD2(-std::rand()) {} const int mD2; void sayHello() const { std::cout << "Hello from Derived2" << std::endl; } }; int main(int argc, char* argv[]) { std::vector<Base*> v; for (int i=0; i<10; ++i) { Base * temp = new Derived1; v.push_back(temp); } for (int i=0; i<10; ++i) { Base * temp = new Derived2; v.push_back(temp); } std::random_shuffle(v.begin(),v.end()); for (int i=0; i<20; ++i) { const Derived1 * d1 = dynamic_cast<Derived1*>(v[i]); const Derived2 * d2 = dynamic_cast<Derived2*>(v[i]); assert(d1!=d2); //Only one cast will succeed, other will be 0 if (d1!=0) std::cout << i << " : " << " Derived1: " << d1->mD1 << std::endl; if (d2!=0) std::cout << i << " : " << " Derived2: " << d2->mD2 << std::endl; } return 0; }


Topic links



last edited (November 15, 2006) by bilderbikkel, Number of views: 4284, Current Rev: 14 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.