Object Oriented Programming · Unit 4 · 7 hrs
Operator Overloading
Exam-focused notes for Operator Overloading (Object Oriented Programming, CSC166): what the TU syllabus asks and how it has actually been tested, with 8 solved past questions from this unit.
Operator Overloading in short
This unit covers how C++ lets existing operators take on new, user defined meanings for class types, the rules that limit what can be overloaded, how an operator is written as a member or friend function, worked examples of unary and binary operator overloading, and the four cases of data conversion that involve a class type.
What this unit covers
- Fundamental of operator overloading
- Restriction on operator overloading
- Operator functions as a class members
- Overloading unary and binary operator
- Data Conversion (basic to basic, basic to user-defined, user-defined to basic, user-defined to user-defined)
Operator functions as a class members
2080 · 5 marks
Create a class named Point with data members x(int) and y(int). Add operator overloading to find the Euclidean distance between two points. [5]
Fundamental of operator overloading
2079 · 10 marks
What is operator overloading? Why it is necessary to overload and operator? Write a program for overloading comparison operators.[10]
2076 · 10 marks
Explain the concept of operator overloading? List the operators that cannot be overloaded. Write programs to add two object of distance class with data members feet and inch by using member function and friend function.[10]
Data Conversion
2079 · 5 marks
What are possible data conversion types? Write a program to show basis to user defined conversion. [5]
Show solved answerHide answer
Data Conversion Types and User-Defined Conversion
Possible Data Conversion Types
In C++, there are mainly two types of data conversion:
1. Implicit Conversion (Automatic Type Conversion)
- Done automatically by the compiler without any external trigger from the user.
- Takes place when there is more than one data type in an expression.
- All data types are upgraded to the largest data type present in the expression to avoid loss of data.
Example:
int a = 5;
float b = 2.5;
float result = a + b; // int 'a' is automatically converted to float
2. Explicit Conversion (User-Defined / Type Casting)
- Also called type casting.
- The user manually converts the data type of a value to a desired type.
- In C++, it can be done in two ways:
- Using C-style cast:
(type) expression - Using C++ cast operator:
type(expression)
- Using C-style cast:
Program to Show Basic to User-Defined Conversion
The following program demonstrates converting a basic (built-in) data type to a user-defined data type (class) using a constructor, and converting a user-defined type back to a basic type using a conversion function (operator overloading).
#include<iostream>
using namespace std;
// User-defined class
class Celsius {
float temperature;
public:
// Default constructor
Celsius() {
temperature = 0;
}
// Constructor for basic to user-defined conversion
// Converts float (basic type) to Celsius object (user-defined type)
Celsius(float t) {
temperature = t;
cout << "Basic to User-Defined Conversion: float -> Celsius object" << endl;
}
// Conversion function: user-defined to basic type
// Converts Celsius object to float (basic type)
operator float() {
cout << "User-Defined to Basic Conversion: Celsius object -> float" << endl;
return temperature;
}
void display() {
cout << "Temperature = " << temperature << " C" << endl;
}
};
int main() {
float temp = 36.6;
// Basic to User-Defined Conversion
// float is implicitly converted to Celsius object using constructor
Celsius c1 = temp;
c1.display();
// User-Defined to Basic Conversion
// Celsius object is converted to float using conversion function
float t2 = c1;
cout << "Converted back to float: " << t2 << endl;
// Explicit (user-defined) type casting
Celsius c2(98.4);
float t3 = (float) c2; // C-style explicit cast
cout << "Explicit cast result: " << t3 << endl;
return 0;
}
Output
Basic to User-Defined Conversion: float -> Celsius object
Temperature = 36.6 C
User-Defined to Basic Conversion: Celsius object -> float
Converted back to float: 36.6
Basic to User-Defined Conversion: float -> Celsius object
User-Defined to Basic Conversion: Celsius object -> float
Explicit cast result: 98.4
Summary Table
| Conversion Type | Direction | Mechanism Used |
|---|---|---|
| Basic to User-Defined | float -> class | Constructor with parameter |
| User-Defined to Basic | class -> float | Conversion function (operator float()) |
| Explicit (Type Casting) | Any -> Any | (type) or type() |
Note: The constructor enables basic-to-user-defined conversion, while the conversion operator (operator overloading) enables user-defined-to-basic conversion. Both together form the complete picture of user-defined type conversion in C++.
2078 · 10 marks
What is meant by type conversion? Define two way of converting one user defined data type (object) to another user defined object? Write a program that converts object of another distance class with data members feet and inch. (Assume 1m = 3.3 feet and 1cm = 0.4 inch)[10]
Show solved answerHide answer
Type Conversion in C++
Given
- Source class:
Meterwith data membersmeter(m) andcentimeter(cm). - Destination class:
Distancewith data membersfeetandinch. - Conversion factors:
- $1\ \text{m} = 3.3\ \text{feet}$
- $1\ \text{cm} = 0.4\ \text{inch}$
- Task: write a program converting an object of one class to a
Distanceobject; explain type conversion and two ways of converting between user-defined types.
No numeric input is missing. (The specific test values like $5\text{ m}, 50\text{ cm}$ are chosen for demonstration.)
Solution
1. What is Type Conversion?
Type conversion is the process of changing a value of one data type into another data type. For built-in types (e.g., int to float), the compiler performs conversions automatically. But for user-defined types (class objects), the compiler does not know the conversion rule, so the programmer must define it explicitly.
Three kinds exist:
- basic to class type
- class to basic type
- class to class type (the focus here)
2. Two Ways of Converting One User-Defined Object to Another
Method 1 - Constructor in the Destination class: A single-argument (conversion) constructor is written in the destination class taking a source object as argument.
class Destination {
public:
Destination(Source s) { /* extract and assign */ }
};
On Destination d = s; the compiler calls this constructor.
Method 2 - Overloaded Casting (Conversion) Operator in the Source class:
A conversion function operator Destination() is written in the source class.
class Source {
public:
operator Destination() { Destination t; /* fill t */ return t; }
};
On Destination d = s; the compiler calls this operator.
Rule: the conversion routine is placed in the destination class (constructor) or in the source class (operator function), never split.
3. Program (both methods)
#include <iostream>
using namespace std;
class Distance { // Destination class
float feet, inch;
public:
Distance(float f = 0, float i = 0) { feet = f; inch = i; }
void display() {
cout << "Feet : " << feet << " ft, Inch : " << inch << " in" << endl;
}
};
class Meter { // Source class
float meter, centimeter;
public:
Meter(float m = 0, float cm = 0) { meter = m; centimeter = cm; }
void display() {
cout << "Meter: " << meter << " m, cm: " << centimeter << " cm" << endl;
}
// Method 2: conversion (casting) operator in source class
operator Distance() {
// 1 m = 3.3 feet, 1 cm = 0.4 inch
return Distance(meter * 3.3f, centimeter * 0.4f);
}
};
int main() {
Meter m1(5, 50); // 5 m, 50 cm
m1.display();
Distance d1 = m1; // calls operator Distance()
d1.display();
return 0;
}
(Alternatively, Method 1 uses a Distance(Meter m) constructor with
feet = m.getMeter()*3.3; inch = m.getCentimeter()*0.4;.)
4. Verification of Calculation (for 5 m, 50 cm)
$$\text{feet} = 5 \times 3.3 = 16.5\ \text{ft}$$ $$\text{inch} = 50 \times 0.4 = 20.0\ \text{in}$$
Output:
Meter: 5 m, cm: 50 cm
Feet : 16.5 ft, Inch : 20 in
2075 · 10 marks
Explain the concept of user-defined to user-defined data concession with the conversion routine located in the destination class.[10]
2080.1 · 5 marks
Create two classes Rupee and Dollar respectively. Write conversion operator to convert between Rupee and Dollar assuming that 1 dollar equals 133 rupees. Write a main program that allows the user to enter an amount in either currency and then converts it to other currency and displays the result. [5]
Overloading unary and binary operator
2080.1 · 10 marks
Write a program to create a class named height with data members meter(int) and centimeter(int). Overload the binary + operator using friend function to add two heights.[10]
Make Unit 4 stick
Practice CSC166 with flashcards & quizzes