templates - C++ calling the right virtual function -
i have problem following situation:
template<class t> class { public: virtual int f() { return 1; } }; class basea : public a<basea> {}; class deriveda : public basea, public a<deriveda> {};
and when do:
basea* b1 = new deriveda; b1->f();
it calls a<basea>::f()
instead of a<deriveda>::f()
, don't know how fix it.
additional info op: homework problem class a
can freely changed, classes basea
, deriveda
cannot changed.
then following 1 solution, based on dominance in virtual inheritance hierarhcy:
#include <iostream> #include <typeinfo> using namespace std; struct basea; struct { virtual auto f() -> int = 0; }; template<class t> class : public virtual { public: virtual auto f() -> int override { cout << typeid( t ).name() << '\n'; return 1; } }; template<> class a<basea>: public virtual {}; class basea : public a<basea> {}; class deriveda : public basea, public a<deriveda> {}; auto main() -> int { basea* b1 = new deriveda; b1->f(); }
Comments
Post a Comment