colobot-data/help/D/cbot/pointer.txt

54 lines
2.3 KiB
Plaintext
Raw Normal View History

\b;References (for specialists)
CBOT uses references for \l;classes\u cbot\class; and \l;arrays\u cbot\array;. 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 \c;\l;null\u cbot\null;\n; 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 \c;\l;null\u cbot\null;\n; reference.
Example:
\c;\s;{
\s; MyClass item1(); // create a new instance
\s; // referenced by item1
\s; MyClass item2; // create a null reference
\s; item2 = item1; // copy the reference,
\s; // item2 and item1 now reference
\s; // the same instance
\s; item1.a = 12; // modifies the instance
\s; // referenced by item1 (and item2)
\s; message(item2.a);// displays 12
\s;}
\n;
If you pass a \l;class\u cbot\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 actuallay modified.
\c;\s;void Test( MyClass item )
\s;{
\s; item.a = 12; // modify the original instance
\s; item = new MyClass(); // new local instance
\s; item.a = 33; // modifie the local instance
\s;}
\n;
Calling the fucntion \c;Test()\n;¦:
\c;\s;{
\s; MyClass toto();
\s; Test(toto);
\s; message(toto.a); // displays 12
\s;}
\n;
The instance containing the field \c;a = 33\n; is referenced only by the newly created instance \c;item\n; inside the fucntion \c;Test\n;. At the end of \c;Test\n; this newly created instance referenced by \c;item\n; is automatically deleted.
A function can return an instance¦:
\c;\s;MyClass Test2( )
\s;{
\s; MyClass item = new MyClass();
\s; item.x = 33;
\s; return item;
\s;}
\n;
Call the function like this:
\c;\s;{
\s; MyClass toto;
\s; toto = Test2(); // toto will contain a reference to
\s; // the instance created by Test2()
\s; message(toto.a); // displays 33
\s;}
\n;
\t;See also
\c;\l;class\u cbot\class;\n;, \c;\l;new\u cbot\new;\n;
\l;Programming\u cbot;, \l;types\u cbot\type; and \l;categories\u cbot\category;.