Member functions with global scope

I have a class with a member function called factorial. I want that function to be available without an instance of the class being around (the class is initialized to eat up a lot of space, and initialization takes time). I am trying something like the code below, but it doesn't work. Does anyone have ideas?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<iostream>
#include<cmath>
#include<vector>

#include "prob_vector.cpp"



using namespace std;

typedef long double (*function_long_double) (long double);



int main(){
  function_long_double factorial = prob_vector::factorial;
  cout << factorial(3) << endl;
  return 0;
}


The error reads
1
2
wrapper.cpp: In function 'int main()':
wrapper.cpp:18: error: invalid use of non-static member function 'long double prob_vector::factorial(long double)'


Absolute beginner here, so please dumb down your comments :-)
The compiler gave you a good advice! Define your member-function as a static member-function of your class.
You could do it like this (No function pointer required!):

1
2
3
4
5
6
7
8
9
10
11
12
#include<iostream>

class prob_vector
{
public:
  static long double factorial(int i);
};

int main(){
  std::cout << prob_vector::factorial(3) << std::endl;
  return 0;
}
Last edited on
Doing what you suggested fixed the problem. Thanks.

Just so that I know for the future, what does defining a member function as static do?
It means that you can use the member function without defining the class. However if you need to save any of the data in private members of the class this won't work because by not defining an object of that class, you haven't allocated any space for those private members.

Static member functions are useful in cases like this:
1
2
3
4
5
6
class conversions
{
public:
    static double feet_to_meters(double feet) { return feet * 3.25; }
    static double meters_to_feet(double meters) { return meters / 3.25; }
}


Here I can use a selection of converting functions without declaring an object. A namespace would also work here too.

Last edited on
Got it. Thanks.
Topic archived. No new replies allowed.