subclass to base class but not subclass pointer to base class pointer?
John Colvin
john.loughran.colvin at gmail.com
Sat Apr 20 08:32:04 PDT 2013
On Saturday, 20 April 2013 at 14:56:25 UTC, Namespace wrote:
> Why can D implicitly cast from the subclass to the base class,
> but not implicitly from the subclasse pointer to the base class
> pointer?
>
> This works: http://dpaste.1azy.net/30dd34a0
> This not: http://dpaste.1azy.net/ffacfd83
>
> Makes not much sense for me.
a pointer to class in D is actually a pointer to a pointer as
classes are reference types. Polymorphism for pointers to
pointers to objects is not allowed.
Consider this (ported from here
https://groups.google.com/forum/?fromgroups=#!topic/comp.lang.c++/kNZ-ksORPwU):
class Base
{
void doBaseThings();
}
class Dirv
{
doDirvThings();
}
void AssignNewBaseTo(Base* basePtr)
{
*basePtr = new Base;
}
void Oops()
{
Dirv dirv;
AssignNewBaseTo(&dirv);
dirv.doDirvThings(); // runtime crash -- a Base
object
// being asked to do Dirv
things.
}
More information about the Digitalmars-d-learn
mailing list