Why does this extremely simple operation not work?

William squidkidsignup at gmail.com
Tue Feb 12 08:58:23 PST 2013


This is an absurdly noobish question, but here goes.  I'm 
learning D (I'm already reasonably comfortable with C and 
Objective-C, so compiled languages are not new to me), and I 
can't figure out why this super simple operation doesn't work.

I have a parent and a child class, and while implicit casting 
from child to parent works (function which takes parent will 
accept instance of child), it does not work with pointers (and 
yes, I understand that because objects are reference types a 
MyObject* is really a pointer to a pointer since a MyObject is a 
pointer).  A function that takes a Parent* as an argument will 
not accept &myChild in its place without an explicit 
cast(Parent*)&myChild.

I feel like there's some fundamental property of the D 
implementation that I'm not getting.  I was under the impression 
an subtype's instance could *always always always* be put in 
place of an instance of the super type.  Why are pointers an 
exception?

class Parent {}
class Child : Parent {}

void myFunc(Parent* obj) {
	writeln("got ", obj);
}

void main() {
	Child myChild = new Child();
	myFunc(&myChild);
}

referenceTest.d(11): Error: function referenceTest.myFunc 
(Parent* obj) is not callable using argument types (Child*)
referenceTest.d(11): Error: cannot implicitly convert expression 
(& myChild) of type Child* to Parent*


More information about the Digitalmars-d mailing list