Instantiating const object with implicitly defined default constructor

May 18, 2010 at 6:58pm
I seem to get a compile error with the below code using g++ 3.2.3:

g++ test.cpp  
test.cpp: In function `int main()':
test.cpp:30: uninitialized const `cc


However, if I remove the comments around the default constructor (which should be the same as the one generated by the compiler, afaik), the code compiles and works as expected. Anyone know why this might be?

Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>

using std::cout;
using std::endl;

class myClass
{
public:
	/*myClass()
	{
	
	}*/
	
	void foo() 
	{
		cout << "foo" << endl;
	}

	void foo() const
	{
		cout << "foo - const - fml" << endl;
	}
};

int main()
{
	myClass c;	
	c.foo();
	
	const myClass cc;
	cc.foo();
	
	return 0;
}


Thanks!
May 18, 2010 at 7:35pm
[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 an object, the object and
its subobjects, if any, have an indeterminate initial value 90) ; if the
object or any of its subobjects are of const-qualified type, the program
is ill-formed.

from http://bytes.com/topic/c/answers/140387-uninitialized-constant-objects

But never seen this before
May 18, 2010 at 7:57pm
3.2.3 is old!

$ g++ --version
g++ (GCC) 3.2.3
Copyright (C) 2002 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

$


You must work where I work...
Last edited on May 18, 2010 at 7:59pm
May 18, 2010 at 8:25pm
@Rollie;
Hi,
Rule for constant >> because we cannot subsequently change the value of an object declared to be const, we must initialize it when it is defined.

myClass doesn't have any default constructor to initialize a variable. So cc is uninitialized which is error in the case of constant variable.

Thanx
May 18, 2010 at 8:30pm
Ah hah, I see! Thanks for the ref RedX.

moorecm - entirely possible :)
Topic archived. No new replies allowed.