Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritence problem in C# without calling base class constructor

I am wondering, as to why I am not getting an error in the code below. I have defined no constructors in the base class, but have defined one in the derived class. Still the code runs as expected. Can someone kindly help me to get rid of the confusion.

class Shape
{
    public void Area()
    {
        Console.WriteLine("I am  a shape");
    }
}

class Circle : Shape
{
    double radius;
    const double pi = 3.14;

    public Circle(double rad)
    {
        radius = rad;
    }

    public new double Area()
    {
        return pi * radius * radius;
    }
}

The code compiles perfectly and gives me the desired results. Thank you,

class Progam
{
    static void Main(string[] args)
    {
        Shape s1 = new Shape();
        s1.Area();

        Shape s2 = new Circle(10);
        s2.Area();

        Circle c1 = new Circle(4.0);
        Console.WriteLine(c1.Area());
    }
}
like image 830
Shadman Mahmood Avatar asked Aug 27 '26 08:08

Shadman Mahmood


2 Answers

A default base constructor (i.e. without parameters) is executed automatically if no other constructors are defined.

When you don't define a constructor explicitly (like in your question), a default constructor is defined implicitly

like image 68
user11909 Avatar answered Aug 28 '26 20:08

user11909


As everybody else has pointed out, here:

Shape s1 = new Shape();

You're initializing your Shape class. You think it doesn't make sense because you don't have a Constructor defined, but since you don't have it it has been dynamicaly generated so the program doesn't break. Thus, your Shaple class is executed like this:

class Shape
{
    public Shape()
    {
    }

    public void Area()
    {
        Console.WriteLine("I am  a shape");
    }
}
like image 41
ikerbera Avatar answered Aug 28 '26 21:08

ikerbera