Pass a derived class reference to a base class reference
does this means that call a base class from the derived class, like the constructor triangle will call the base class?
class Shape {
public int width, height;
public Shape(int x) {
width = height = x;
}
}
class Triangle : Shape {
public string style;
public Triangle(int x) : base(x) {
style = "isosceles";
}
}
Yes, it will instruct the runtime to invoke that base Shape constructor before Triangle’s.
The logic executes in this order:
You can therefore direct calls to different constructor overloads if you have them. Also note that if your base class has a parameterless constructor, there’s essentially an implicit
base()added if you do not specify one. That means if your base class does not have a parameterless constructor, all subclasses must make a validbase(...parameters...)in their constructor.Also, you can use
this()instead of base to target a constructor on the current subclass class.The outputs would be:
Constructors chain on themselves until they eventually call the
Object()base constructor. That’s whyvar c = new MySubClass(true)calls more than two constructors.