#include <stdio.h>
class A {
 public:
    A() : next(0) {
        if (head == 0) {
            head = this;
        } else {
            A* step = head;
            while (step->next != 0) {
                step = step->next;
            }
            step->next = this;
        }
    }
    virtual ~A() {
        if (head == this) {
            head = 0;
        } else {
            A* step = head;
            while (step->next != this) {
                step = step->next;
            }
            step->next = next;
        }
    }
    
    static A* head;
    A* next;
};

class B : public A {
 public:
    B() {}
    virtual ~B() {}
    virtual void foo() {
        printf("function foo\n");
    }
};

class C : public A {
 public:
    C() {}
    virtual ~C() {}
    virtual void bar() {
        printf("function bar\n");
    }
};

class D : public B {
 public:
    D() {}
    virtual ~D() {}
    virtual void foo() {
        printf("function foo from D\n");
    }
};

A* A::head = 0;

int main() {
    A a_cls;
    B b_cls;
    C c_cls;
    D d_cls;

    A* step = A::head;
    B* step_b = 0;

    while (step != 0) {
        step_b = dynamic_cast<B *>(step);
        if (step_b != 0) {
            step_b->foo();
        }
        step = step->next;
    }

    return 0;
}
