Question

Is there any right way to declare a class (interface) Limit that can be used as "composition" of both interfaces Param and Lim?

Base interface classes Param and Lim:

class Param {
public:
    virtual char *toStr(void) = 0;
};

class Lim {
public:
    virtual char *toStrL(void) = 0;
};

ParamA and ParamB implements interface Param:

class ParamA : public Param {
public:
    virtual char *toStr(void){ return "A";};    
};

class ParamB : public Param {
public:
    virtual char *toStr(void){ return "B";} 
};

LimitA and LimitB additionally implements Lim:

class LimitA : public ParamA, public Lim {
public:
    virtual char *toStrL(void){ return "LA";}
};

class LimitB : public ParamB, public Lim {
public:
    virtual char *toStrL(void){ return "LB";}
};

With Limit I would like to access methods toStr() and toStrL()

class Limit : public Param, public Lim {
};

void example(void){
    LimitA limitA;
    LimitB limitB;
    Limit *limit = polymorphic_downcast<Limit *>(&limitB);  // unable to type cast correctly
    char *str1 = limit->toStr();
    char *str2 = limit->toStrL();
}
Was it helpful?

Solution

No, that's not possible. The runtime can only know about derived classes you explicitly inherited from in the class declaration. You cannot insert extra classes later.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top