Search code examples
c++function-pointersclass-method

C++ function method via function pointer


I'm trying to understand how function pointer works can't clarified why I get the following err.

#include <iostream>

using namespace std;
enum COLOR {RED,BLACK,WHITE};

class Car
{public:
 Car (COLOR c): color(c) { cout<<"Car's constructor..."<<endl; CarsNum++;}
 ~Car () {cout<<"Car's destructor..."<<endl; CarsNum--;}
 void GetColor () { cout<<"Color of the car is"<<color<<endl;}
 static int GetCarsNum () {cout<<"Static membet CarsNum="<<CarsNum<<endl; return 0;}
private:
COLOR color;
static int CarsNum;

};

int Car::CarsNum=0;

int main()
{
int (Car::*pfunc) () = NULL;
pfunc=&Car::GetCarsNum ();


 Car *ptr= new Car(RED);
 ptr->GetColor ();
 ptr->GetCarsNum ();
 delete ptr;
 ptr=0;
 Car::GetCarsNum();
    return 0;
}

Err msg:

main.cpp|23|error: lvalue required as unary '&' operand

Problem is with:

  pfunc=&Car::GetCarsNum ();

Any help would be greatly appreciated


Solution

  • No need for parentness:

    pfunc=&Car::GetCarsNum;
    

    and

    int (Car::*pfunc) () = NULL;
    

    Oh, UPDATE: you have static method: In this case GetCarsNum() is just a simple function:

    int (*pfunc) () = &Car::GetCarsNum;