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

(C++) Downcast

Casting a pointer-to-a-base class to a pointer-to-a-derived class using dynamic_cast. This process is not always successfull. The opposite of downcasting is upcasting.

  1. include <iostream>
//--------------------------------------------------------------------------- struct Base { Base(const int& value) : mValueBase(value) {} virtual void doCout() const { std::cout << "Base: " << mValueBase << std::endl; } const int mValueBase; }; //--------------------------------------------------------------------------- struct Derived : public Base { Derived(const int& value1, const int& value2) : Base(value1), mValueDerived(value2) {} virtual void doCout() const { std::cout << "Derived: " << mValueBase << " " << mValueDerived << std::endl; } const int mValueDerived; }; //--------------------------------------------------------------------------- void funcDerived(const Derived * derived) { //Does nothing std::cout << "funcDerived called for Derived with values " << derived->mValueBase << " and " << derived->mValueDerived << std::endl; derived; } //--------------------------------------------------------------------------- int main() { const Base * poly = new Derived(3,4); //funcDerived(poly); //Does not work: Cannot convert 'const Base *' to 'const Derived *' funcDerived(dynamic_cast<const Derived*>(poly)); //Works after downcasting with dynamic cast }


Code links



last edited (November 11, 2006) by bilderbikkel, Number of views: 1932, Current Rev: 5 (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.