I seem to have some misconceptions about how the static
keyword works in C++; specifically, I need to understand the problem with the following code:
#include <iostream>
struct A{
int a;
A(int ain) : a(ain) { }
A() : a(1) { }
static A getA()
{
return A(2);
}
};
struct B
{
static A a = A::getA();
};
int main() {
std::cout << B::a.a << std::endl;
}
Had static
worked as I expected it to, the above code sample would have printed 2
and exited normally - instead, I get the following compiler error message:
g++ -c -o syntax.o syntax.cpp
syntax.cpp:17:21: error: ‘A::getA()’ cannot appear in a constant-expression
static A a = A::getA();
^
syntax.cpp:17:26: error: a function call cannot appear in a constant-expression
static A a = A::getA();
^
syntax.cpp:17:26: error: invalid in-class initialization of static data member of non-integral type ‘A’
syntax.cpp:17:26: error: initializer invalid for static member with constructor
syntax.cpp:17:26: error: (an out of class initialization is required)
syntax.cpp:17:26: error: ‘B::a’ cannot be initialized by a non-constant expression when being declared
make: *** [syntax.o] Error 1
I read the error messages and I realize that there's something about static
that I haven't understood, but I find it hard to pinpoint what. It's probably because I've done a fair amount of work in languages like Java and C#, which also have the static
keyword but where it, apparently, works differently.
Will someone please explain to me why the above code is invalid?