Previous Section  < Free Open Study >  Next Section

Example Code for Leak #2


#include <iostream.h> 

class Melon {

 char* variety;

public:

 Melon(char* var);

 ~Melon();

 void print();



};



Melon::Melon(char* var)

{

 variety = new char[strlen(var)+1];

 strcpy(variety, var);

}



Melon::~Melon()

{

 delete variety;

}



void

Melon::print()

{

 cout << ''I'm a '' << variety << ''Melon\n'';

}

class Meal {

 char* restaurant;

 Melon* m;

public:

 Meal(char* var, char* res);

 ~Meal();

 void print ();

};



Meal::Meal(char* var, char* res)

{

 m = new Melon(var);

 restaurant = new char[strlen(res)+1];

 strcpy(restaurant, res);

}



// Oops! Forgot to delete the contained Melon.

// This would not be necessary if Melon were a

// contained object as opposed to a pointer to an

// object.

Meal::~Meal()

{

 delete restaurant;

}

// The correct destructor would be defined

//as follows:

/* Meal::~Meal()

{

 delete restaurant;

 delete m;

} */

void

Meal::print()

{

 cout << ''I'm a Meal owned by '';

 m->print();

}



main()

{

 Mean ml (''Honeydew'' , ''Four Seasons'');

 Meal m2 (''Cantaloup'', ''Brook Manor Pub'');

 ml.print(); m2.print();

}

    Previous Section  < Free Open Study >  Next Section