OOPortal OOPortal


Inheritance/Polymorphism  «Prev 

Typing Conversion Visibility

C++ Program Dissection


//Test pointer conversion rules.

#include  "student.h"  //include relevant declarations

int main()
{
   student       s("Mae Pohl", 100, 3.425, fresh),
                    *ps = &s;
   grad_student  gs("Morris Pohl", 200, 3.2564, grad,
                     ta, "Pharmacy",
                    "Retail Pharmacies"), *pgs;

ps -> print();            //student::print
ps = pgs = &gs;
ps -> print();            //student::print
pgs -> print();           //grad_student::print
}

Objects, Abstraction, Data Structures
student s("Mae Pohl", 100, 3.425, fresh), *ps = &s;
grad_student  gs(&Morris Pohl", 200, 3.2564, grad, ta, "Pharmacy",
"Retail Pharmacies"), *pgs;

This function declares both objects and pointers to them. The conversion rule is that a pointer to a publicly derived class may be converted implicitly to a pointer to its base class. In our example, the pointer variable ps can point at objects of both classes, but the pointer variable pgs can point only at objects of type grad_student. We wish to study how different pointer assignments affect the invocation of a version of print().

ps -> print();

This invokes student::print(). It is pointing at the object s of type student.
ps = pgs = &gs;

This multiple assignment statement has both pointers pointing at an object of type grad_student. The assignment to ps involves an implicit conversion.
ps -> print();

This again invokes student::print(). The fact that this pointer is pointing at a grad_student object gs is not relevant.
pgs -> print();

This invokes grad_student::print(). The variable pgs is of type pointer to grad_student and, when invoked with an object of this type, selects a member function from this class.