could somebody explain the creation of the code.

#include <iostream>

using namespace std;

class First {
        public:
                int a;
                First() {};
                First(int a) {
                        this->a = a;
                }

                int getA() {
                        return a;
                }

                virtual int getB() {
                        cout << "getB() from super class..." << endl;
                        return 0;
                }
};

class Second : public First {
        public:
                int b;
                Second(int b) {
                        this->b = b;
                }

                int getB() {
                        cout << "getB() from child class..." << endl;
                        return b;
                }

};

int main() {
        First* t = new Second(2);
        First* cTest = dynamic_cast<First*>(t);
        cout << cTest->getB() << endl;

}

I was expecting the technique from the super class could be known as due to the casting to First.

thanks ahead of time

regards sebastian

The function getB() is virtual within the base class, which means you obtain the derived implementation whether or not you've got a pointer-to-base or pointer-to-derived.

(This is the whole reason for polymorphism.)

An engaged cast in the hierarchy does not alter the fundamental proven fact that you are still pointing in a B. Particularly, it does not alter the vtable used to obtain the implementation of getB() that'll be used.

Typically, you simply need dynamic_cast() to visit lower an inheritance hierarchy, not up.

There only is available one object, which is of type Second.

To obtain the behavior you're searching for, you will have to produce a copy and slice it:

First cTest = static_cast<First>(*t);
cout << cTest.getB() << endl;

You are not altering anything together with your cast. You're casting an initial- to some First*, that is simply a project. Since t is another with = new Second(2), you've overridden the virtual table using the child's records, therefore it will call the youngsters techniques as opposed to the parents.

cTest is only a pointer-to-First which indicates the identical object that t does, because cTest and t retain the same memory address, where is available another object, and that's why the Second's technique is known as.