Here is simple program. If I comment constructor, I get an error Just wanted to check what is the reason for this?
t.cc: In function 'int main(int, char**)':
t.cc:26: error: uninitialized const 'const_test'
#include <iostream>
using namespace std;
class TestPrint
{
public:
// TestPrint() {}
void Print()
{
std::cout << "TestPrint" << std::endl;
}
void Print() const
{
std::cout << "const TestPrint" << std::endl;
}
};
int main(int argc, char* argv[])
{
TestPrint normal_test;
normal_test.Print();
const TestPrint const_test;
const_test.Print();
}
It is indeed ill-formed. §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 nonstatic 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.
Emphasis mine. Any compiler that does not issue a diagnosis for your program is non-compliant (looking at you MSVC). A simpler test:
struct foo {};
int main()
{
const foo f;
}
The idea is simple: constants need to be initialized to something. If you have no user-defined constructor, you have no initialization.
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