2010/03/21

[C++] Virtual Destructor

#include <iostream>

#include <string>

#include <vector>

using namespace std;

/*

             1    *
Human -----> Tool
                        /\ 
                        |
                     |-----| 
                     |      |
                Pen   Pencil

*/

class Tool // the abstract class

{

public:

// no explicit constructor. there is a default one - Tool();

virtual void use() = 0;

virtual ~Tool(){

cout << "calling ~Tool()" << endl;

}

};

class Pen: public Tool

{

private:

int *x; // some private data;

public:

Pen(){

x = new int[100];

}

void use(){

    cout << "using the Pen" << endl;

}

~Pen(){

cout << "calling ~Pen()" << endl;

delete [] x; // x is a pointer to dynamically allocated memory space in this object. Pencil is responsible to delete the space.

}

};

class Pencil: public Tool

{

private:

char *y; // some private data;

public:

Pencil(){

y = new char[100];

}

void use(){

cout << "using the Pencil" << endl;

}

~Pencil(){

cout << "calling ~Pencil()" << endl;

delete [] y; // y is a pointer to dynamically allocated memory space in this object. Pencil is responsible to delete the space.

}

};

class Human

{

private:

vector<Tool*> tools;

public:

void addTool(Tool* tool){ // keep the pointers to Tools only.

tools.push_back(tool);

}

void paint() // use each tool

{

for (int i = 0; i < (int)tools.size() ; i++){

tools[i]->use();

}

}

virtual ~Human()

{

cout << "Calling ~Human()" << endl;

for (int i = 0; i < (int)tools.size() ; i++){

delete tools[i]; // if the tools are not shared between other Human, this Human object should delete the tools.

}

}

};

int main()

{

Human *human = new Human();

human->addTool(new Pen());

human->addTool(new Pen());

human->addTool(new Pencil());

human->paint();

delete human;

return 0;

}

/* output:

using the Pen

using the Pen

using the Pencil

Calling ~Human()

calling ~Pen()

calling ~Tool()

calling ~Pen()

calling ~Tool()

calling ~Pencil()

calling ~Tool()

*/

沒有留言:

Buddhism and Software Developer

In today's fast-paced society, we are often surrounded by work, goals, and external pressures. However, the wisdom found in Buddhism off...