C++, How do you call a derived member function from a base class?


The original programmer had this idea that seems to work on whatever compiler he was using, but doesn't work so well in VS C++. The practice looks very questionable to me.

He's got a generic base class called mathObject that has a lot of common math functions. On top of that, he's got a class called Cosmos and on top of that, another one called QuintCosmos.

The general idea is that he wants to call a member function that has the same signature from either Mathobject or Cosmos or QuintCosmos. He's trying to cast it to

typedef void (Mathobject::*moDerivs) (const double, const double*, double*)

So, to recap, he can have function with this signature anywhere in this hierarchy and he wants to tell a third class (an Ordinary Differential Equation, ODE, Solver), to use a function with this signature.

hnext = Miscmath::odeint(&QuintCosmos::propagateHistoryInTau, this);

In the odeint() method, he calls this function like so.

double Miscmath::odeint(moDerivs derivs, Mathobject* mo)
    (mo->*derivs)(x, y, dydx);

This fails to compile in VS C++ with

error C2664: 'double Miscmath::odeint(moDerivs,Mathobject *)': cannot convert argument 1 from 'void (__thiscall QuintCosmos::* )(const double,const double *,double *)' to 'moDerivs'

The original author tried to cast the function pointer with (moDerives) like this:

hnext = Miscmath::odeint((moDerivs)&QuintCosmos::propagateHistoryInTau, this);

This allows it to compile, but it fails at runtime with:

Exception thrown at 0x001E7148 in cmb-easy.exe: 0xC0000005: Access violation reading location 0x0000006C.

So, bottom line, does anyone know how to accomplish this: execute a member function from a base class?

asked on Stack Overflow Jan 28, 2020 by Quarkly • edited Jan 28, 2020 by Remy Lebeau

0 Answers

Nobody has answered this question yet.

User contributions licensed under CC BY-SA 3.0