[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
CppDynamicCast
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.
If this conversion is successfull, dynamic_cast returns the pointer, else it returns 0.
Other standard casts are:
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
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:
- static_cast, for casting between simple data types (e.g. between int and double)
- const_cast, for casting away const
- reinterpret_cast, for casting between unrelated data types
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.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; }
- include <stdlib>
- include <vector>
- include <algorithm>
- include <iostream>
- include <assert>
Topic links
- argc
- argv
- assert
- class
- const
- cout
- endl
- for
- if
- int
- main
- new
- public
- std
- std::cout
- std::endl
- std::vector
- vector
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
