Conflating a couple of dissimilar issues here
static B test2; //error
fails because B
's constructor requires arguments that haven't been provided and is private
so it can't be accessed outside the class. Correct those and B
is good to go.
class B {
public: // added for outside access to constructor
B(int a) {
printf("%d\n", a);
}
};
static B test2{1}; // added arguments
As for A
, a static
member is not part of a class instance, so the compiler doesn't need it to be complete. It doesn't take up any space, and at this point it's not being used for anything. It's just a declaration. You can declare all sorts of stuff without the compiler getting upset (so long as the declaration's syntax is good). You run into trouble when you try to use something without a definition.
Example:
void testfunc(const A &)
{
}
int main(){
testfunc(A::test);
}
fails at the linker because A::test
was never defined. If you try to correct that with
class A {
public:
static A test{1}; // let's try to define it inline!
int a;
int b;
int c;
A(int d, int e) : a(d), b(e), c(15) {
}
A(int d) :A(d, 10) {
printf("%d %d %d", a, b, c);
}
};
now the compiler cares enough to report that the class is incomplete. We'll have to move the definition outside the class where it is complete
class A {
public:
static A test; //declared
int a;
int b;
int c;
A(int d, int e) : a(d), b(e), c(15) {
}
A(int d) :A(d, 10) {
printf("%d %d %d", a, b, c);
}
};
A A::test{1}; // defined
Now
void testfunc(const A &)
{
}
int main(){
testfunc(A::test);
}
will compile and link.
Documentation on the care and feeding of static
members.