Click to See Complete Forum and Search --> : Should const value be initialised ?


ColdFire
December 31st, 2006, 09:00 PM
I read this
Just as you can create a constant of a built-in data type, you can also create a constant of a class. Always remember that the constant refers to a value that doesn't change and the constant value must be initialized with a known or already defined value. Here is an example:

using namespace System;

public value class CHouse
{
public:
__wchar_t TypeOfHome;
int Bedrooms;
double Bathrooms;
Byte Stories;
int YearBuilt;
double Value;
};

int main()
{
const CHouse singleFamily = { L'S', 5, 2.5, 3, 1962, 524885 };

Console::Write("Type of Home: ");
Console::WriteLine(singleFamily.TypeOfHome);
Console::Write("Number of Bedrooms: ");
Console::WriteLine(singleFamily.Bedrooms);
Console::Write("Number of Bathrooms: ");
Console::WriteLine(singleFamily.Bathrooms);
Console::Write("Number of Stories: ");
Console::WriteLine(singleFamily.Stories);
Console::Write("Year Built: ");
Console::WriteLine(singleFamily.YearBuilt);
Console::Write("Monetary Value: ");
Console::WriteLine(singleFamily.Value);

return 0;
}

I tried the modified code without initializing the const object. It still works without errors. Why so?

using namespace System;

public value class CHouse
{
public:
__wchar_t TypeOfHome;
int Bedrooms;
double Bathrooms;
Byte Stories;
int YearBuilt;
double Value;
};

int main()
{
const CHouse singleFamily;

Console::Write("Type of Home: ");
Console::WriteLine(singleFamily.TypeOfHome);
Console::Write("Number of Bedrooms: ");
Console::WriteLine(singleFamily.Bedrooms);
Console::Write("Number of Bathrooms: ");
Console::WriteLine(singleFamily.Bathrooms);
Console::Write("Number of Stories: ");
Console::WriteLine(singleFamily.Stories);
Console::Write("Year Built: ");
Console::WriteLine(singleFamily.YearBuilt);
Console::Write("Monetary Value: ");
Console::WriteLine(singleFamily.Value);

return 0;
}

INA_ctive
January 1st, 2007, 05:46 AM
yes, it is still compilable, but the const now contains garbage value from previous value contained in the memory and it is not changeable. thus, the const variable contains garbage and cannot be used

ColdFire
January 1st, 2007, 06:27 AM
All of them contain 0.

Zaccheus
January 2nd, 2007, 02:25 PM
Everything is always automatically default initialised to zero, so there is never any garbage to worry about.