index:   hello1  hello2  hello3  hello4    source:  hello.zip

hello2.cpp

hello2.cpp adds a member variable that distinguishes one world from others. We instantiate objects inside a loop (local scope) and use new/delete to create an object on the heap.



#include <iostream>
#include <string>
using namespace std;

string worlds[] = {"Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune"};
int count = 0;

class theWorld {
public:
	theWorld() { instance = count++; cout << "Hello from " + worlds[instance] << endl; }
	~theWorld() { cout << "Goodbye from " + worlds[instance] << endl; }
	int instance;
};

theWorld myWorld;

int main()
{
	cout << "Hello from main program.\n";
	theWorld *pworld = new theWorld();
	for (int i=0; i<2; i++) {
		theWorld loopWorld;
	}
	delete pworld;
	cout << "Goodbye from main program.\n";
	return 0;
}


Results

C:\classes\ece538\work\hello>hello2
Hello from Mercury
Hello from main program.
Hello from Venus
Hello from Earth
Goodbye from Earth
Hello from Mars
Goodbye from Mars
Goodbye from Venus
Goodbye from main program.
Goodbye from Mercury


Maintained by John Loomis, updated Tue Jan 23 20:45:01 2007