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.
So you'd use static (or, alternatively, an unnamed namespace) when writing a function that's only intended for use within this unit; the internal linkage means that other units can define different functions with the same name without causing naming conflicts.
According to Static data members on the IBM C++ knowledge center: The declaration of a static data member in the member list of a class is not a definition. You must define the static member outside of the class declaration, in namespace scope.
A static method without a class does not make any sense at all. The static keywords signals that this method is identical for all instances of the class. This enables you to call it.. well.. statically on the class itself instead of on one of its instances.
Defining a member function outside a class allows to separate the interface and its realization.
C++11 standard §9.3 [class.mftc] p3
:
[...] Except for member function definitions that appear outside of a class definition, and except for explicit specializations of member functions of class templates and member function templates (14.7) appearing outside of the class definition, a member function shall not be redeclared.
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.
The class and it's members are already defined, you just have to include the file into your main (which you've done). You do not need to declare or redefine it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With