CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Dec 2004
    Posts
    126

    A simple scenario of run-time polymorphism

    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

  2. #2
    Join Date
    Jan 2002
    Location
    Scaro, UK
    Posts
    5,940

    Re: A simple scenario of run-time polymorphism

    You should be using the 'as' operator to do the casting :

    Code:
    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.

    Code:
    Circle circlex = (Circle)whatever
    is limited to basic types e.g.

    Code:
    ArrayList aList = new ArrayList();
    aList.Add(10);
    int nValue = (int)aList[0];
    For classes in C# use the 'as' operator.

    Darwen.
    Last edited by darwen; January 29th, 2005 at 06:23 PM.
    www.pinvoker.com - PInvoker - the .NET PInvoke Interface Exporter for C++ Dlls.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured