Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Pointers to Member Functions Inheritance

Tags:

People also ask

How do you use pointers to member functions?

Using a pointer-to-member-function to call a function Calling the member function on an object using a pointer-to-member-function result = (object. *pointer_name)(arguments); or calling with a pointer to the object result = (object_ptr->*pointer_name)(arguments);

Can we create a pointer to a member function?

You can use pointers to member functions in the same manner as pointers to functions.

How to declare pointer-to-member-function c++?

Short answer: add a const to the right of the ) when you use a typedef to declare the member-function-pointer type. For example, suppose you want a pointer-to-member-function that points at Fred::f , Fred::g or Fred::h : class Fred {

Can we inherit member function in C++?

Inheritance is a mechanism of reusing and extending existing classes without modifying them, thus producing hierarchical relationships between them. In the main function, object obj accesses function A::f() through its data member B::x with the statement obj.


I have a need to be able to have a super class execute callbacks defined by a class that inherits from it. I am relatively new to C++ and from what I can tell it looks like the subject of member-function-pointers is a very murky area.

I have seen answers to questions and random blog posts that discuss all sorts of things, but I am not sure if any of them are specifically dealing with my question here.

Here is a simple chunk of code that illustrates what I am trying to do. The example might not make a lot of sense, but it accurately resembles the code I am trying to write.

class A {
    protected:
    void doSomething(void (A::*someCallback)(int a)) {
        (*this.*someCallback)(1234);
    }
};

class B : public A {
    public:
    void runDoIt() { doSomething(&B::doIt); }
    void runDoSomethingElse() { doSomething(&B::doSomethingElse); }
    protected:
    void doIt(int foo) {
        cout << "Do It! [" << foo << "]\n";
    }
    void doSomethingElse(int foo) {
        cout << "Do Something Else! [" << foo << "]\n";
    }
};

int main(int argc, char *argv[]) {
    B b;
    b.runDoIt();
    b.runDoSomethingElse();
}