Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define static const member?

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.

  • Is there another way to define this static const member variable?
  • Is this a limitation of gcc-4.4?
  • Is there a workaround?
like image 813
Didier Trosset Avatar asked May 31 '12 13:05

Didier Trosset


People also ask

How do you define a static member?

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.

Can static members be const?

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 = .

How do you initialize a const member?

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.

How do you initialize a static member?

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.


2 Answers

Say:

Test::Dummy const Test::dummy = { };
like image 165
Kerrek SB Avatar answered Oct 22 '22 01:10

Kerrek SB


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.

like image 36
Jonathan Wakely Avatar answered Oct 22 '22 01:10

Jonathan Wakely