I got these virtual classes from a library that implement an algorithm in the form of abstract classes
class A{
public :
virtual void foo() = 0 ;
};
class B{
public:
void setA(A * a) { m_a = a ;}
virtual void f() = 0;
void g() {m_a->foo();}
protected:
A * m_a ;
};
To use the library you just have to derive the classes and implement the pure virtual functions, like foo(), and provide other methods specific to the implementation as well (bar()).
class dA : public A {
public :
void foo() {/* ... */}
void bar() {/* ... */}
};
class dB : public B {
public :
void f() ;
};
I would typically use these class by calling
dB * mydB = new dB() ;
mydB->setA(new dA() );
mydB->f() ;
mydB->g() ;
But I have a design problem when implementing dB::f(), because I need to call dA::bar() which is specific to dB. But in the class, I only keep a reference to dB trough a B*. Then I have thought of two options :
- use a
dynamic_casteach timef()is called to castB::m_ainto adB* - add a m_dA member to dB which stores the same pointer as m_a, but can be used to access dB specific functions.
Of course I can’t change the the base classes.
I would like to know if there is a more elegant solution to this problem (like a design pattern I did not thought of). If not, which one should I choose ?
You’ve a third solution. Add a function
setA()in thedB. Of course, this function will hideB::setA()which is good for you ifdB::setA()is implemeted as:In this way, you don’t need to dynamic_cast each time you call
dB::f(), which makes the call fast!