C++ calling the right virtual function

107 views Asked by At

I have a problem with the following situation:

 template<class T>
class A {
public: virtual int  f() { return 1; }
};

class BaseA : public A<BaseA> {};
class DerivedA : public BaseA, public A<DerivedA> {};

and when I do:

 BaseA* b1 = new DerivedA;
b1->f();

it calls A<BaseA>::f() instead of A<DerivedA>::f() and I don't know how to fix it.

2

There are 2 answers

4
Cheers and hth. - Alf On

Additional info from the OP: this is a homework problem where class A can be freely changed, but classes BaseA and DerivedA cannot be changed.

Then the following is one solution, based on dominance in a virtual inheritance hierarhcy:

#include <iostream>
#include <typeinfo>
using namespace std;

struct BaseA;

struct I
{
    virtual auto  f()
        -> int = 0;
};

template<class T>
class A
    : public virtual I
{
public:
    virtual auto  f()
        -> int override
    { cout << typeid( T ).name() << '\n'; return 1; }
};

template<>
class A<BaseA>: public virtual I {};

class BaseA : public A<BaseA> {};
class DerivedA : public BaseA, public A<DerivedA> {};

auto main() -> int
{
    BaseA* b1 = new DerivedA;
    b1->f();
}
1
Nagendra NR On

The Following program calls f from derivedA (output : f in derived). Works fine.. anything wrong here ?

#include <iostream>
using namespace std;

template<class T>
class A
{
  public:
   virtual int f()
   {
       return 1;
   }
};

class BaseA : public A<BaseA>
{
  public:
  virtual int f()
  {
   cout << "f in base" << endl;
   return 1;
  }
};

class DerivedA :  public BaseA, public A<DerivedA>
{
   public:
   int f()
   {
       cout << "f in derived" << endl;
       return 1;
    }
};

main() {
    BaseA* b1 = new DerivedA;
    b1->f();
}