Home All Groups Group Topic Archive Search About

Base Class Method to use Shadow'ed member variable of Derived Class?

Author
4 Apr 2006 12:33 PM
Joe HM
Hello -

I have a function in a base class that I want to use the shadow'ed
member variable of the derived class.  Here is the code ...

Public Class cCaptureBase
    Protected Const cDummy As String = "Base"

    Overridable Sub print()
        Console.WriteLine(cDummy)
    End Sub
End Class

Public Class cCaptureDerived
    Inherits cCaptureBase

    Protected Shadows Const cDummy  As String = "Derived"
End Class

Sub Main()

    Dim lInstance As cCaptureBase
    lInstance = New cCaptureDerived

    lInstance.print()

I would like print() to print the cDummy of the cCaptureDerived class.
Is there any way of doing that?  I know I could override the print() in
the derived class but I would like to keep that in the base class.

This might either be something very simple or something that should not
be done in proper OO design.  Any suggestions?

Thanks!
Joe

Author
4 Apr 2006 1:01 PM
Larry Lard
Joe HM wrote:
Show quoteHide quote
> Hello -
>
> I have a function in a base class that I want to use the shadow'ed
> member variable of the derived class.  Here is the code ...
>
> Public Class cCaptureBase
>     Protected Const cDummy As String = "Base"
>
>     Overridable Sub print()
>         Console.WriteLine(cDummy)
>     End Sub
> End Class
>
> Public Class cCaptureDerived
>     Inherits cCaptureBase
>
>     Protected Shadows Const cDummy  As String = "Derived"
> End Class
>
> Sub Main()
>
>     Dim lInstance As cCaptureBase
>     lInstance = New cCaptureDerived
>
>     lInstance.print()
>
> I would like print() to print the cDummy of the cCaptureDerived class.
> Is there any way of doing that?  I know I could override the print() in
> the derived class but I would like to keep that in the base class.
>
> This might either be something very simple or something that should not
> be done in proper OO design.  Any suggestions?

A good rule of thumb is that a design that requires the use of
'Shadows' is doing something wrong.

Try this:

Public Class BaseClass
    Protected Overridable ReadOnly Property Dummy() As String
        Get
            Return "base"
        End Get
    End Property

    Public Overridable Sub Print()
        Console.WriteLine(Me.Dummy)
    End Sub

End Class

Public Class DerivedClass
    Inherits BaseClass

    Protected Overrides ReadOnly Property Dummy() As String
        Get
            Return "derived"
        End Get
    End Property

End Class

Module Module1

    Sub Main()

        Dim instance As BaseClass = New DerivedClass

        instance.Print()

        Console.ReadLine()
    End Sub

End Module

--
Larry Lard
Replies to group please
Author
4 Apr 2006 2:59 PM
Joe HM
D'oh ... right ... I forgot about the Property!

Thanks for the help ... and I will avoid "Shadows" in the future ...

Joe