Is it possible to define a static function member as a inline member?

When it comes to static function members, is it required to make a prototype of the function and define the function with the scope operator? or is it possible to define a static INLINE member in a class?

See the program below to understand what i mean

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
#include <iostream>

using namespace std;

class Plants
{
    static int number_of_plants;

public:
    static void getNumber ()	// static inline member function
	{
	number_of_plants++;
	cout << number_of_plants;
	}

}object;


int main ()
{
   Plants::getNumber ();    // compiler says theres an error here


}
Last edited on
is it required to make a prototype of the function and define the function with the scope operator?


No.

or is it possible to define a static INLINE member in a class?


Yes.



Nothing is wrong with the function in the code you posted. The only error in the code that I see is that you are not instantiating your static "number_of_plants" member. If you do that it should work fine:

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

using namespace std;

class Plants
{
    static int number_of_plants;

public:
    static void getNumber ()
    {
        number_of_plants++;
        cout << number_of_plants;
    }

};

int Plants::number_of_plants = 0;  // <- instantiate it

int main ()
{
    Plants::getNumber ();
}
Last edited on
Thank you for your response.

One more question though, do I have to instantiate the static variable every time I want the value to change or returned?

When should I instantiate the static member?
You should instantiate it once, just like you would define a method of the class once - for a static integer like this, you can actually just add it into the class definition:
static int number_of_plants = 0;
This works with any type in C++11.

For other types, the initialization (just like Disch wrote as a example, see line 18) would generally be in the source file. If you want to change it any other time, you can just assign to it normally, e.g.:
Plants::number_of_plants = 123;
"When should I instantiate the static member?"

Always, unless you intend not to use it :D. You don't need to initialise it though if you just want the initial value to be zero.

int Plants::number_of_plants;

You can look at a static member variable as a global variable with class scope. For a "regular" global variable e.g. int number_of_plants;, definition and instantiation take place in the same line.
Topic archived. No new replies allowed.