Search code examples
c++inheritancevirtual-functionsdynamic-caststatic-cast

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?


Solution

  • You need a dynamic cast:

    Student * s = new ...;    // Create student of some sort.
    
    if ( ResearchStudent * r = dynamic_cast<ReasearchStudent*>( s ) ) {
       r->ResFunc();
    }
    else if ( CourseStudent * c = dynamic_cast<CourseStudent*>( s ) ) {
       c->CourseFunc();
    }
    else {
       throw "Unknown student type.";
    }
    

    Note that this uses type information maintained by the compiler, provided the class has at least one virtual function - if all else fails, make the destructor virtual (as it must be in this case anyway). You should always prefer this approach to maintaining your own type information.