Design issue forcing me to down-cast base class to derived types


I have a class accepting the base class, but it needs to accept the derived class to perform derived-class-specific operations. However I need it to be polymorphic:

class I{
    OL ol;

class OD{
    int data_member1;
    int data_member2;

class FD : public OD {
    int data_member3;

class ND : public OD{
    int data_member4;


class OL{
    virtual void u(OD od) = 0;

class NL : public OL{
    //Accepts OD-type for polymorphism, but only ever uses ND-type objects
    void u(OD nd){
        //Manipulate datamember1
        //Manipulate datamember2
        //Manipulate datamember3 (which FD doesn't have)

class CL : public OL{
    //Accepts OD-type for polymorphism, but only ever uses FD-type objects
    void u(OD fd){
        //Manipulate datamember1
        //Manipulate datamember2
        //Manipulate datamember4 (which ND doesn't have)

The problem is that I have to declare the parameter type for OL::u() as OD (so that I can use polymorphism), but in NL::u() and CL::u() the parameter type must be the derived so that I can access the data members that particular derived has (ND doesnt have datamember4 and FD doesnt have datamember3).

What should I do? The only solution I can think of is to down-cast the OL object in NL::u() and CL::u() to the derived type, but this feels very "hacky".

My overall aim is to be able to do:

I i1;
OD fd = new FD();

I i2;
OD nd = new ND();

This video can help you solving your question :)
By: admin