Destructors: Array of Object Pointers

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

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];		
	for (int i=0; i<MAX_SIZE; i++){
		Aptr[i] = new A;
	}

	for (int j=0; j<MAX_SIZE; j++){
		delete Aptr[j];
	}
	
	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: