How to implement static class member functions in *.cpp file?
Solution 1:
It is.
test.hpp:
class A {
public:
static int a(int i);
};
test.cpp:
#include <iostream>
#include "test.hpp"
int A::a(int i) {
return i + 2;
}
using namespace std;
int main() {
cout << A::a(4) << endl;
}
They're not always inline, no, but the compiler can make them.
Solution 2:
Try this:
header.hxx:
class CFoo
{
public:
static bool IsThisThingOn();
};
class.cxx:
#include "header.hxx"
bool CFoo::IsThisThingOn() // note: no static keyword here
{
return true;
}
Solution 3:
helper.hxx
class helper
{
public:
static void fn1 ()
{ /* defined in header itself */ }
/* fn2 defined in src file helper.cxx */
static void fn2();
};
helper.cxx
#include "helper.hxx"
void helper::fn2()
{
/* fn2 defined in helper.cxx */
/* do something */
}
A.cxx
#include "helper.hxx"
A::foo() {
helper::fn1();
helper::fn2();
}
To know more about how c++ handles static functions visit: Are static member functions in c++ copied in multiple translation units?
Solution 4:
In your header file say foo.h
class Foo{
public:
static void someFunction(params..);
// other stuff
}
In your implementation file say foo.cpp
#include "foo.h"
void Foo::someFunction(params..){
// Implementation of someFunction
}
Very Important
Just make sure you don't use the static keyword in your method signature when you are implementing the static function in your implementation file.
Good Luck
Solution 5:
Yes you can define static member functions in *.cpp file. If you define it in the header, compiler will by default treat it as inline. However, it does not mean separate copies of the static member function will exist in the executable. Please follow this post to learn more about this: Are static member functions in c++ copied in multiple translation units?