-1

I found this question here but now I want to extend it. so I have the following class in one file and it works correctly:

typedef int (*fptr)();

int f1() {
    return 1;
}

int f2() {
   return 2;
}




fptr f( char c ) {
    if ( c == '1' ) {
        return f1;
    }
    else {
        return f2;
    }
}

But when I want to move the functions in another file and make a factory out of them, I get an error that I cannot understand.

it would be like this:

Header:

public class Factories{
   public:
     int f1();
     int f2();
}

CPPFile:

int f1() {
    return 1;
}

int f2() {
   return 2;
}

Header:

public class FactoryClass{
   public:
     fptr f( char c );
}

CPPFile:

typedef int (*fptr)();
fptr f( char c ) {
    if ( c == '1' ) {
        return Factories::f1;
    }
    else {
        return Factories::f2;
    }
}

Here in the returns of this FactoryClass Function I get the error "return value type does not match the function type". Any Ideas would be appreciated.

Afshinzkh
  • 111
  • 1
  • 14
  • In C++ you can simply overload a pure virtual function which means you don't need a function pointer. – SPlatten Apr 13 '16 at 12:14
  • typedef int (*fptr)(); is not a pointer to the member function of the Factories class, that would be **typedef int (Factories::*fptr)();** – Biruk Abebe Apr 13 '16 at 12:16

3 Answers3

2

Factories::f1 is not a normal function, it is a member function. Since it is a member function it needs to take a pointer to the object that called it so it can affect that instance. This means the type of a member function includes what type of object it is called from so a pointer to f1 actually has the type

int (Factories::*)()

You will either have to make fptr

typedef int (Factories::*fptr)();

or make the functions static so they act like regular functions.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
1

the member functions Facotires::f1 you are returning just have the wrong signature. If possible, make them (f1 and f2) static. If not, bind the respective class instance (using boost::bind or std::bind)

lipp
  • 5,586
  • 1
  • 21
  • 32
1

The function type changed when you put them in a class. The new type should be typedef int (Factories::*fptr)();

C++: Calling member function via pointer

Community
  • 1
  • 1
Kyle A
  • 928
  • 7
  • 17