Problem with inheritance / compossition

  • Thread starter Thread starter Dilip Krishnan
  • Start date Start date
D

Dilip Krishnan

This is because you have a cyclic reference in the classes. the
dependency of the classes causes the constructor to be called infinitely
 
Hi I have this C# code
---------------------------------

class BaseUnit;
....
class ResizeBorder : Shape
....

class Shape : BaseUnit
{
ResizeBorder a = new ResizeBorder();
}
---------------------------------
(The classes offcourse has implementations)

When i do this i get a stackOverFlowException.

If ResizeBorder dosent inherit from shape it works perfeckt...Am I doing
somethíng wrong? Or is the StackOverFlow maybe caused ba something else wich
first shows when i use the above form?

Anders
 
Flare,

The reason this is happening is because when you create a new
ResizeBorder instance, the constructor for the Shape class needs to be
called. When that happens, you create another ResizeBorder instance, which
then calls the constructor of the Shape class again, and so on, and so on,
ad infinitum (or at least, until you get the StackOverflowException).

Hope this helps.
 
Hi, Flare

You have perfect infinite loop of constructors here. In Shape constructor
you create ResizeBorder, which calls Shape constructor, which once again
creates ResizeBorder and so on. That's why you have stack overflow.

HTH
Alex
 
Back
Top