[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
CppUpCast
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
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.//--------------------------------------------------------------------------- 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; }
- include <iostream>
Code links
- ::,scope operator
- <<,stream out operator
- #include
- assert
- char
- class
- cout
- delete
- endl
- for
- #include
- int
- iostream
- main
- new
- return
- scope operator,::
- std
- stream out operator, <<
- struct
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
