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

(C++) To upcast, to cast up, upcasting

Casting a pointer-to-a-derived class to a pointer-to-a-base class. This process will always succeed, as information is lost (as a base class 'has less information' as a derived class. The opposite is a downcast.

  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 funcBase(const Base * base) { //Does nothing std::cout << "funcBase called for Base with value " << base->mValueBase << std::endl; base; } //--------------------------------------------------------------------------- int main() { const Derived * derived = new Derived(1,2); funcBase(derived); //Implicit upcast to Base* funcBase(dynamic_cast<const Base*>(derived)); //Explicit upcast to const Base* delete derived; }


Code links



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