0

I need to understand the concept that why we cannot call constructor of base class from derived. I have some scenario.

public class clsA
    {
        int i = 10;
        public void CallA()
        {
            Console.WriteLine("Called by Class A");
        }
    }

    public class clsB : clsA
    {
        int i = 20;
        public void CallB()
        {
            Console.WriteLine("Called by Class B");
        }

    }

if i do like that

clsA _obja = new clsA();

then constructor of base class called and we get its methods.

if i do like that

clsB _objb = new clsB();

then also constructor of base class called and we get base class methods and derived class methods as well.

if i do like that

clsA _objab = new clsB();

then constructor of base class called and we get its methods.

But now my question is that why we cannot call constructor of base class from derived class like

clsB _objb = new clsA();

Please suggest me. I want simple answer.

Rahul
  • 5,603
  • 6
  • 34
  • 57
  • 1
    A lot of answers as to why a derived class reference cannot refer to a base class object: ( http://stackoverflow.com/questions/729527/is-it-possible-to-assign-a-base-class-object-to-a-derived-class-reference-with-a) though the wording is slightly different. – Anindya Dutta May 28 '15 at 16:05

1 Answers1

3

This has nothing to do with the constructor calls. The problem is that you can't assign an instance of a parent class to a variable of a child class. A clsB instance is a clsA, but a clsA object is not necessarily a clsB.

BJ Myers
  • 6,617
  • 6
  • 34
  • 50