Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) Dynamic_castExample1

 

Technical facts

 

Operating system(s) or programming environment(s)

IDE(s):

Project type:

C++ standard:

Compiler(s):

Libraries used:

 

 

 

 

 

Qt project file: ./CppDynamic_castExample1/CppDynamic_castExample1.pro

 

include(../../ConsoleApplication.pri) #Or use the code below
# QT += core
# QT += gui
# greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
# CONFIG   += console
# CONFIG   -= app_bundle
# TEMPLATE = app
# CONFIG(release, debug|release) {
#   DEFINES += NDEBUG NTRACE_BILDERBIKKEL
# }
# QMAKE_CXXFLAGS += -std=c++11 -Wall -Wextra -Weffc++
# unix {
#   QMAKE_CXXFLAGS += -Werror
# }

SOURCES += main.cpp

 

 

 

 

 

./CppDynamic_castExample1/main.cpp

 

#include <cassert>

struct Base
{
  virtual ~Base() {}
};

struct Derived : public Base { };

int main()
{
  //Base initialized with derived, can be downcasted to derived
  {
    Base * const p1 = new Derived;
    Derived * const p2 = dynamic_cast<Derived*>(p1);
    assert(p1);
    assert(p2);
    assert(p1 == p2);
    delete p1;
    //delete p2; //Do not re-delete!
  }
  //Base initialized with base, cannot be downcasted to derived
  {
    Base * const p1 = new Base;
    Derived * const p2 = dynamic_cast<Derived*>(p1);
    assert( p1);
    assert(!p2);
    assert(p1 != p2);
    delete p1;
  }
  //Const base initialized with derived, can be downcasted to const derived
  {
    Base * const p1 = new Derived;
    const Derived * const p2 = dynamic_cast<const Derived*>(p1);
    assert(p1);
    assert(p2);
    assert(p1 == p2);
    delete p1;
    //delete p2; //Do not re-delete!
  }
  //Const base initialized with base, cannot be downcasted to const derived
  {
    const Base * const p1 = new Base;
    const Derived * const p2 = dynamic_cast<const Derived*>(p1);
    assert( p1);
    assert(!p2);
    assert(p1 != p2);
    delete p1;
  }
  //Const base initialized with derived, cannot be down- and const-casted to non-const derived
  {
    const Base * const p1 = new Derived;
    //Removing const: will and should not compile
    //Derived * const p2 = dynamic_cast<Derived*>(p1));
    assert(p1);
    delete p1;
  }
  //Base initialized with derived, can be downcasted to const derived with adding constness
  {
    const Base * const p1 = new Derived;
    //Adding const: will and should compile
    const Derived * const p2 = dynamic_cast<const Derived*>(p1);
    assert(p1);
    assert(p2);
    assert(p1 == p2);
    delete p1;
    //delete p2; //Do not re-delete!
  }
}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict

This page has been created by the tool CodeToHtml