In brief: From a C++ base-class pointer which points to an instance of a derived class, how can one determine at run-time whether a non-pure virtual function (with an implementation in the base class) has been re-implemented in the derived class?
The context:
I am writing a C++ library to solve certain classes of mathematical equation. The library provides an Equation
class with several virtual functions, which library users use as a base class for the particular equation they wish to solve. The library also provides a Solver
class, which takes an Equation *
as a constructor parameter. The user then writes code along the lines of:
class MyEquation : public Equation
{ ... } // equation definition here
int main()
{
MyEquation myEqn;
Solver solver(&myEqn);
solver.Solve();
}
If certain combinations of the virtual functions in Equation
are not redefined in the derived equation class, certain computationally expensive parts of the algorithm run by the Solver
object can be omitted. I would therefore like to know, in the constructor of Solver
, which functions have been redefined, and which will instead run the default implementation in Equation
.
I would like to make this transparent to users of the library so I am not looking for a solution where, for example, the user sets some flags in the constructor of their derived equation specifying which functions have been redefined.
One possible solution is for the default implementations of the virtual functions in Equation
to set a private flag in the Equation
class; the constructor of the Solver
class can then clear this flag, run the virtual function, and check the flag value to see whether the implementation in Equation
has been called. I would like to avoid this though, because simply setting the flag every time the virtual function is executed slows the algorithm down a good deal (the execution of these virtual functions contributes significantly to the run time of the program, and the default implementations simply return a constant).
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…