3D-kreativ
3D-kreativ

Reputation: 9299

About inheritance and constructors

I just wondering if this code is correct that I found in some information. The thing I find strange, is that diameter is used twice in both example, is this really correct?

public Ellipse(double diameter): base(diameter, diameter)

Upvotes: 0

Views: 113

Answers (4)

Botz3000
Botz3000

Reputation: 39610

That depends on what the base class constructor does with the parameters, but syntactically, it's correct.

The code you posted calls the base class constructor that matches the supplied arguments instead of the default base class constructor (if any).

Upvotes: 1

Hubi
Hubi

Reputation: 1629

The syntax is correct. The classes might look something like that:

public class Base
{
  public Base(double d1, double d2)
  {
  }
}

public Eclipse : Base
{
   public Ellipse(double diameter)
        : base(diameter, diameter)
   {
   }
}

Upvotes: 2

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48568

This is constructor chaining i.e. calling base constructor before child constructor.

If base class has a constructor like

public Base(double, double)

then it is perfectly fine.

Upvotes: 1

gideon
gideon

Reputation: 19465

This is the constructor of an Ellipse class, it calls the base class constructor which has two parameters.

It could look something like this:

class Shape
{
 public Shape(double diameter1, double diameter2)
 {
 }
}
class Ellipse : Shape
{
 public Ellipse(double diameter) : base(diameter, diameter)
 {
 }
}

If you do new Ellipse(10); 10 is passed into the Ellipse constructor, which calls the Shape class constructor and passes 10 as the arguments for both those params.

Upvotes: 2

Related Questions