Declaring Variables

Consider the following variable declarations.

int length; int area = 0; DayOfYear today;

Constructor Basics

Adding A Constructor

We can add a constructor to our DayOfYear class.

class DayOfYear { public: // Constructor DayOfYear (int initialMonth, int initialDay); void Input( ); void Output( ); private: int m_month; int m_day; };

Constructor Syntax

Implementing a Constructor

The definition of a constructor is given in the same way as any other member function.

In the implementation file:

DayOfYear::DayOfYear(int initialMonth, int initialDay) { m_month = initialMonth; m_day = initialDay; }

Note the lack of return type.

Member Initialization List

An alternative way of defining constructors is also possible, sometimes necessary and actually preferred.

DayOfYear::DayOfYear(int initialMonth, int initialDay) :m_month( initialMonth ), m_day( initialDay ) { // no code }

The body of this style of constructor need not be empty, but if left empty, good programming practice requires an explicit comment.

Overloaded constructors

Since a constructor is a member function, a constructor can be (and often is) overloaded. Consider this new version of the DayOfYear class.

class DayOfYear { public: // specify the month and day as above DayOfYear (int initialMonth, int initialDay); // initialize to first (day=1) of the month DayOfYear (int initialMonth); // initialize to January 1 DayOfYear ( ); ... };

Invoking Overloaded Constructors

We can now create DayOfYear objects in a variety of ways

DayOfYear christmas( 12, 25 ); DayOfYear aprilFools ( 4 ); // This declaration uses the default constructor. DayOfYear jan1st; // but NOT like this! DayOfYear today( );

Constructors with Default Arguments

class DayOfYear { public: // this constructor can be invoked in three ways // and is also the default constructor DayOfYear (int initialMonth = 1, int initialDay = 1); void Input( ); void Output( ); private: int m_month; int m_day; };

Constructors with Default Arguments

Each of these declarations invokes the one and only constructor for the new DayOfYearClass:

// month = 1 and day = 1 via default parameters DayOfYear someDay; // explicit month = 3; day = 1 by default DayOfYear march1st( 3 ); // explicit month and day DayOfYear july4th( 7, 4 );

Default Constructors

Checking Validity