How to cast between base and derivative classes?

Asked

Viewed 631 times

3

I have an exercise that says I have to create a foundation. This base has two derivatives. I have to cast 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?

  • The exercise is confused, poorly formulated. Casting a daughter class to a mother class is done automatically.

  • 1

    @Henriquebarcelos say this to my teacher :/ I thought the same thing!

  • I believe the only way is to contact him and ask him to explain better what he wants. Then you update the question here.

  • @Henriquebarcelos Haha... He just emailed me that the exercise would be clarified; half the students reported the difficulty to him!

  • @Henriquebarcelos I edited the question, but I removed my code, because now I just want to learn!

  • 2

    It still doesn’t make any sense, because there is no relationship between derivada1 and derivada2. They can be considered of the same supertype, but there is no conversion between one and the other. This exercise basically asks you to extend a class Fruta with Banana and Maçã and turn a banana into an apple. Teachers and their wild ideas --'

Show 1 more comment

1 answer

3

This can 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 the non-virtual methods called from this pointer will cause the methods defined in the base class to be executed. If you need to call a reset method in the derived class in this case, you will need to cast a pointer to be recognized as being for the derived class.

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

  • If you could put more text explaining the answer would be excellent!

  • 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 the non-virtual methods called from this pointer will cause the methods defined in the base class to be executed. If you need to call a reset method in the derived class in this case, you will need to cast a pointer to be recognized as being for the derived class.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.