Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Static member pointer to function - how to initialize it?

I have a static pointer to function like the following in my class, but I'm not sure how to instantiate it:

class Foo{ 
 private:   
    static double (*my_ptr_fun)(double,double);                               
};
like image 712
user1195321 Avatar asked Feb 07 '12 17:02

user1195321


People also ask

How do you initialize a pointer to a function?

You need to initialize a pointer by assigning it a valid address. This is normally done via the address-of operator ( & ). The address-of operator ( & ) operates on a variable, and returns the address of the variable. For example, if number is an int variable, &number returns the address of the variable number .

How do you initialize a static member?

We can put static members (Functions or Variables) in C++ classes. For the static variables, we have to initialize them after defining the class. To initialize we have to use the class name then scope resolution operator (::), then the variable name. Now we can assign some value.

Can we use this pointer in static member function?

'this' pointer is not available in static member functions as static member functions can be called without any object (with class name).

How do you create a static member function?

Static Member Functions in C++ To create a static member function we need to use the static keyword while declaring the function. Since static member variables are class properties and not object properties, to access them we need to use the class name instead of the object name.


1 Answers

The same way you would initialize every other static member object in C++03:

class Foo{ 
 private:   
    static double (*my_ptr_fun)(double,double);                               
};

double bar(double, double);

double (*Foo::my_ptr_fun)(double,double) = &bar;

Whatever you would need a static function pointer for anyway.

This is called initialization. instantiation means something different in C++.

like image 53
pmr Avatar answered Oct 30 '22 17:10

pmr