0

Possible Duplicate:
C++: Accessing Virtual Methods

I'm trying to use the virtual method table to call functions by index in a class... Suppose we have the following code:

class Base
{
public:
    Base() {}
    virtual ~Base() {}

    virtual Base* call_func(unsigned int func_number)
    {
       // Some way to call f_n
    }
protected:
    virtual Base* f_1() const = 0;
    virtual Base* f_2() const = 0;
    virtual Base* f_3() const = 0;
};

I've already implemented this using function arrays, if-statement and case-statement... so, Is there a a better approach to call methods using just pointers (accessing to the vtable for example) or something like that?

After resolve this i'm going to create derived classes (for example derived1 and derived 2) with different implementations of f_1, f_2, f_3 and have a class control like this:

class Control
{
protected:
    Base* current;

public:
    Control(Base* curr = new derived1): current(curr) {}
    virtual ~Control() 
    {
        delete current;
    }
    virtual void call_functions(unsigned int func_numb)
    {
        delete current
        Base* new = current->call_func(func_numb);
        current = new;
    }
};

Sorry for my horrible English :S... and thanks in advance!

2

3 Answers 3

1

C++ doesn't have very good built-in introspection, i.e., as you probably know, you can't look up a member function by name at runtime and call it from a named lookup. But you can create a table of member function pointers; see, for example, the example in the C++ FAQ Lite entry How do I create and use an array of pointer-to-member-function?. (I hope this is not the same as the "function arrays" you already mentioned, but it does seem to be the best way to accomplish what you want.)

If I may ask, why do you need to call functions by index? Virtual functions usually exist to accomplish a specific task with their own set of parameters for the task.

If you were to access the vtable more directly, you might make something work, but it would be brittle and non-portable.

1
  • yes you're right, i'll take your last paragraph as a good answer to my question Dec 12, 2012 at 15:12
0

Use pointer to member functions:

virtual Base* call_func(Base *(Base::*pf)())
{
  return this->*pf();
}

If you need the argument to be an arithmetic scalar, use a lookup array:

virtual Base* call_func(unsigned int func_number)
{
  static const Base *(Base::*(table[]))() = { &Base::f_1, &Base::f_2, &Base::f_3 };
  return this->*(table[func_number])();
}
0

Just a rough code.

void *vptr = *(void**)this;
void *method = ((void**)vptr)[index + first_method_offset];
typedef void (*method_type)();
void *m = (method_type)method;
m();

where first_method_offset is needed if your indexed methods are not first in the vtable.

Not the answer you're looking for? Browse other questions tagged or ask your own question.