Search code examples
c++function-pointers

Member Function Pointer Giving multiple errors


I have a member function pointer inside of my MethodPtr class. That's public and is declared like this:

void (Method::*func)() = nullptr;

It's giving me multiple errors and I'm unsure why. These errors are

'func': unknown override specifier

'Method': is not a class or namespace name

'methodptr': unkown override specifier

missing type specifier

syntax error: ")"

syntax error: missing ')' before identifier 'func'

unexpected token(s) preceding ';'

These errors are shown in the error list and show duplicates. Here's my code:

Method.h

#pragma once
#include "Methodptr.h"
#include <iostream>

class Method {
public:
    Method();
    void doSomething();
    MethodPtr methodptr;
};

Method.cpp

#include "Method.h"

Method::Method() { 
        //methodptr.func = &Method::doSomething;
}

void Method::doSomething() {
    std::cout << "Did something!" << std::endl;
}

The program crashes with the constructor expression commented out.

MethodPtr.h

#pragma once
#include "Method.h"

class MethodPtr {
public:
    void (Method::* func)() = nullptr;
};

Main.cpp

#include <iostream>
#include <fstream>
#include "Method.h"

int main() {
    Method method;
    //method.doSomething();
}

At first, I didn't know that member function pointers were a thing. So, I fixed that, and created a separate project to test it. I've continued to get this error since.

I don't want to use lambdas or std::function, unless there is no other way.

Currently, I'm just trying to figure out what I'm doing wrong here. I did get std::function to work when I used std::bind() and std::placeholder along with it.


Solution

  • You need to uncomment the line in the Method constructor or use the member initializer list to initialize methodptr:

    Method::Method() : methodptr{&Method::doSomething} {}
    

    and you also need to actually use the member function pointer.

    It could look like this:

    #include <iostream>
    
    class Method;           // forward declaration
    
    class MethodPtr {
    public:
        void (Method::*func)() = nullptr;
    };
    
    class Method {
    public:
        Method();
        void doSomething();
        void call();             // will use methodptr
        MethodPtr methodptr;
    };
    
    Method::Method() : methodptr{&Method::doSomething} {}
    
    void Method::call() {
        // dereferencing the function pointer to call it on `this`:
        (this->*methodptr.func)();
    }
    
    void Method::doSomething() {
        std::cout << "Did something!" << std::endl;
    }
    
    int main() {
        Method method;
        method.call();
    }
    

    Demo