Home > Mobile >  returning pointer to a function inline without typedef
returning pointer to a function inline without typedef

Time:12-15

I'm running into syntax errors with C where I have to return a pointer to a function inline.

struct Note{}

Observer.hpp

class Observer {
    protected:
        void (*notify)(Note *note); // should this be *(*notify...)?
    public:
        void (*(*getNoteMethod)())(Note *note);
};

Observer.cpp

void (*Observer::getNoteMethod())(Note*) { //error: non-static data member defined out-of-line
    return this->notify;
}

I'm getting this error, error: non-static data member defined out-of-line

I'm new to C and attempting to define the return function signature correctly.

CodePudding user response:

The problem is the declaration syntax for the member function (which returns function pointer). Declare it as:

class Observer {
    protected:
        void (*notify)(Note *note);
    public:
        void (*getNoteMethod())(Note *note);
};

Better to declare the function pointer type in advance via using or typedef, which looks much clearer. E.g.

class Observer {
    using function_pointer_type = void(*)(Note*); // the function pointer type
    protected:
        function_pointer_type notify;             // the data member with function pointer type
    public:
        function_pointer_type getNoteMethod();    // the member function returns function pointer
};

// Out-of-class member function definition
Observer::function_pointer_type Observer::getNoteMethod() {
    return this->notify;
}
  • Related