Pointers, References and Inheritance


When a class B is derived from a class A, pointers to objects of class A can be used to point to objects of class B. For example suppose that class B is derived from class A, then:

image from book

 A* thePointer; B theObject; thePointer = &theObject; 

image from book

are legal statements. See ptr_base1.cpp Notice in this example the commented out code where an attempt to access a method of the B class with the pointer thePointer to the A class is not permitted even though it contains the address of an object of B. As this example shows, it is only possible for a pointer to the base to access the derived object's base members.

A pointer to a derived class can not be used to hold the address of an object to the base class. See this fact ptr_base4.cpp that will not compile because of a violation of this principle.

In addition to pointers to a base class A being used to address an object of a derived class B, it is also possible to use an object b of the derived class B where a reference to a base object of A is used. That is an object to a derived class may be used as the argument of a function that was defined with an argument that is a reference to a base object. See object.cpp.

In the example: ptr_base1.cpp above where thePointer was a pointer to class A, the lines of code made thePointer a pointer to theObject an object of B. While this is a pointer to the object of B, the pointer only addresses the part of theObject associated with the base class A. For example if showA( ) is a method of class A, then the following line would be correct:

image from book

 thePointer -> showA(); 

image from book

However if showB( ) is a method of class B, then typecasting would be required as in the following:

image from book

 ((B*)thePointer) -> showB(); 

image from book

See ptr_base2.cpp.

Another problem that can occur is when you use arithmetic operations on thePointer (e.g. thePointer + 1). Since thePointer is a pointer to the class A, the advancement in memory is the size of an object of A and not the size of an object of B even though thePointer contains the address of an object of B. Therefore mixing the pointer of a base class with the address of a derived object may cause problems. In addition recall that although you may use a pointer of the base class A to address an object of a derived class B, the converse is not true i.e. a pointer to the derived class B can not be use to access an object of A. See ptr_base3.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