Class Example: Overloaded Constructors

#include <iostream.h>
#include <string.h>
/********************************************************
 File: class4.C
 Instantiate a date class, initialize two date objects,
 and print them. The initialization is done using
 overloaded constructors
*********************************************************/

class date {
     char label[100];
     int day;
     int month;
     int year;
public:
     date();
     date(char * , int , int , int );
     void print();
};

date::date()
{
	cout << "Calling default constructor..." << endl;
        strcpy(label, "Yesterday");
	day = 0;
	month = 0;
	year = 0;
}

date::date(char * l, int d, int m, int y)
{
     cout << "Calling parameterized constructor..." << endl;
     strcpy(label, l);
     day   = d;
     month = m;
     year  = y;
}

void date::print()
{
     cout << "Oject: " << label << endl;
     cout << "The date stored in this object is:" << endl;
     cout << "Day: " << day << endl;
     cout << "Month: " << month << endl;
     cout << "Year: " << year << endl;
}

typedef date Date;
typedef char String[100];

int main()
{
     int day, month, year;
     String curr_day = "Today";

     cout << "Enter today's date in DD MM YYYY format: ";
     cin >> day >> month >> year;

     Date today(curr_day, day, month, year);
     today.print();
    
     Date yesterday;
     yesterday.print();

     exit(0);

}

Output:

Enter today's date in DD MM YYYY format: 14 4 1997
Calling parameterized constructor...
Oject: Today
The date stored in this object is:
Day: 14
Month: 4
Year: 1997
Calling default constructor...
Oject: Yesterday
The date stored in this object is:
Day: 0
Month: 0
Year: 0



Back to Previous Page

Document:
Local Date:
Last Modified On: