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