Calling operator in base type from derived type

General FreeBASIC programming questions.
Post Reply
Rule
Posts: 16
Joined: Nov 03, 2020 19:04
Contact:

Calling operator in base type from derived type

Post by Rule »

Consider the following example:

Code: Select all

Type Parent
    Declare Operator Let (ByRef rhs As Const Parent)
    ...
End Type

Type Child Extends Parent
    Declare Operator Let (ByRef rhs As Const Child)
    ...
End Type
It would be useful if you could call Operator Parent.Let from Operator Child.Let, for example if you don't know the inner workings of Parent, or at least to avoid code redundancy. How should you do that? The only way that seems to work doesn't look very safe:

Code: Select all

Operator Child.Let (ByRef rhs As Const Child)
    Base.Operator Let rhs    '' error
    Parent.Let rhs           '' error
    Cast(Parent, This) = rhs '' seems to work but is inelegant and probably unsafe
    ...
End Operator
Rule
Posts: 16
Joined: Nov 03, 2020 19:04
Contact:

Re: Calling operator in base type from derived type

Post by Rule »

The best I could come up with, is a helper subroutine:

Code: Select all

Private Sub ParentOperatorLet (ByRef lhs As Parent, ByRef rhs As Const Parent)
    lhs = rhs
End Sub

Operator Child.Let (ByRef rhs As Const Child)
    ParentOperatorLet This, rhs
    ...
End Operator
fxm
Moderator
Posts: 12133
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: Calling operator in base type from derived type

Post by fxm »

'Cast(Parent, This) = rhs' is safe, and implicitly calls the 'Parent.Let' operator by using the assignment operator after up-casting.

Other solution to explicitly call the 'Parent.Let' operator by using the 'Procptr()' operator (since fbc 1.10.0):

Code: Select all

Operator Child.Let (ByRef rhs As Const Child)
'    Base.Operator Let rhs    '' error
'    Parent.Let rhs           '' error
'    Cast(Parent, This) = rhs '' works and safe
'    ...
    Procptr(Parent.Let)(This, rhs)
End Operator
Rule
Posts: 16
Joined: Nov 03, 2020 19:04
Contact:

Re: Calling operator in base type from derived type

Post by Rule »

Thank you, fxm. I was unsure about the explicit Cast because I didn't know what happens under the hood. I came up with the helper routine because 1) the ByRef avoids that we're unintentionally working on a copy, and 2) I consider it best to rely on implicit casting as much as possible.
fxm
Moderator
Posts: 12133
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: Calling operator in base type from derived type

Post by fxm »

In an inheritance hierarchy, only up-casting is always safe. Down-casting can often be unsafe depending on its use.

'Procptr(Parent.Let)(This, rhs)' induces an implicit up-casting because the type of 'Procptr(Parent.Let)()' is 'Sub(As Parent, As Const Parent)'.
Post Reply