I have a situation where I need to achieve polymorphism without vtable. Here is what I am trying to do
- There is a class hierarchy: C extends B, B extends A
- The idea is to declare a function pointer in A and constructors of B and C assign their corresponding methods to the function pointer in A
- With the code below I am able to achieve polymorphism for class C but not for class B.
Obviously I am missing something here. I am not sure if this is even possible. Greatly appreciate any insights into this problem.
I can do this with the below code
A<C> *c = new C();
c->BasePrint(); //Reached C's Print
but not this
// A<B> *b = new B();
// b->BasePrint(); //Intentionally incorrect to demonstrate the problem.
Is there any way to achieve this?
template <typename T>
class A
{
public:
typedef void (T::*PrintFn)(void);
protected:
PrintFn printFn;
public:
void BasePrint()
{
if(printFn)
(((T*)this)->*printFn)();
}
};
template <typename T>
class B : public A<T>
{
public:
B()
{
printFn = &B::Print;
}
void Print()
{
//Print B
}
};
class C : public B<C>
{
public:
C()
{
printFn = &C::Print;
}
void Print()
{
//Print C
}
};