scdmb
scdmb

Reputation: 15621

Definition of constant object of class

There is such code:

class MojaKlasa{
public:
};

int main()
{
  const MojaKlasa a;

  return 0;
}

Compiler error is:

error: uninitialized const ‘a’

However after modification of class MojaKlasa:

class MojaKlasa{
public:
  MojaKlasa(){}
};

it works all right. Default constructor should be defined automatically by C++ - why isn't it done in this case and default constructor must be explicitly defined?

Upvotes: 2

Views: 3379

Answers (3)

user784668
user784668

Reputation:

When declared as such, MojaKlasa is a POD type, so the compiler can't initialize it to any meaningful value automatically, just like it couldn't automatically initialize a const int to any meaningful value.

Note that you don't need an explicit default constructor to create constants of this type:

const MojaKlasa foo = {}; // works fine

Upvotes: 2

Mat
Mat

Reputation: 206729

Draft n3290 (C++0X) has this in §8.5/6:

To default-initialize an object of type T means:
— if T is a (possibly cv-qualified) class type (Clause 9), the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
— if T is an array type, each element is default-initialized;
— otherwise, no initialization is performed.
If a program calls for the default initialization of an object of a const-qualified type T, T shall be a class type with a user-provided default constructor.

So you actually need a user-defined constructor here, the compiler-generated one would not be sufficient.

BTW, clang++ has a great diagnostic for this:

$ clang++ -std=c++0x -pedantic -Wall t.cpp
t.cpp:7:19: error: default initialization of an object  of const type
                   'const MojaKlasa' requires a user-provided default constructor
  const MojaKlasa a;
                  ^
1 error generated.

For C++03, the wording is as follows (§8.5/9):

If no initializer is specified for an object, and the object is of (possibly cv-qualified) non-POD class type (or array thereof), the object shall be default-initialized; if the object is of const-qualified type, the underlying class type shall have a user-declared default constructor. Otherwise, if no initializer is specified for a non-static object, the object and its subobjects, if any, have an indeterminate initial value ; if the object or any of its subobjects are of const-qualified type, the program is ill-formed.

Which explains the why it is this way. You've got a POD type that you're not initializing, so its members have an "indeterminate" values. Since the object you declare is const, you can't assign to its fields, so you're left with a POD whose values you can't assign to, and you can't read from either (would be undefined behavior). Not very useful.

Upvotes: 7

bert-jan
bert-jan

Reputation: 968

The compiler might be confused because the size of a is zero! Try adding a dummy member to MojaKlasa.

Upvotes: -2

Related Questions