|
ex4-9.cpp - Example 4-9 Constructor/Destructor - Person and People classes |
// File: ex4-9.cpp
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class Person
{
private:
char* name;
public:
Person(const char *); // constructor
~Person();
void print(void) const; // display Person's name
};
Person::Person(const char* n)
{
name = new char[strlen(n)+1];
if (name == NULL)
{
cerr << "Insufficent memory to store " << n << endl;
exit(1);
}
strcpy(name,n);
}
Person::~Person()
{
cout << "Person destructor call for " << name << endl;
delete [] name;
}
void Person::print(void) const
{
cout << name << endl;
return;
}
class People
{
private:
Person** array;
int Person_index; // Person index
int Max_People; // number of People in array
public:
People(int);
~People();
void addPerson(void);
void print(void) const;
};
People::People(int nope)
{
Max_People = nope;
array = new Person*[Max_People];
Person_index = 0;
}
People::~People()
{
cout << "\nPeople destructor called" << endl;
for (int i = 0; i < Max_People; i++)
{
cout << "deleting pointer to Person[" << i << "]\n";
delete array[i];
}
delete [] array;
}
void People::addPerson(void)
{
char temp[20];
cout<<"Enter the Persons name => ";
cin >> temp;
array[Person_index++] = new Person(temp);
return;
}
void People::print(void) const
{
cout << "\nHere's the People:\n";
for (int i = 0; i < Person_index; i++) array[i]->print();
return;
}
int main (void)
{
cout << "How many friends do you have? ";
int no_friends;
cin >> no_friends;
People friends(no_friends);
for (int i = 0; i < no_friends; i++) friends.addPerson();
friends.print();
return 0;
}
CIS27: Programming in C++ Instructor: Joe Bentley