In C++, we don’t need to specify the static keyword in the declaration of the header and in the definition in the class.
It means that this keyword has to be added only in the header.
You probably know that using the static keyword means that the function is unique in program.
So if you add static in the .h and in the .cpp, you will have like two methods with the same name.
And the compiler won’t appreciate it.
Let’s take two examples, one not working and another yes.
We are going to implement 2 files:
- MyClass.h
- MyClass.cpp
The bad
MyClass.h
#ifndef MYCLASS_H_
#define MYCLASS_H_
class MyClass {
public:
MyClass();
virtual ~MyClass();
static void myMethod();
};
#endif /* MYCLASS_H_ */
MyClass.cpp
#include "MyClass.h"
MyClass::MyClass() {
}
MyClass::~MyClass() {
}
static void MyClass::myMethod() {
}
The good
MyClass.h
#ifndef MYCLASS_H_
#define MYCLASS_H_
class MyClass {
public:
MyClass();
virtual ~MyClass();
static void myMethod();
};
#endif /* MYCLASS_H_ */
MyClass.cpp
#include "MyClass.h"
MyClass::MyClass() {
}
MyClass::~MyClass() {
}
void MyClass::myMethod() {
}
Conclusion
A really annoying problem that you’ve just solved.
Great job.