Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++. Class method pointers

There is a class

class A {
public:
    A() {};

private:
    void func1(int) {};
    void func2(int) {};


};

I want to add a function pointer which will be set in constructor and points to func1 or func2.

So I can call this pointer (as class member) from every class procedure and set this pointer in constructor.

How can I do it?

like image 889
Nikita Avatar asked Jul 23 '10 15:07

Nikita


1 Answers

class A {
public:
    A(bool b) : func_ptr_(b ? &A::func1 : &A::func2) {};

    void func(int i) {this->*func_ptr(i);}

private:
    typedef void (A::*func_ptr_t_)();
    func_ptr_t_ func_ptr_;

    void func1(int) {};
    void func2(int) {};
};

That said, polymorphism might be a better way to do whatever you want to do with this.

like image 152
sbi Avatar answered Oct 27 '22 03:10

sbi