Home > Mobile >  Why C does allow in-class definition?
Why C does allow in-class definition?

Time:10-06

Does in-class definition break the ODR rule?

Bjarne Stroustrup's explanation states this:

A class is typically declared in a header file and a header file is typically included into many translation units. However, to avoid complicated linker rules, C requires that every object has a unique definition. That rule would be broken if C allowed in-class definition of entities that needed to be stored in memory as objects.

class foo 
{
    float f = 1.1f;
    int i = 1;
    string s = "foo";
    long long ll = 44ll;
};

Does that is the actual definition of the members? Does this break ODR rule? and if not, what're the advantages of doing this over initialization through constructors?

CodePudding user response:

Does in-class definition break the ODR rule?

What you demonstrate is not "definition". It is default member initialiser. This default initialiser will be used if one is not provided for the non-static data member when initialising an instance of the class.

The example does not violate ODR.

Technically, the standard doesn't mention anywhere how non-static data members could even be defined. They however seem to not be excluded from being "odr-used" which may be a defect in the wording of the standard. The need for definition doesn't really apply to sub-objects.

CodePudding user response:

In class initialization helps us set the default state of a member(which in turn let us set the default state of the object as a whole). For example, if you want that any object of a given class should have a default value(state) then you should use in-class initialization.

There is also one more reason in-class initialization is used. If you don't provide the in-class initializers for built-in type then they will have garbage value. That is, we cannot say anything about that data member's value, which is not what we want.

This is why it is always recommended that you should initialize non-static built in type data members.

  • Related