oop tutorials
lutger
lutger.blijdestijn at gmail.com
Wed Mar 5 01:58:33 PST 2008
Saaa wrote:
>> Could anybody give a simple example of unallocated class reference use?
>> I think that would explain it all to me :)
I'll try to give a few examples.
1. Error checking:
Class theObject = tryToMakeTheObjectInASpecialWay();
if (theObject is null)
throw new Exception("could not make the object!");
2. Conditional construction, this isn't really a good way to do it but that
doesn't matter for this example:
Car myCar;
if (winLottery == true)
myCar = new Porsche();
else
myCar = new Ford();
3. Composition. It is common that objects holds references to other objects
that are allocated at a later stage than that the 'parent' object is
allocated.
A classical example is a linked list:
class List(T)
{
T data;
List!(T) next;
}
> Class className; // This will create a reference
> className=new Class(); // This will allocate an instance of Class
>
> Why do I need to name the class twice?
> Is there a shortcut?
In this case you don't, it's better to write:
Class className = new Class();
or with type inference:
auto className = new Class();
> And, could I do:
>
> Class className;
> className=new Class_2();
Yes, but only if Class_2 can be downcast to Class:
class Class_2 : Class
{
}
Again, you could also write Class className = new Class_2();
More information about the Digitalmars-d-learn
mailing list