Composite Classes with Base/Member Initialization List

 

File Date.h:

#ifndef DATE_H
#define DATE_H

class Date
{
public:
   Date() : month(1),day(1),year(2000) { }
   Date::Date(int mm,int dd,int yy) : month(mm),day(dd),
                                      year(yy) { }
   Date(const Date&);
   void setDate(int,int,int);
   void showDate();
private:
   int month;
   int day;
   int year;
};

#endif

File Date.C:

#include <iostream.h>
#include "Date.h"

//  copy constructor
Date::Date(const Date& old) : month(old.month),day(old.day),
                              year(old.year)
{ }

//  setDate sets the data members of the invoking object to the
//  values passed in the parms
void Date::setDate(int mo, int da, int yr)
{
	month = mo;
	day = da;
	year = yr;
}

//  print the invoking object in the format mm/dd/yyyy
void Date::showDate()
{
   cout << month << '/' << day << '/' << year;
}

File Person.h:

#ifndef PERSON_H
#define PERSON_H

#include "Date.h"
#include <string>

class Person
{
public:
   Person() { }
   Person(string nn,Date bd,int aa) : name(nn),birthday(bd)
                                      { age = aa; }
   Person(const Person&);
   void print();
private:
   string name;
   Date birthday;
   int age;
};

#endif

File Person.C:

#include "Person.h"
#include "Date.h"

// copy constructor
Person::Person(const Person& old) : name(old.name),
                                    birthday(old.birthday),
                                    age(old.age)
{ }

// print the invoking object
void Person::print()
{
   cout << "Name:     " << name << endl;
   cout << "Age:      " << age << endl;
   cout << "Birthday: ";
   birthday.showDate();
   cout << endl;
}

File main.C:

#include <iostream.h>
#include <string>
#include "Date.h"
#include "Person.h"

int main()
{
   string nn;
   int mm,dd,yy,age;
   cout << "Enter your name: ";
   getline(cin, nn);
   cout << "Enter your birthday (month day year): ";
   cin >> mm >> dd >> yy;
   Date birth(mm,dd,yy);
   cout << "Enter your age: ";
   cin >> age;

   cout << endl;
   Person you(nn,birth,age);
   you.print();
}

To Compile and Execute:

>g++ Date.C Person.C main.C
>a.out

Output:


Enter your name: Daniel Schatz-Miller
Enter your birthday (month day year): 4 23 1984
Enter your age: 21

Name:     Daniel Schatz-Miller
Age:      21
Birthday: 4/23/1984


Email Me | Office Hours | My Home Page | Department Home | MCC Home Page

© Copyright Emmi Schatz 2002