strange behavior when const class objects involved with constructor?

Hi, all:
I come up with this problem when I was reading the replies to my previous post. I have the following simple code

1
2
3
4
5
6
7
8
class A {
};

int main()
{
	const A a; 
	return 0;
}


That is, I defined an class A and then try to define a const object. The compiler complains that a is uninitialized. Then I add an explicit default constructor into A, i.e.,

1
2
public:
  A() {} 


then everything is fine. So it seems that const object can not be initialized by synthesized default constructor. Another thing I feel wierd is about the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class A {
	public:
	A() {}
	void f() const {cout << i << endl;}
	private:
	int i;
};

int main()
{
	const A a; 
	a.f();
	return 0;
}


Here A has private member i, and the default constructor actually does anything. Still the definition of const object is fine, and a.f() just print a random value for i.

Anyone can give some explanation?


I wouldn't have thought that your first example would give a error because the class has no data
members.
However suppose you had this:
1
2
3
4
5
6
7
8
9
10
class A 
{
int x;
};

int main()
{
    const A a; 
    return 0;
}


You notice that the class has a data member, it has no programmer defined constructor(s)

When you try to create the constant variable const A a;, using the compiler suplied
default constructor, the compiler will not be happy -
because it would not know what values to give to the data member x.
You would need to give x a meaningful value at constrution time because you cannot change it afterwards.
Therefore, you need to supply your own constructor - the compiler is now happy because you have taken the responsibilty for constructing the objects.
1
2
3
4
5
6
7
8
class A {
};

int main()
{
	const A a; 
	return 0;
}
is supposed to compile regardless of the content of the 'class A' (Visual C++ emits (at least) a warning when 'class A' contains something)

mathwang2 wrote:
a.f() just print a random value for i.
since you did not initialze i it remains random
Topic archived. No new replies allowed.