Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing subclass members from a baseclass pointer C++

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?

like image 953
David Mason Avatar asked Apr 01 '10 10:04

David Mason


1 Answers

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();
}
like image 58
Thomas Bonini Avatar answered Oct 08 '22 18:10

Thomas Bonini