I have an array of custom class Student objects. CourseStudent and ResearchStudent both inherit from Student, and all the instances of Student are one or the other of these.
I have a function to go through the array, determine the subtype of each Student, then call subtype-specific member functions on them.
The problem is, because these functions are not overloaded, they are not found in Student, so the compiler kicks up a fuss.
If I have a pointer to Student, is there a way to get a pointer to the subtype of that Student? Would I need to make some sort of fake cast here to get around the compile-time error?
The best thing would be to use virtual functions:
class Student
{
// ...
virtual void SpecificFunction() = 0; /* = 0 means it's abstract; it must be implemented by a subclass */
// ...
};
class CourseStudent
{
void SpecificFunction() { ... }
};
Then you can do:
Student *student;
student->SpecificFunction();
A (worse) alternative can be using dynamic_cast
:
Student *student;
CourseStudent *cs = dynamic_cast<CourseStudent *>(student);
if (cs) {
/* student is a CourseStudent.. */
cs->SpecificFunction();
}