Code Example for Memory Leakage #8 #include <iostream.h> class Fruit { double weight; char* color; protected: Fruit(double, char*); Fruit(const Fruit&); public: //Note the nonpolymorphic destructor ~Fruit(); // The correct destructor would look like: // virtual ~Fruit(); virtual void print(); }; Fruit::Fruit(double w, char* col) { weight = w; color = new char[strlen(col)+1]; strcpy(color, col); } Fruit::Fruit(const Fruit& rhs) { weight = rhs.weight; color = new char[strlen(rhs.color)+1]; strcpy(color, rhs.color); } Fruit::~Fruit() { delete color; } void Fruit::print() { cout << ''\tFruit weight:'' << weight << ''\n''; cout << ''\tFruitcolor:'' << color << ''\n''; } class Apple : public Fruit { char* variety; public: Apple(double, char*, char*); Apple(const Apple&); ~Apple(); void print (); }; Apple:: Apple(double w, char* col, char* var) : Fruit(w, col) { variety = new char[strlen(var)+1]; strcpy(variety, var); } Apple::Apple(const Apple& rhs):Fruit(rhs) { variety = new char[strlen(rhs.variety)+1]; strcpy(variety, rhs.variety); } Apple::~Apple () { delete variety; } void Apple::print() { cout << ''Hi, I'm a'' << variety << ''Apple\n''; Fruit::print(); } class Banana : public Fruit { char* export; public: Banana(double, char*); Banana(const Banana&); ~Banana(); Banana::Banana(double w, char* exp) : Fruit(w, ''Yellow'') { export = new char[strlen(exp)+1]; strcpy(export, exp); } Banana:: Banana(const Banana&rhs):Fruit(rhs) { export = new char[strlen(rhs.export)+1]; strcpy(export, rhs.export); } Banana::~Banana() { delete export; } void Banana::print() { cout << ''Hi, I'm a banana from ''; cout << export << ''\n''; } main() { Fruit *basket[20]; int i, num; double weight; char color[128], variety[128], answer[128]; // The following code allows the user to // interactively build a fruit basket of size // 1 through 20. cout << ''How many fruit in the basket? ''; cin >> num; if (num < 0 num > 20) num = 10; for (i=0; i<num; i++) { cout << ''A)pple or B)anana? ''; cin >> answer; if (answer [0] == 'a' answer[0] == 'A' ) { cout << ''Apple's weight: ''; cin >> weight; cout << ''Apple's color: ''; cin >> color; cout << ''Apple's variety: ''; cin >> variety; basket[i] = new Apple(weight, color, variety); } else { cout << ''Banana's weight: ''; cin >> weight; cout << ''Banana's country: ''; cin >> variety; basket[i] = new Banana (weight, variety); } } for (i=0; i<num; i++) { basket[i]->print(); } // If Fruit's destructor is not virtual, // then this code will call Fruit's // destructor num times. This will leak // the memory used for the variety string in // each Apple and the export string in each // Banana. for (i=0; i<num; i++) { delete basket[i]; } } |