Ghost of Bill Gates Ghost of Bill Gates - 1 year ago 56
C++ Question

Is this typecasting? What is this?

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

((MultipleAnswerQuestion*)second)->setAlternative(2, "City2");

And why is this done instead of just

second->setAlternative(2, "City2");


((MultipleAnswerQuestion)second)->setAlternative(2, "City2");

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?


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);

((MultipleAnswerQuestion*)second)->setAlternative(2, "City2");

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


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


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

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download