static functions

I have a question about static functions. I did some googling and just want to verify it. Would it be correct to understand that a static function in c allows the function to only be seen by other functions in the same file. In c++ a static function in a class can be called without an instance of that class.

test example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <limits>

using std::cout;	using std::endl;
using std::cin;		using std::numeric_limits;
using std::streamsize;


class test
{
public:
	test() { cout << "constructor called" << endl; }

	static int funkyfunction(int a, int b)
	{ return (a + b);}
};

int main(int argc, char *argv[])
{
        // no class instance
	// test static function and make sure constructor wasnt called
	cout << test::funkyfunction(6,7);

	cout << endl;
	cout << "Press ENTER to continue...";
	cin.ignore(numeric_limits<streamsize>::max(), '\n' );
}


If this is correct can anyone show a real world example where a static function would be useful.
static has multiple meanings in C++, two of which you listed above.

Line 26 above is an example of a static function declared inside a class (max).

It is generally used where the function is logically related to the class, but the function does not need access to any data members of the class.
ok. oh I never noticed that about line 26. it does look like one. ok. all in all pretty straight forward on this. Thanks jsmith for taking the time to look.
Last edited on
Topic archived. No new replies allowed.