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 =)
The exercise is confused, poorly formulated. Casting a daughter class to a mother class is done automatically.
– Henrique Barcelos
@Henriquebarcelos say this to my teacher :/ I thought the same thing!
– user2692
I believe the only way is to contact him and ask him to explain better what he wants. Then you update the question here.
– Henrique Barcelos
@Henriquebarcelos Haha... He just emailed me that the exercise would be clarified; half the students reported the difficulty to him!
– user2692
@Henriquebarcelos I edited the question, but I removed my code, because now I just want to learn!
– user2692
It still doesn’t make any sense, because there is no relationship between
derivada1
andderivada2
. 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 classFruta
withBanana
andMaçã
and turn a banana into an apple. Teachers and their wild ideas --'– Henrique Barcelos