C++ , type Compatibility In Inheritance , derived class pointer can be assigned to base pointer
Автор: RioProfessor Liu
Загружено: 2021-05-11
Просмотров: 268
Описание:
Certain type compatibility relationships hold among different classes in an inheritance hierarchy. Because objects in an inheritance hierarchy are commonly accessed through pointers, we state these rules in terms of pointers:
A derived class pointer can always be assigned to a base class pointer. This means that base class pointers can point to derived class objects.
A type cast is required to perform the opposite assignment of a base class pointer to a derived class pointer. An error may result at run time if the base class pointer does not actually point to a derived class object.
In this section of code, the new operator returns a pointer to the derived class TFaculty, which is assigned to the base class pointer ptp. The base class pointer ptp is then assigned to ptf using a type cast.
In general, a pointer to a base class that actually points to a derived class object must first be appropriately cast before the additional features of the derived class can be used.
A derived class may override member functions that are defined in its base class. When a pointer to a base class is being used to access a member function that has been overridden by the derived class, the default C++ behavior is to use the version of the function that is defined in the class of the pointer rather than in the class of the object. For example, the code
Person *pP = new TFaculty("Indiana Jones", ARCHEOLOGY);
sets pP, which is a pointer to the base class Person, to point to a TFaculty object. Note that TFaculty overrides the getName function defined in Person. In executing the statement
Повторяем попытку...
Доступные форматы для скачивания:
Скачать видео
-
Информация по загрузке: