Destructors: Array of Objects

#include <iostream.h>
#include <string.h>
/******************************************************************
 File: dest_array.C
 Dynamically create an array of objects, initialize them
 using their default constructors, and destroy the array
 of objects
******************************************************************/

class A {
public:
	A();
	~A();
private:
	char* string;
	static int counter;
};

A::A(){
	string = new char[strlen("Object") + 1];
	strcpy(string, "Object");
	cout << "Constructing Object " << ++counter << endl;
}

A::~A(){
	cout << "Destroying Object " << counter-- << endl;
	delete [] string;
}

int A::counter=0;
const int MAX_SIZE = 10;

int main() {
	A* Aptr = new A[MAX_SIZE];		
	delete [] Aptr;
	return 0;
}

Output:

Constructing Object 1
Constructing Object 2
Constructing Object 3
Constructing Object 4
Constructing Object 5
Constructing Object 6
Constructing Object 7
Constructing Object 8
Constructing Object 9
Constructing Object 10
Destroying Object 10
Destroying Object 9
Destroying Object 8
Destroying Object 7
Destroying Object 6
Destroying Object 5
Destroying Object 4
Destroying Object 3
Destroying Object 2
Destroying Object 1



Back to Previous Page

Document:
Local Date:
Last Modified On: