A.T.
A.T.

Reputation: 26312

Stack overflow exception, unable to find reason

i have piece of code

public class A
    {
        public A()
        {
            Console.WriteLine("A");
        }
        B b = new B("From A");
    }
    public class B : A
    {
        public B()
        {
            Console.WriteLine("B");
        }
        public B(string str)  //Getting exception here
        {
            Console.WriteLine("In B " + str);
        }
    }
    public class C : A
    {
        B b = new B("From C");
        public C()
        {
            Console.WriteLine("C");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            new C();
            Console.ReadKey();
        }
    }

Here, i know that all properties are initialized first before base constructor called, but i am unable to find why i am getting Stackoverflow exception. Any Help ?? Thanks

Upvotes: 0

Views: 135

Answers (4)

Martin Eden
Martin Eden

Reputation: 6262

Because B inherits from A, it inherits the

B b = new B("From A");

field. So whenever you create a B object it creates another B object, in an infinite recursive chain.

So in the actual Program you have, you create a C object. This then constructs a B object using the overload that takes a string ("From C"). You then get an exception on that constructor, because it then recursively creates infinite B objects.

Upvotes: 10

Sundeep
Sundeep

Reputation: 51

The problem above is due to cyclic instantiation.

Here our thinking of instantiation causes these kind of issues: Here when we instantiate C we just do not get object of class C but, it in fact is the combination of C+B+A.

These kind of problems can be easily identified by drawing an object diagram with Arrows from instantiating object to instanted object.

Upvotes: 0

jiten
jiten

Reputation: 5264

Since B inherits from A

//public class B : A

And when you create object of B in class A,It goes in recursive infinite loop.

Upvotes: 0

JohnLBevan
JohnLBevan

Reputation: 24430

Recursive infinite loop:

  • Every time you create a B, you create a new A (through inheritance).
  • Every time you create an A, you create a new B (through variable b).

Upvotes: 4

Related Questions