Pointing to a Derived Class

A pointer to a certain class can also point to a derived class. When this happens, only the members common to base and derived class can be accessed through the pointer. In order to access all members of a derived class through a base class pointer, the pointer must be cast to the derived class pointer type. All in all, although the pointer points to a derived object, it remains a base class pointer.

Example


#include <iostream>
#include <string>

using namespace std;

class BaseClass 
{
    string a;

public:
    void seta(string s) 
    {
        a = s;
    }
};

class DerivedClass : public BaseClass 
{
    string d;

public:
    void setd(string s) 
    {
        d = s;
    }
};

int main() 
{
    BaseClass baseObject;
    DerivedClass derivedObject;
    BaseClass *basePointer;

    basePointer = &baseObject;
    basePointer->seta("Hello");

    // The pointer points to a derived object
    basePointer = &derivedObject;  
    
    // A base class member can be instantiated
    basePointer->seta("Hi there"); 

    // basePointer->setd("goodnight"); wouldn't compile
    // because setd() belongs only to DerivedClass
}