On Tuesday, 8 August 2017 at 06:03:06 UTC, Nrgyzer wrote:
Hi guys,
I've the following code:
abstract class a {}
class b : a { this(a* myAttr = null) {} }
class c : a { this(a* myAttr = null) {} }
void main()
{
auto myb = new b();
auto myc = new c(&myb);
}
DMD says "Constructor c.this(a* myAttr = null) is not callable
using argument types (b*)". I'm confused why it fails because
class b and c are both derived from class a and the constructor
of class b accepts a pointer of class a.
When I replace "auto myb = new b();" by "a myb = new b();", it
works as expected. But then I cannot class-specific functions
of class b because I've the instance of the base-class a. So,
what's the correct way?
Don't use pointers. Classes are already reference types:
abstract class a {}
class b : a { this(a myAttr = null) {} }
class c : a { this(a myAttr = null) {} }
void main()
{
auto myb = new b();
auto myc = new c(myb);
}
If you pass class pointers around, you're passing pointers to the
*references*, not to the *instances*. A b is always an a, but a
b* is not an a* unless you cast. And anyway, it's almost
certainly not what you want.