compilatiion error for static member function defination outside class.

Jun 14, 2010 at 8:24am
Hi ,

I'm new to the c++, please can anyone explain can we define static member function outside the class, as myself trying gives compilation error.

please correct me if i've specified wrong syntax.


class A
{
static int count;
public :
A()
{
count ++;
}

static void A::countobjects (void)
{
cout<<"Number of objects="<<countobj<<endl;
}
};

int A:: count = 0;
main()
{
A test;
A::countobjects();
}

$g++ a.out

class.cpp:30: error: cannot declare member function âstatic void A::countobjects()â to have static linkage
Jun 14, 2010 at 10:11am
The code works fine for me, except that countobj is not declared anywhere.
Jun 14, 2010 at 10:35am
You should not use the class qualifier A:: in the declaration of your member function.

If you want to move the definition of your member function outside the class declaration then you add the class qualifier, but you only use the static keyword in the declaration (in the class) and not in the definition:

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
28
29
30
31
32
#include <iostream>

class A
{
	static int count;
public:
	A()
	{
		count++;
	}

	// Do  not add A:: qualifier here
	static void countobjects(); // no need for void parameter

};


// define static member data and functions here
// Note, do NOT use the static keyword, only in
// the declaration in the class
int A::count = 0;

void A::countobjects() // no need for void parameter
{
	std::cout << "Number of objects=" << count << std::endl;
}

int main()
{
	A test;
	A::countobjects();
}
Last edited on Jun 14, 2010 at 10:36am
Jun 14, 2010 at 12:48pm
Thanks galik,

i was using static prefix in definition part of static member function, removing it solved.

- santosh
Topic archived. No new replies allowed.