/***************************************************************************** *** FILE: test_gc.cpp *** DATE: 04/02/2004 *** AUTHOR: Daniel Dementiev *** GOAL: This file contains a small illustration to managed extension of *** MS C++. The class "Robot" is created as managed class (__gc *** modifier). In the function test_gc_object() we create two objects *** of the managed class Robot, but manually delete only one of them. *** However, since the pointer to the second object gets lost once the *** function is over the .NET garbage collection destroyes the second *** Robot object as well. *** To build the program use: *** c:\> cl test_gc.cpp /clr *****************************************************************************/ #using using namespace System; __gc class Robot { private: static int curID = 1; int ID; int HP; public: Robot() : ID(curID++), HP(100) { Console::WriteLine( String::Concat(S"Robot ", ID.ToString(), S" created\n") ); }; ~Robot() { Console::WriteLine( String::Concat(S"Robot ", ID.ToString(), S" destroyed\n") ); } void GetHit(int damage) { HP -= damage; if( HP > 0) Console::WriteLine(S"Robot {0} still alive with {1} HP\n", ID.ToString(), HP.ToString()); else Console::WriteLine(S"Robot {0} is dead\n", ID.ToString()); } __property int get_Energy() { Console::WriteLine( S"get_\n"); return HP; }; __property void set_Energy(int hp) { Console::WriteLine( S"set_\n"); HP = 0<=hp ? hp : HP; }; }; __gc class Cannon { public: Cannon() { Console::WriteLine( S"Cannon is created\n"); }; ~Cannon() { Console::WriteLine( S"Cannon is destroyed\n"); }; void Shoot(Robot &rbt) { rbt.GetHit(10); }; }; void test_gc_object() { Robot *rp = new Robot(); Robot *r = new Robot(); Cannon *c = new Cannon(); rp->GetHit(0); c->Shoot(*rp); r->Energy = 15; r->Energy += 20; rp->GetHit(0); r->GetHit(0); delete rp; } int main() { Console::WriteLine(S"Testing managed class Robot\n"); test_gc_object(); return 0; }