Composite Class Person

 

File Date.h:

#ifndef DATE_H
#define DATE_H

class Date
{
public:
   Date(int=1,int=1,int=2000);
   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"

//  default constructor if all parms are allowed to default; otherwise
//  it initializes data members to values passed
Date::Date(int mo, int da, int yr)
{
   month = mo;
   day = da;
   year = yr;
}

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

//  set the data members of the invoking object
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,Date,int);
   Person(const Person&);
   void print();
private:
   string name;
   Date birthday;
   int age;
};

#endif

File Person.C:

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

// default constructor; does no initialization
Person::Person()
{ }

// constructor to initialize all data members
Person::Person(string nn,Date bd,int aa)
{
   name = nn;
   birthday = bd;
   age = aa;
}

// 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