views:

68

answers:

2

I am learning C++. Just curious, can only static and constant varibles be assigned a value from within the class declaration? Is this mainly why when you assign values to normal members, they have a special way doing it

void myClass::Init() : member1(0), member2(1)
{
}
+5  A: 

This looks like it is supposed to be a constructor; if it is, it should have no return type, and it needs to have the same name as the class, e.g.,

myClass::myClass()
    : member1(0), member2(1)
{

}

Only a constructor can have an initializer list; you can't delegate that type of initialization to an Init function.

Any nonstatic members can be initialized in the constructor initializer list. All const and reference members must be initialized in the constructor initializer list.

All things being equal, you should generally prefer to initialize all members in the constructor initializer list, rather than in the body of the constructor (sometimes it isn't possible or it's clumsy to use the initializer list, in which case, you shouldn't use it, obviously).

James McNellis
ok, that makes sense. But I've received errors previously stating that only static const members can be declared within a class. Does this mean that only static and constant members can be assigned a value from within the class declaration, in oppose to the intializer list or the constructor body.
numerical25
Only static integral members can be initialized within the class declaration. Any non-integral members must be initialized externally from the class declaration. (i.e. you can't initialize a static float in the declaration, but you could an int, short, char or bool).
Nathan Ernst
A: 

Static class members don't belong to any particular object. A static member is shared between all objects of that class. Therefore, you don't initialize them in a constructor - that would re-initialize them far too often, for instance.

Now there is the question why only static const class members can be initialized in the class itself. The reason is that the class is most likely in a header, and that header is included in multiple translation units. This causes a problem for the compiler. In which translation unit (ie. in which object file) should it put the actual initialization? But for simple consts, it doesn't matter. int const TWO = 2; doesn't need an actual initialization in a translation unit, the compiler just remembers it.

MSalters