Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize a static const non-integral data member of a class

Consider the sample program below:

#include <iostream>

using namespace std;

class test
{
   public:
      static const float data;
};

float const test::data = 10;   // Line1


int main()
{
   cout << test::data;
   cout << "\n";

   return 0;
}

Please note the comment Line1 in the sample code.

Questions:

  1. Is Line1 doing the initialization of the date member data?
  2. Is Line1 the only way to initialize a static const non-integral data member?
like image 300
nitin_cherian Avatar asked Dec 13 '11 14:12

nitin_cherian


1 Answers

Is Line1 doing the initialization of the date member data?

It certainly is, as well as providing the definition of the object. Note that this can only be done in a single translation unit, so if the class definition is in a header file, then this should be in a source file.

Is Line1 the only way to initialize a static const non-integral data member?

In C++03 it was. In C++11, any static member of const literal type can have an initialiser in the class definition. You still need a definition of the member if it's "odr-used" (roughly speaking, if you do anything that needs its address, not just its value). In this case, the definition again needs to be in a single translation unit, and must not have an initialiser (since there's already one in the class definition).

like image 127
Mike Seymour Avatar answered Oct 06 '22 05:10

Mike Seymour