Consider the followin simple class definition –
// file A.h
#include <iostream>
class A {
public:
static int f();
static const int aa;
};
// file A.cpp
#include "a.h"
using namespace std;
const int A::aa = 10;
int A::f() {
return A::aa;
}
And this is my main file –
// main.cpp file
#include "a.h"
#include "b.h"
using namespace std;
const int A::aa = 100;
int A::f();
int main() {
cout << A::aa << "\n";
cout << A::f() << "\n";
}
When I try to compile main.cpp, the compiler complains that the declaration of A::f() in main.cpp outside the class is a declaration, not a definition. Why is this? I do not intend to define A::f() in main.cpp. It is defined in A.cpp and the linker should link the declaration of A::f() in main.cpp with its definition in A.cpp. So I do not understand why am I getting this error. Note this is a compilation error.
C++11 standard
§9.3 [class.mftc] p3:Aside from that, you’ll get a linker error due to multiple definitions of
A::aa, but it seems that you expected that, judging from your last sentence.