Colobot Wiki

CBOT uses references for classes and arrays. Any class variable actually contains a reference to the instance. The instance actually contains the class fields. Several references can reference the same instance. A null reference references nothing. You can compare an instance to a suitcase and a reference to a carrier. Each time we need a new suitcase we create a new instance with a carrier. But a suitcase can be carried by more than one carrier. A carrier who carries no suitcase is a null reference.


	MyClass item1(); // create a new instance
	                 // referenced by item1
	MyClass item2;   // create a null reference
	item2 = item1;   // copy the reference,
	                 // item2 and item1 now reference
	                 // the same instance
	item1.a = 12;    // modifies the instance
	                 // referenced by item1 (and item2)
	message(item2.a);// displays 12

If you pass a class instance as parameter to a function, the function only receives a reference to the instance. That means if you modify the instance in the function, the instance that has been specified by the caller will be actually modified.

void Test( MyClass item )
	item.a = 12;          // modify the original instance
	item = new MyClass(); // new local instance
	item.a = 33;          // modifies the local instance

Calling the function Test():

	MyClass toto();
	message(toto.a);  // displays 12

The instance containing the field a = 33 is referenced only by the newly created instance item inside the function Test. At the end of Test this newly created instance referenced by item is automatically deleted.

A function can return an instance:

MyClass Test2( )
	MyClass item = new MyClass();
	item.x = 33;
	return item;

Call the function like this:

	MyClass toto;
	toto = Test2(); // toto will contain a reference to
	                // the instance created by Test2()
	message(toto.a); // displays 33