Re: [ROOT] C++ Question

From: Radovan CHYTRACEK (Radovan.Chytracek@cern.ch)
Date: Fri Mar 16 2001 - 16:22:53 MET


Olivier Meplan wrote:
> 
> Hi Rooters!
> I have a C++ question....It is related to pointer to functions of a
> class. I want define in a base class a method (name RK in the example)
> which used pointer to methods of a derived class...and I don't now how
> to do. Here is what I do (and which of course don't work):
> 
> the base class A:
> 
> class A {
>    void (*Fct)(double t,double *X,double *dX);
>    void RK(...);
> };
>  RK methods use the pointer Fct.
> 
> then a class B:
> 
> class B : public A {
>     ...
>    void EDP1(double t,double *X,double *dX);
>    void EDP2(double t,double *X,double *dX);
>    void Evol(...);
> };
> 
> Now in the method Evol(...) I want to use A::RK(...) with either EDP1 or
> EDP2 for the pointer Fct (e.g. Fct=EDP1) but the cast don't work.

What about the following code.
However I do not recommend this ugly style of OO programming.
It could work or not depending on C++ compiler.
This code works for me using EGCS 1.1.2 on Linux.
If I remember correctly it worked for me on Win/NT Visual C++ 5.0/6.0 as
well.

Better to go and search at Google for "Callbacks in C++" where you get a
pointers to some nice and elegant
solutions.

#include <iostream>
    
// Functor prototype
class functor_ddd {
public:
  functor_ddd( double t , double* X, double* dX ) : ft(t),fX(X),fdX(dX)
{}   
  virtual void operator()() = 0;
protected:
  double  ft;
  double* fX;
  double* fdX; 
};

typedef functor_ddd Fct;

class A {
public:
    void RK( Fct* func ) {
    if( func != 0 )
       (*((Fct *)func)) ();
    }
};

class B : virtual public A {
public:
    class func1 : public Fct {
    public:
      func1( double t , double* X, double* dX ) : functor_ddd(t,X,dX) {}   
      void operator() () {
        std::cout << "func1>> " << "t: " << ft << " X: " << *fX << " dX: "
<< *fdX << std::endl;
      }
    };

    class func2 : public Fct {
    public:
      func2( double t , double* X, double* dX ) : functor_ddd(t,X,dX) {}   
      void operator() () {
        std::cout << "func2>> " << "t: " << ft << " X: " << *fX << " dX: "
<< *fdX << std::endl;
      }
    };

    void Evol( int which, double& a, double& b, double& c) {
      Fct* pFunc = 0;
      switch( which ) {
        case 1: pFunc = new func1( a, &b, &c ); break;
        case 2: pFunc = new func2( a, &b, &c ); break;
        default: break;
      };
      
      A::RK( pFunc );

      if( pFunc != 0 ) {
        delete pFunc;
        pFunc = 0;
      }
    }
};

int main( int argc, char* argv[] )
{
  B go; double tval = 1.; double val = 2.; double dVal = 3.;
  go.Evol( 1, tval, val, dVal );
  tval = 4.; val = 5.; dVal = 6.;
  go.Evol( 2, tval, val, dVal );
  return 0;
};




This archive was generated by hypermail 2b29 : Tue Jan 01 2002 - 17:50:39 MET