2

Possible Duplicate:
declaring a const instance of a class
Why does C++ require a user-provided default constructor to default-construct a const object?

My program like this:

class c
{
};

int main()
{
    const c a;

    return 0;
}

when I compile it using g++, it prompt:

main.cpp:10:7: note: ‘const class c’ has no user-provided default constructor

Why, this is just an empty class and do not do anything, why I have to provide a user-provided constructor.

2
  • 3
    See stackoverflow.com/questions/5934457/… and stackoverflow.com/questions/4674332/… Commented Mar 9, 2012 at 10:11
  • 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 an 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. $8.5/9 Commented Mar 9, 2012 at 10:14

2 Answers 2

1

Because the language rules say so.

The constant must have its value set in the definition, as it cannot be assigned a value later. If you don't explicitly provide a value, the type must have a default constructor.

Sign up to request clarification or add additional context in comments.

Comments

1

You don't have to. It's just a note, not even a warning. The rationale is that the class can't do anything useful, which is rarely intended. GCC is just checking to see if you overlooked something.

10 Comments

GCC is wrong. This should be a compile error (and in fact my version of GCC (llvm-g++-4.2) does issue an error).
clang++ doesn't issue any error which is wrong. My g++4.6 issues error: uninitialized const ‘a’ [-fpermissive]
@Prasoon Which version of clang++ are you using? My version (3.0) correctly treats this as an error. Unfortunately, g++-4.6.2 doesn’t. Which is weird, since your GCC 4.6 does.
@KonradRudolph: It's a language extension; it doesn't impact conforming code. There is a diagnostic, as required. Overall, I wouldn't call it wrong.
@MSalters I’m pretty sure that the program is ill-formed and it’s thus wrong. Unfortunately I cannot find the passage cited by Prasoon but either way, you end up with an uninitialised const object and that should not be legal. That said, C++ also allows other uninitialised PODs to exist and that too should actually be illegal since otherwise you’ll be forced to call operator = on an uninitialised value. EDIT and if it’s a language extension then GCC is still wrong since some compiler versions don’t issue any diagnostic, not even when compiled with -pedantic.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.