My Test
class has a const
static
member of a subtype. I usually define this const
static
member as follows.
class Test
{
public:
class Dummy {};
private:
static Dummy const dummy;
};
Test::Dummy const Test::dummy; // ERROR HERE
int main()
{
return 0;
}
When compiling this source with gcc-4.6, it gives no error and compiles correctly.
When compiling this same source with gcc-4.4, it gives the following error:
error: uninitialized const ‘Test::dummy’
on the marked line.
What Does Static Members Mean? Static members are data members (variables) or methods that belong to a static or a non static class itself, rather than to objects of the class. Static members always remain the same, regardless of where and how they are used.
A static const data member must be initialized globally like any other static data member. In addition, since it is a constant, its value cannot later be changed. For example: const float Order::tax_rate = .
To initialize the const value using constructor, we have to use the initialize list. This initializer list is used to initialize the data member of a class. The list of members, that will be initialized, will be present after the constructor after colon. members will be separated using comma.
We can put static members (Functions or Variables) in C++ classes. For the static variables, we have to initialize them after defining the class. To initialize we have to use the class name then scope resolution operator (::), then the variable name. Now we can assign some value.
Say:
Test::Dummy const Test::dummy = { };
See http://gcc.gnu.org/wiki/VerboseDiagnostics#uninitialized_const (which gives the relevant reference to the standard) and also the GCC 4.6 release notes which say
In 4.6.0 and 4.6.1 G++ no longer allows objects of const-qualified type to be default initialized unless the type has a user-declared default constructor. In 4.6.2 G++ implements the proposed resolution of DR 253, so default initialization is allowed if it initializes all subobjects. Code that fails to compile can be fixed by providing an initializer e.g.
struct A { A(); };
struct B : A { int i; };
const B b = B();
Use -fpermissive to allow the old, non-conforming behaviour.
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