How to do casting between base and derived classes?

2

I have an exercise that says I have to create a foundation. This basis has two derivatives. I have to do a cast of the derived class (1) for the derived class (2) and the derived class (2) for the base class. How should I do an exercise like this without using references ?

    
asked by anonymous 02.03.2014 / 14:39

1 answer

2

This may show the use of a cast for a base class:

#include <iostream>

class Base{
public:
    void metodoHerdado(){

        std::cout << "Metodo na base" << std::endl;
    }
};

class Derivada : public Base{
public:
    void metodoHerdado(){

        std::cout << "Metodo na derivada" << std::endl;
    }
};

int main(){

    Base* ponteiroBase = new Derivada;

    Derivada* ponteiroDerivada = static_cast<Derivada*>(ponteiroBase);

    ponteiroBase->metodoHerdado();
    ponteiroDerivada->metodoHerdado();

    return 0;
}

The example basically shows that we can create an instance from a derived class and "store it" in a pointer to the base class, but non-virtual methods called from this pointer will cause the methods defined in the class to execute base. If you need to call a method that is redefined in the derived class in this case, you need to cast a cast so that the pointer is recognized as being for the derived class.

For a sister class, I need to think better about a justification =)

    
25.06.2014 / 19:48