13.8 THE CLIMAX: ARRAY OF DERIVED CLASS OBJECTS

So far, we have used individual pointers for different derived classes. We know that base class pointer can point to derived class objects. Therefore, it is possible to define an array of base class pointer which points to derived class objects. It means that we can have an array where not all the array elements need to be of the same type. This is a great advantage.

Consider a case where Employee is the base class and Worker, Staff and Officer are the derived class. We could now write a code

Employee *eptr[3];  eptr[0] = new Worker() ;  eptr[1] = new Staff() ;  eptr[2] = new Officer() ;

Now, we have effectively an array of three dissimilar objects – objects belonging to different classes. We were ...

Get Object Oriented Programming with C++, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.