Accessing subclass members from a superclass pointer C++

David Mason picture David Mason · Apr 1, 2010 · Viewed 16.5k times · Source

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?

Answer

Thomas Bonini picture Thomas Bonini · Apr 1, 2010

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