0

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

4 Answers 4

10

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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).

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.