Example Code for Leak 2

 <  Free Open Study  >  

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(); } 
 <  Free Open Study  >  


Object-Oriented Design Heuristics
Object-Oriented Design Heuristics (paperback)
ISBN: 0321774965
EAN: 2147483647
Year: 1996
Pages: 180

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net