#297 – Three Different Ways to Initialize the Contents of a struct

You must assign a value to each field in a struct before using it, but there are several different ways to do this.

The first way is to assign the values directly, after you declare a new struct variable.

            Point3D myPoint;
            myPoint.x = 34.0;
            myPoint.y = 25.0;
            myPoint.z = 36.0;

The second way to assign values to all of the fields is to invoke the parameterless constructor, by using the new operator.  Note that you always get the built-in parameterless constructor–you cannot declare your own parameterless constructor in a custom struct.

This built-in constructor will initialize all fields to their default values.

            Point3D myPoint = new Point3D();

The last way to assign values is to invoke a custom constructor, assuming that your constructor assigns values to the fields.

            Point3D myPoint = new Point3D(10.0, 20.0, 30.0);
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: