Reputation: 141
I have a program where a class T has a static function.
static void T::func()
{
m_i=10;
cout<<m_i<<endl;
}
When I try to add static in function definition, the compiler throws error error: cannot declare member function ‘static void T::func()’ to have static linkage. Why is it not accepting static keyword in definition?
Upvotes: 2
Views: 308
Reputation: 409356
The problem is that the keyword static
means different things depending on context.
When you declare a member function to be static, like in
class T
{
...
static void func();
...
};
Then the static
keyword means that func
is a class function, it's not bound to a specific object.
When you define the function in a source file, like
static void T::func() { ... }
Then you set the function linkage which is different from using static
in a declaration inside a class. What static
does when defining the function is to say that the function is only available in the current translation unit, and that contradicts the declaration that the function is available for all who knows the class.
It's simply not possible to make a member function (declared static
or not) have static linkage.
If you want to "hide" the member function from others, so it can't be called, why not simply make it a private
member function? You could also use things like the pimpl idiom or just not have it as a member function to begin with, in which case you can declare it to have static
linkage.
Upvotes: 9
Reputation: 1064
You don't need static in implementation, only in definition.
T.h
class T
{
int m_i;
static int s_i;
public:
static void func();
};
T.cpp
int T:s_i = 0;
void T::func()
{
// Access only static and local variables
// I.e this is not allowed
m_i=10;
// This is allowed
s_i=10;
}
Upvotes: 2