Click to See Complete Forum and Search --> : A simple scenario of run-time polymorphism


vikrampschauhan
January 29th, 2005, 03:39 PM
Say we have a base class Point and a class Circle derives from it.

Say we have the following objects:

Point point1=new Point();
Circle circle1=new Circle();

Then the following is valid:

Point point2=circle1;

point2 should be fully constructed after this statement - so this is fine.

Circle circle2=(Circle) point2

circle2 should be fully constructed after this statement - since point p2 points to a circle, circle2 will point to point2 and be fully defined. So, this is also valid.



But say, now we had:

Circle circle3=(Circle) point1;

We will fail while casting(point1 cannot be casted to a circle - its definition is limited - doesnot include the definition of a circle).

But let us assume the casting succeded.

Even if we were not caught by the casting step, we will fail when we assign circle3 the point1 - this is because we are giving circle3 a simple point and after this stament executes, circle3 is not fully constructed - circle3 consists of [Point+Circle] and only the point part of it is defined by this statement.

So, this may cause a run time error.

Is my analysis correct here?


Thanks
Vikram

darwen
January 29th, 2005, 05:21 PM
You should be using the 'as' operator to do the casting :


Circle circle3=point1 as Circle;


If 'point1' isn't originally a 'Circle' class, or a derived class of Circle then this will have the effect of setting circle3 to null.

To be honest, this isn't a particularly good example of object orientation. This hierarchy should never exist because circles and made up of points - not a type of a point.

Anyway :

Explicit casting e.g.


Circle circlex = (Circle)whatever


is limited to basic types e.g.


ArrayList aList = new ArrayList();
aList.Add(10);
int nValue = (int)aList[0];


For classes in C# use the 'as' operator.

Darwen.