Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregate Initialization Safety in C++

Suppose I have the following struct:

struct sampleData
{
       int x;
       int y;
};

And when used, I want to initialize variables of sampleData type to a known state.

sampleData sample = { 1, 2 } 

Later, I decide that I need additional data stored in my sampleData struct, as follows:

struct sampleData
{
       int x;
       int y;
       int z;
};

It is my understanding that the two field initialization left over from my pre-z data structure is still a valid statement, and will be compiled., populating the missing fields with default values.

Is this understanding correct? I have been working recently in Ada, which also allows aggregate initialization, but which would flag a similar issue as a compilation error. Assuming that my assumptions about the C++ code above are correct, is there a language construct which would recognize missing initialization values as an error?

like image 695
Greg Avatar asked Jun 08 '11 20:06

Greg


People also ask

What is aggregate initialization in C++?

An aggregate is just what it sounds like: a bunch of things clumped together. This definition includes aggregates of mixed types, like structs and classes. An array is an aggregate of a single type. Initializing aggregates can be error-prone and tedious. C++ aggregate initialization makes it much safer.

What is designated initializer in C?

A designated initializer, or designator, points out a particular element to be initialized. A designator list is a comma-separated list of one or more designators. A designator list followed by an equal sign constitutes a designation.

Why do we use initialization?

Initialization is the process of locating and using the defined values for variable data that is used by a computer program. For example, an operating system or application program is installed with default or user-specified values that determine certain aspects of how the system or program is to function.

What is initialization value?

In computer programming, initialization (or initialisation) is the assignment of an initial value for a data object or variable. The manner in which initialization is performed depends on the programming language, as well as the type, storage class, etc., of an object to be initialized.


1 Answers

Initialising variables that way is only supported with Aggregate Classes.

If you add constructor(s) then then problem goes away, but you'll need to change the syntax a little and you lose the ability to store the struct in a union (among other things).

struct sampleData
{
    sampleData(int x, int y) : x(x), y(y) {}
    int x;
    int y;
};

sampleData sample( 1, 2 );

Adding z (and changing the constructor) will mark sample( 1, 2 ) as a compile error.

like image 174
Peter Alexander Avatar answered Oct 05 '22 09:10

Peter Alexander