/
ColdC/Functions/
ColdC/Structure/
<head><title>ColdC: Objects: Variables</title></head>

<h1 align=center><a href="/ColdC/">ColdC</a>: <a href="/ColdC/Objects/">Objects</a>: Variables</h1>

<hr>

<p>In ColdC there are two types of variables, <i>local variables</i> and
<i>object variables</i>.  An object variable is defined on the object, and
can be accessed by any method defined on the same object.  Object variables
exist outside of the scope of methods.  Local variables are defined within
a method, with their scope being limited to that method.</p>

<p>If a variable is used in a method, but it is not defined as an argument
or a local variable (at the top of the method), it is assumed to be an object
variable.  When the method is executed the interpreter looks on the object
for the variable.  If the interpreter cannot find the variable on the object,
the error <code>~varnf</code> is thrown.</p>

<p>It is important to remember that variables may only be accessed by
methods <i>defined on the same object as the variable</i>.  No other method
may reference that variable.  As an example let us define two objects (if
this syntax is unfamiliar, see <a href="/ColdC/TextDB/">the TextDB format</a>):

<blockquote>
<pre>
object $obj_A: $root;
var $obj_A text;

public method $obj_A.get_text {
    return text;
};

public method $obj_A.set_text {
    arg new_text;

    text = new_text;
};

object $obj_B: $obj_A;

</pre>
</blockquote>

<p>Calling <code>$obj_A.set_text("text")</code> will set <code>text</code>
on $obj_A with a value of "text".  <code>$obj_B</code> does inherit the
ability to define and write to it's own copy of <code>text</code> (using
methods defined on <code>$obj_A</code>), but it does not inherit values
assigned to object variables on it's ancestors.  I.e. calling <code>$obj_B.get_text()</code> will return <code>0</code> (the default unset value), as we
have not yet set it to any value on <code>$obj_B</code>, only on
<code>$obj_A</code> (this is called <a href="http://www.cold.org/ColdC/oop.html#encap"><i>encapsulation</i></a>).</p>

<p>If we were to override the method <code>get_text</code> defined on
<code>$obj_A</code>, on <code>$obj_B</code>, as:

<blockquote>
<pre>
public method $obj_B.get_text {
    return "more text: " + text;
};
</pre>
</blockquote>

<p>When we called it, the <code>~varnf</code> error would be raised, because
the object variable <code>text</code> is not defined on $obj_B, where the
overriding method <code>get_text</code> is defined.</p>

<hr size=4><p align=center><i>Last Modified on Jan 25 1996</i>
<br><i>Copyright &copy; 1995, 1996, Brandon Gillespie</i>
</body>