Bug 91 – Inherited classes require base class to have a default constructor.
Status
RESOLVED
Resolution
INVALID
Severity
minor
Priority
P2
Component
dmd
Product
D
Version
D1 (retired)
Platform
x86
OS
Windows
Creation time
2006-04-06T23:46:00Z
Last change time
2014-02-15T02:09:48Z
Assigned to
bugzilla
Creator
eric96
Comments
Comment #0 by eric96 — 2006-04-06T23:46:42Z
Let me know if this is expected behavior or some rule I don't know about, but I think it's a bug. If you insert the default constructor "this(){}" in A, it compiles fine.
// Looks like it requires the base class to have a default constructor.
class A
{ this (int i) // constructor yage.a.this(int) does not match argument types ()
{}
}
class B : A
{ this (int i)
{}
}
Also, Windows XP SP2; Haven't tried it on Linux yet.
Comment #1 by smjg — 2006-04-07T05:30:24Z
The compiler is correctly diagnosing an error. The derived class needs a base class constructor to call. The keyword "super", when used in a constructor, denotes a constructor of the base class.
class B : A {
this (int i) {
super(i);
}
}
If no call to super is present, then it looks for a default constructor and calls that. Hence if there's no default constructor in the base class, then you must call super when calling the derived class.
Comment #2 by eric96 — 2006-04-07T11:33:06Z
I'm familiar with super(), but I incorrectly thought that I could completely override the constructor in the parent class, as it works with other methods. Is this behavior consistent with other oo languages?
Comment #3 by smjg — 2006-04-07T11:55:54Z
Yes, including C++ and Java. If anybody could circumvent the requirement to use a constructor simply by creating a derived a class, it would defeat the point.
You can, however, put a protected constructor in the base class. This is a constructor created specifically for derived classes to base their constructors on. You would be able to completely override* a constructor if the base class has a protected constructor that does nothing. But can you think of an example in which this would make sense?
* Actually, constructors don't override as such. A constructor is a member only of the class in which it is defined, not of any derived classes. Hence if the base class has no default constructor, then when deriving a class from it you must explicitly define a constructor.