Reputation: 11
The doubt is:
When defining a constant constructor in a subclass, it is necessary that the default constructor of the upper class is constant.
However, when the default constructor of the upper class is defined as constant, it is not necessary that the constructor of the inherited class be constant.
The codes below exemplifies the situation:
// Default constructor of the subclass defined as constant:
class Super_class {
Super_class();
}
class Sub_class extends Super_class {
const Sub_class() : super();
}
// Default constructor of the upper class defined as constant:
class Super_class {
const Super_class();
}
class Sub_class extends Super_class {
Sub_class() : super();
}
Could someone explain to me how this works?
Upvotes: 0
Views: 259
Reputation: 71623
If your subclass has a const
constructor, then it is must call a super-class const
constructor, otherwise it won't be able to perform compile-time constant evaluation of the entire construction. The const
superclass constructor does not need to be the unnamed (sometimes mistakenly named "default") constructor. The superclass just have to have some constant generative constructor that you can call.
Example:
class SuperClass {
final int foo;
factory SuperClass() => const SuperClass._(0);
const SuperClass._(this.foo);
}
class Subclass {
final int bar;
const SubClass(int foo, this.bar) : super._(foo);
}
A subclass does not have to have a const constructor, even if the superclass does. The superclass itself can have non-constant constructors as well as constant constructors.
Upvotes: 1
Reputation: 89965
Constructors are not inherited. A const
base class constructor imposes no const
requirements on its derived classes.
A const
constructor means that the object must be constructible in a const
context. One way of thinking about it is that the object must be constructible at compilation time; it does not depend on any runtime values. Consequently, a const
constructor can depend only on other things that are const
, including base class constructors.
Upvotes: 1