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

Steven Schveighoffer schveiguy at gmail.com
Fri May 22 22:40:50 UTC 2020


On 5/22/20 5:39 PM, Vinod K Chandran wrote:
> On Friday, 22 May 2020 at 20:51:20 UTC, Steven Schveighoffer wrote:
>> On 5/22/20 4:04 PM, Vinod K Chandran wrote:
>>> [...]
>>
>> Yes. What you cannot do is this (which I hope doesn't compile in 
>> VB.net, but I wouldn't be surprised):
>>
>> Dim sampleList As New List(Of Child)
>> sampleList.Add(New Base(10))
>>
>> Which is the equivalent of what you were requesting.
>>
> Nope--
> List(Of Base) will contain an instance of a Child.
> So in the same manner, i want
> void function(Base) = fnPtr wiil work with
> void function(Child)
> 

That is the opposite of what you are thinking. A function pointer has to 
be valid based on its parameter types. Covariant functions are allowed.

This is OK:

void function(Child) fptr;

void foo(Base) {}

fptr = &foo; // OK! it's fine to call fptr with a Child, because it is a 
Base as well

void function(Base) fptr2;

void foo2(Child) {}

fptr2 = &foo2; // Error! if you called fptr2 with a Base that is NOT a 
Child, bad things will happen.

This is more clear if you actually try calling them:

fptr2(new Base); // the compiler should allow this
foo2(new Base); // but would not allow this

So why should fptr2 be allowed to point at foo2?

-Steve


More information about the Digitalmars-d-learn mailing list