25-Virtual Destructors

25-Virtual - #include #include #include using namespace std There is a problem with proper object destruction when

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
#include <iostream> #include <sstream> #include <string> using namespace std; // // There is a problem with proper object destruction when using polymorphism. // If we delete a base class pointer that is storing a derived object // Not all of the destructors will be propertly called. // // Broken Case: class SomeObject { private: int someData; public: SomeObject(int data) { someData = data; } int getData() { return someData; } }; class Broken { private: SomeObject *data; public: Broken(int d = 0) { data = new SomeObject(d); cout << data->getData() << " - Broken object built.\n"; } ~Broken() { cout << data->getData() << " - Broken object destroyed.\n"; delete data; } }; class DerivedBroken : public Broken { private: SomeObject *moreData; public: DerivedBroken(int d = 0) { moreData = new SomeObject(d); cout << moreData->getData() << " - Derived Broken object built.\n"; } ~DerivedBroken() { cout << moreData->getData() << " - Derived Broken object destroyed.\n"; delete moreData; // memory leak } }; void OKExample()
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
{ // Create and let them fall out of scope
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 10/05/2011 for the course CS 37 taught by Professor Glenncuevas during the Summer '09 term at Irvine Valley College.

Page1 / 4

25-Virtual - #include #include #include using namespace std There is a problem with proper object destruction when

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online