WHAT IS PROTECTED DATA?

Examine the program named INHERIT4.CPP for an example we will use to define protected data. Just to make the program more versatile, we have returned to the use of the keyword public prior to the name of the parent classes in lines 18 and 29 of the class definitions.

If the data within a base class were totally available in all classes inheriting that base class, it would be a simple matter for a programmer to inherit the superclass into a derived class and have free access to all data in the parent class. This would completely override the protection afforded by the use of information hiding. For this reason, the data in a class are not automatically available to the methods of an inheriting class. There are times when you may wish to automatically inherit all variables directly into the subclasses and have them act just as though they were defined as a part of those classes also. For this reason, the designer of C++ has provided the keyword protected.

In the present example program, the keyword protected is given in line 5 so that all of the data of the vehicle class can be directly imported into any derived classes but are not available outside of the class or derived classes. All data are automatically defaulted to private type if no specifier is given. The keyword private can be used as illustrated in lines 19 and 30 but adds nothing due to the fact that class members default to private by definition.

You will notice that the variables named wheels and weight are available to use in the method named initialize() in lines 85 through 91 just as if they were declared as a part of the car class itself. We can now state the rules for the three means of defining variables and methods.

private – The variables and methods are not available to any outside calling routines, and they are not available to any derived classes inheriting this class.

protected – The variables and methods are not available to any outside calling routines, but they are directly available to any derived class inheriting this class.

public – All variables and methods are freely available to all outside calling routines and to all derived classes.

You will note that these three means of definition can also be used in a struct type. The only difference with a struct is that everything defaults to public until one of the other keywords is used.

Be sure to compile and execute this program before continuing on to the next example program.

Share
Tweet
Share
Pin