PPT9_Polymorphism_TypeConversion
PPT9_Polymorphism_TypeConversion
Poly-morphism
(Type Conversion)
1
What is Type Conversions?
• When constants and variables of different types are mixed in an
expression, C++ applies automatic type conversion to the operand
as per certain rules. Similarly, an assignment operator also causes
the automatic type conversion.
• The type conversions are automatic as long as the data types
involved are built-in types.
Using constructor
Using Operator Overloading
Example (Using Constructor)
#include <iostream> int main() {
using namespace std; int distance;
cout<<"Enter distance in meters";
class Distance { cin>>distance;
private: Distance d = 5; // Implicit conversion from int to Distance
int feet;
float inches; d.display(); // Output: 16 feet 4.12 inches
public: return 0;
// Constructor for basic to user-defined conversion }
Distance(int meters) {
feet = meters * 3.281; // Convert meters to feet During type conversion using the
inches = (meters * 3.281 - feet) * 12; constructor we can pass only one
} argument and we can do type
conversion at the type of
void display() { initialization only.
cout << feet << " feet " << inches << " inches" << endl;
}
};
Using Operator Overloading
• Type conversion from basic to class type can also be done by
operator overloading.
operator typename( )
{
//Function statements
}
Continued…
• The conversion function should satisfy the following condition: