How to use base class & child class as parameter in one function ?

H. S. Teoh hsteoh at quickfur.ath.cx
Fri May 22 21:14:56 UTC 2020


On Fri, May 22, 2020 at 08:55:45PM +0000, Vinod K Chandran via Digitalmars-d-learn wrote:
> On Friday, 22 May 2020 at 20:06:20 UTC, Adam D. Ruppe wrote:
> > On Friday, 22 May 2020 at 20:04:24 UTC, Vinod K Chandran wrote:
> > > sampleList.Add(New Child(10.5)) Is this possible in D without
> > > casting ?
> > 
> > Direct translation of this code works just fine in D.
> 
> Yeah, my bad. I just checked in D. But think inherited type difference
> is a problem in function pointer's parameters only.
> alias EvtFuncPtr = void function(EventArgs);
> Now, this EvtFuncPtr won't allow any derived classes of EventArgs as
> parameter. That's the problem i am facing.
[...]

So you're basically saying:

	void function(DerivedClass)

cannot implicitly convert to:

	void function(BaseClass)

right?

This is as it should be:

	class Base { ... }
	class Derived : Base { ... }
	class Another : Base { ... }

	void baseFunc(Base) { ... }
	void derivedFunc(Derived) { ... }

	void function(Base) funcPtr;
	funcPtr = baseFunc;	// OK
	funcPtr = derivedFunc;	// Not allowed

Why is it bad to assign derivedFunc to funcPtr?  Consider this:

	Base obj = new Another;
	funcPtr = baseFunc;
	funcPtr(obj);	// OK, because Another is a subtype of Base

	funcPtr = derivedFunc; // suppose this was allowed
	funcPtr(obj);	// Uh oh, derivedFunc receives an argument of
			// type Another which is not a subtype of
			// Derived

So, it's not permissible to allow assigning derivedFunc to funcPtr
without a cast.


T

-- 
Indifference will certainly be the downfall of mankind, but who cares? -- Miquel van Smoorenburg


More information about the Digitalmars-d-learn mailing list