C++ (Qt)#include <iostream> class Base {public: virtual ~Base() { }}; class Foo{public: virtual ~Foo() { }}; class FooBase: public Base, public Foo{ }; int main(){ Base *base = new FooBase; Foo *foo = dynamic_cast<Foo *>(base); if (foo){ std::cout << "yes"; } else { std::cout << "no"; }}
C++ (Qt) Foo *foo = dynamic_cast<Foo *>(base);
C++ (Qt)#include <stdio.h> struct Root { virtual ~Root( void ) {}}; struct Leaf1 { virtual ~Leaf1( void ) {}}; struct Leaf2 { virtual ~Leaf2( void ) {}}; struct Tree : public Root, public Leaf1, public Leaf2 {}; int main( void ){ Tree * tree = new Tree; Leaf1 * leaf1 = tree; Leaf2 * leaf2 = dynamic_cast<Leaf2 *> (leaf1); printf("Tree = %p, Leaf1 = %p, Leaf2 = %p\n", tree, leaf1, leaf2); return 0;}
C++ (Qt)class A { virtual void f(); };class B { virtual void g(); };class D : public virtual A, private B { };void g() { D d; B* bp = (B*)&d; // cast needed to break protection A* ap = &d; // public derivation, no cast needed D& dr = dynamic_cast<D&>(*bp); // fails ap = dynamic_cast<A*>(bp); // fails bp = dynamic_cast<B*>(ap); // fails ap = dynamic_cast<A*>(&d); // succeeds bp = dynamic_cast<B*>(&d); // ill-formed (not a run-time check)}
C++ (Qt)B* bp = (B*)&d; // cast needed to break protection
C++ (Qt)Leaf1 * leaf1 = new Leaf1;Leaf1 * leaf1_1 = tree;
B* bp1 = (B*)&d;B* bp2 = &d; // допустим, там publicassert(bp1 == bp2); // false