Reputation: 845
I have a class Tester, which I decided to declare static as a member of a class Foo,
class Tester {
public:
bool test(const Data &d);
};
class Foo {
static Tester tester;
};
But when I call tester.test(data) from an instance of Foo, the program compiles fine, but does not respond after the call. When I make Tester::test static,
class Tester {
public:
static bool test(const data &d);
};
Then it works. Why is this? It would seam that I should be able to declare a static class and use it's non static members, for example, if I had a static vector. I'm using gcc 4.7 to compile.
Upvotes: 0
Views: 72
Reputation: 20523
I believe you get a linker error (right?). This is because you fail to give the definition of Foo::tester
. (You're only providing its declaration.)
In Foo
's .cpp
file add this line:
Tester Foo::tester;
This is the definition of Foo::tester
and fixes the linking issue.
Update Here is a complete example:
#include <iostream>
class Data {};
class Tester {
public:
bool test(const Data &) { std::cout << "Yes\n"; return true; }
};
class Foo {
static Tester tester;
public:
Foo() {
Data data;
tester.test(data);
}
};
Tester Foo::tester;
int main() {
Foo f;
}
It compiles, it links, it runs and it ouputs Yes
.
Update 2 After reflection on Ben Voigt's comment.
If you remove the definition of Foo::tester
then the code doesn't link. If you subsequently make Tester::test
static (as the OP said) then it links again and runs as expected.
On reflection, it actually makes sense. If tester
is not defined, you can't call a (non-static) method on it. However, if the method is static then you don't need an object, you only need its type to make the call. When the compiler sees the call tester.test(data);
then (I guess) it only considers the type of tester
(provided by the declaration) and then the code works.
Upvotes: 2