Reputation: 5636
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.
Upvotes: 0
Views: 88
Reputation: 6823
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
.
Upvotes: 3