Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

Protecting Class Members

When a class definition is used to build another class through inheritance, an interface is available to the new class. Like a back door, the new class can call any methods and use any member data declared protected and still remain hidden to any class users.

The protected class interface allows the class definition to provide a specific interface to any new class built to enhance the functionality of an existing class. Member data is commonly defined as protected if the members' usage isn't governed by code. Member data for a class property is a good example. If the property is a simple value and doesn't require special code, it's more efficient for the new class definition to be able to use and set the data value directly.

The following protected members are added to the class definition in Listing 3.1. These members are available through the public properties defined in the class to users and directly available to any class that inherits from it:

Public Class CircleButton

  'Protected member data
  Protected ptPos As Drawing.Point
  Protected strText As String

  'Public properties to set/get protected member data
  Public Property Pos() As Drawing.Point
   Pos = ptPos
  End Get
  Set(ByVal Value As Drawing.Point)
   ptPos = Value
  End Set
  End Property

  Public Property Text() As String
   Text = strText
  End Get
  Set(ByVal Value As String)
   strText = Value
  End Set
  End Property


You can also define methods as protected to provide a semi-private interface to any class that inherits your class. The methods aren't available to class users, so they are still contained within the "black box." Derived classes can override protected methods to change the functionality of the object or even make a method public, which changes the interface available to users of the new class.

Overall, protected is used whenever the encapsulated functionality and member data are available for enhancement and access by new class definitions. Because the methods and members aren't visible to the class users, the integrity of the object design is maintained.

  • + Share This
  • 🔖 Save To Your Account