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

Vinod K Chandran kcvinu82 at gmail.com
Sat May 23 08:33:30 UTC 2020


On Friday, 22 May 2020 at 22:40:50 UTC, Steven Schveighoffer 
wrote:
> On 5/22/20 5:39 PM, Vinod K Chandran wrote:
>> [...]
>
> 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

Thank you for the guidance. I got the point. :)


More information about the Digitalmars-d-learn mailing list