-2

I need an array of pointers to member functions in a base class like this

class Base {
public:
    typedef int(Base::*func)();
    func f[3];
    Base();
    void run();
};

void Base::run()
{
    cout << (this->*f[0])() << endl;
    cout << (this->*f[1])() << endl;
    cout << (this->*f[2])() << endl;
}

The function run() will be the same for all child classes. But pointers in the array f[] will refer to member functions that will be defined in the child classes.

class Child: public Base {
public:
    typedef int(Child::*func)();
    func f[3];
    int A();
    int B();
    int C();
    Child();
};
int Child::A()
{
    return 1;
}
int Child::B()
{
    return 2;
}
int Child::C()
{
    return 3;
}
Child::Child()
{
    f[0] = &Child::A;
    f[1] = &Child::B;
    f[2] = &Child::C;
}

If I run this code in program I get problems

Child x;
x.run(); 

How to do this?

2 Answers2

1

This works:

class Base {
public:
    typedef int(Base::*func)();
    func f[3];
    virtual int A() { return 0; }
    virtual int B() { return 0; }
    virtual int C() { return 0; }
    Base() {};
    void run()
    {
        cout << (this->*f[0])() << endl;
        cout << (this->*f[1])() << endl;
        cout << (this->*f[2])() << endl;
    }
};

 class Child: public Base {
     public:
     int A() { return 1; }
     int B() { return 2; }
     int C() { return 3; }
     Child()
     {
         f[0] = &Base::A;
         f[1] = &Base::B;
         f[2] = &Base::C;
    }
};
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
0

You're facing two major obstacles here.

One, you never initialize the Base::f but that is what run operates on. You declare a member f in the child class and initialize it in the constructor. The Base classes f is never initialized, and is filled with garbage. When you call run, it tries to use those random values. This is undefined behavior.

Two, int(Base::*)() and int(Child::*)() are two distinct and incompatible types. You look like you want to fill the array with pointers to child functions and call them from the base class.

There are a couple ways to fix this:

  1. You could make run virtual and implement it in the child class to call the functions.
  2. You could put the functions in the base class and make them virtual, so pointers to them will call the derived versions.
  3. You could make an array of std::function objects instead of pointers.
Weak to Enuma Elish
  • 4,622
  • 3
  • 24
  • 36