Member Data and Member Function Hiding


It is possible for members (either data members or member functions) of a derived class and the base class to have the same name. This is of special interest when the derived class objects have public access to base class members.

For example, if the name: theMember is used both for the name of a member of the base class and for a member of a derived class, and then the variable name: theMember is used in a statement with an object of the derived class. In this case, the derived member will be the default member accessed.

For example, suppose that DerivedClass is publicly derived from BaseClass. Therefore, if anObject is an object of DerivedClass and both classes have a member: theMember, then the following statement would have anObject accessing theMember of DerivedClass:

image from book

 DerivedClass anObject; anObject.theMember 

image from book

It is said that the derived class' member name hides the base class' member name from access (as was discussed above where it was pointed out that local variables hide global variables from access within a function in which they are defined).

While this is true, this default access may be overcome using the scope resolution operator (::) as in the following rewrite of the above example:

image from book

 DerivedClass anObject anObject.BaseClass::theMember. 

image from book

As a result of the above statement, anObject is accessing theMember of the BaseClass. For an example, see nametest.cpp.

In addition to the problem caused by member hiding as seen above, there is an additional problem caused by a member function of BaseClass and DerivedClass having the same name. For example, suppose that BaseClass and DerivedClass both have a member function with a name like: theFunction(). Further suppose that it is necessary for theFunction() of DerivedClass to call theFunction() of BaseClass within the function body as in the following example:

image from book

 theFunction() {   ....   theFunction();   .... } 

image from book

where the .... indicates additional code and the method: theFunction() in the body is a method of BaseClass.

If the programmer is not careful, it may appear to the compiler that the derived member function: theFunction() is defined as a recursive function. To avoid the appearance of a recursive definition, the scope resolution operator should be used on the reference of the base class member function as in the following:

image from book

 theFunction() {   ....   BaseClass::theFunction();   .... } 

image from book

For example see extdname.cpp




Intermediate Business Programming with C++
Intermediate Business Programming with C++
ISBN: 738453099
EAN: N/A
Year: 2007
Pages: 142

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net