Search code examples
c++pointerslanguage-agnostic

Is this typecasting? What is this?


Is this typecasting in C++ or am I seeing things?

    ((YesNoQuestion*)first)->setAnswer(false);
    ((MultipleAnswerQuestion*)second)->setAlternative(2, "City2");
    ((MultipleAnswerQuestion*)second)->setCorrectAlternative(2);

And why is this done instead of just

    first->setAnswer(false);
    second->setAlternative(2, "City2");
    second->setCorrectAlternative(2);

or

    ((YesNoQuestion)first)->setAnswer(false);
    ((MultipleAnswerQuestion)second)->setAlternative(2, "City2");
    ((MultipleAnswerQuestion)second)->setCorrectAlternative(2);

Doesn't the pointer provide the sufficient "identity" to make member functions of a child class viable for the parent class?

And why make the types pointers as well? Is it because the Question-objects are pointers that the new type has to be a pointer too?


Context:

These are answers from an old exam 5-6 years ago and everyone is on vacation now so I can't ask the professors who made it, but they did this in the main-file:

#include "MultipleAnswerQuestion.h"
#include "YesNoQuestion.h"

int main()
{
    Question *first = NULL;
    Question *second = NULL;

    string alt[] = {"City1", "City2", "City3"};
    first = new YesNoQuestion("Some statement here");
    second = new MultipleAnswerQuestion("Some question here", alt, 3, 0);

    ((YesNoQuestion*)first)->setAnswer(false);
    ((MultipleAnswerQuestion*)second)->setAlternative(2, "City2");
    ((MultipleAnswerQuestion*)second)->setCorrectAlternative(2);

    first->print(); //Prints Q
    second->print(); //Prints Q

}

Abstract baseclass: Question(string question = "");

Children:

YesNoQuestion(string question = "", bool answer = true);

MultipleAnswerQuestion(string question, string alternatives[], 
                       int nrOfAlternatives, int correctAnswer);

Solution

  • This is a type of type casting used for polymorphism. The first alternative you proposed would only work if the base class Question has virtual methods for setAnswer, setAlternative and setCorrectAlternative. If not, then you'd have to convert the pointer to the good class in order for the method to be found. The second alternative would not work because first and second are pointers, therefore their values are an addresses. Interpreting those addresses as objects of a class would not make sense in itself.