Lesson 7 | A derived class |
Objective | Typing conversions and visibility |
Reference Typing Conversions Visibility
Reference to the derived class is implicitly converted
Describe how a reference to the derived class may be implicitly converted to a reference to the public base class.
An object of the derived class can in many ways be treated as if it were the base class type when the object is manipulated through pointers and references. A pointer whose type is a pointer to the base class can point to objects that have the derived class type.
A reference to the derived class may be implicitly converted to a reference to the public base class. The opposite conversion, from base class reference to the derived class reference, must be explicit. For example:
student s("Mae Pohl", 100, 3.425, fresh);
grad_student gs("Morris Pohl", 200, 3.2564, grad, ta, "Pharmacy", "Retail Pharmacies");
student& rs = gs; // OK: every grad_student is a student
grad_student& ps = s; // Error: not every student is a grad_student
ps = static_cast<grad_student> (s); // this works
In this case, the variable rs is a reference to student. The base class of grad_student is student.
Therefore, this reference conversion is appropriate. An attempt to perform an implicit conversion from student type to grad_student type produces an error.
Typing Conversions - Quiz
Click the Quiz link below to take a brief multiple-choice quiz on constructors and typing conversions for base and derived classes.
Typing Conversions - Quiz