Iimplicit type conversion within class hierarchies, which occurs in the context
of assignments and function calls.
In addition, explicit type casting in class hierarchies is
discussed, in particular, upcasting and downcasting.
Converting To Base Classes
Example for implicit conversion
Implicit Conversion
If a class is derived from another class by public inheritance, the derived class assumes the
characteristics and features of the base class. Objects of the derived class
type then become special objects of the base class, just
like an automobile is a special type of vehicle.
You can utilize the is relationship when
handling objects. It is possible to assign an object of a derived class to an
object of the base class. This causes an implicit type
conversion to a base class type.
The base class thus becomes a generic term for multiple
special cases. Given that the classes PassCar and Truck were derived from the Car
class, objects of the PassCar or Truck type can always be managed like objects of Car type.
Assignments
Implicit type conversion in class hierarchies occurs in
assignments to
-
base class objects
-
pointers or references to the base class.
Function Calls
Additionally, a similar kind of implicit type conversion
takes place for the arguments of function calls.
Given the function compare() with the
following prototype
Example:
bool compare( Car& , Car& );
and two objects of the derived PassCar
class type, beetle and miata,
the following statement is valid
Example:
compare( beetle, miata);
The compiler performs implicit type conversion for the arguments
beetle and miata, converting
them to the parameter type, that is, to a reference to the base class Car.
Type conversion for arguments used in function calls is
similar to the type conversion that occurs in assignments, as shown in the
following section.
0 Comments