Reputation: 153
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());
}
}
Upvotes: 3
Views: 499
Reputation: 193
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");
}
}
Upvotes: 1
Reputation: 1265
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
Upvotes: 6
Reputation: 550
Default constructors If you don't provide a constructor for your class, C# creates one by default that instantiates the object and sets member variables to the default values as listed in the Default Values Table. If you don't provide a constructor for your struct, C# relies on an implicit default constructor to automatically initialize each field of a value type to its default value as listed in the Default Values Table.
Reference: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/constructors
Upvotes: 1