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);
};
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 .
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.
'this' pointer is not available in static member functions as static member functions can be called without any object (with class name).
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.
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++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With