-1
#include <iostream>

class virtualClass{
public:
    virtual int a() = 0;
};

class UnknownImplementation : public virtualClass{
public:
    int a() override { return 1;}
};

class myFramework {
public:
    int c(int (virtualClass::*implementedFunc)(void)){
        implementedFunc();
        return 2;
    }
};

int main(){
    //some user implements the virtual class and calls myFramework function
    myFramework* mfp = new myFramework();
    std::cout << mfp->c(&(UnknownImplementation::a)) << std::endl;
}

Hi, I am working on a framework that is supposed call an implemented virtual function and use it. It is similar to the code above. The compiling errors I get are:

testVirtual.cpp: In member function ‘int myFramework::c(int (virtualClass::)())’: testVirtual.cpp:16:19: error: must use ‘.’ or ‘->’ to call pointer-to-member function in ‘implementedFunc (...)’, e.g. ‘(... -> implementedFunc) (...)’ implementedFunc(); ^ testVirtual.cpp: In function ‘int main()’: testVirtual.cpp:24:47: error: invalid use of non-static member function ‘virtual int UnknownImplementation::a()’ std::cout << mfp->c(&(UnknownImplementation::a)) << std::endl;

How do I fix these problems? Thanks in advance!

passing an instance of the implemented class and calling the function worked.

Maya Sela
  • 29
  • 5
  • Possible duplicate of [Function pointer to member function](https://stackoverflow.com/questions/2402579/function-pointer-to-member-function) – Algirdas Preidžius Jun 04 '18 at 08:45
  • 2
    Better to pass the object of `UnknownImplementation` and call appropriate function of `virtualClass` inside `myFramework::c`. Since every implementation of `virtualClass` would define the functions which could be called from within `myFramework::c`. This is called command pattern. – sameerkn Jun 04 '18 at 08:45
  • yeah that worked, thanks – Maya Sela Jun 04 '18 at 08:58

1 Answers1

1

To build on sameerkn's comment, this code should be:

#include <iostream>

class virtualClass{
public:
    virtual int a() = 0;
};

class mySubclass : public virtualClass{
public:
    int a() override { return 1;}
};

int main(){
    mySubclass * x= new mySubclass ();

    // ...

    std::cout << x->a () << std::endl;
}

The point here is that you can pass objects (or pointers) of type virtualClass around - even though they might actually be mySubclass objects in real life - and still wind up in the right implementation of a(). myFramework is entirely unnecessary.

That's what virtual methods are for - consumers of virtualClass don't need to know anything about classes that might - now or in the future - be derived from it, and if I have read your question correctly, this is what you want.

Paul Sanders
  • 24,133
  • 4
  • 26
  • 48