4 Operator Overloading

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.

Operator Overloading: notes

Fundamental of operator overloading

Operator overloading is a form of compile time polymorphism in which an existing operator is given an additional, user defined meaning when applied to objects of a class, without losing its original meaning for the built in types; the + operator overloaded to add two Complex objects can still be used, unchanged, to add two ints. Overloading extends only the semantics of an operator, that is, what it computes; the grammatical rules that govern it, the number of operands it takes, its precedence and its associativity, cannot be changed by overloading.

Restriction on operator overloading

A small set of operators cannot be overloaded in C++: the member access operators . and .*, the scope resolution operator ::, the sizeof operator, and the conditional (ternary) operator ?:. Every other operator, including assignment =, the comparison operators, and even the indexing operator [], is eligible for overloading.

Operator functions as a class members

To overload an operator, an operator function is written using the keyword operator followed by the operator's own symbol, and it is defined as either a member function or a friend function of the class. The choice affects how many arguments the function takes explicitly: a member operator function takes no explicit argument for a unary operator (the object it is called on supplies the operand implicitly through this) and only one explicit argument for a binary operator (the left hand operand is again implicit), while a friend operator function needs one explicit argument for a unary operator and two for a binary operator, since a friend function has no implicit object of its own.

return_type operator symbol(argument_list) {
    // task defined for the operator
}

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]

Operator overloading allows us to redefine the behavior of an operator for user-defined types (classes). Here, we overload the - operator (or a suitable operator) to compute the Euclidean distance between two Point objects. The Euclidean distance formula between two points P1(x1, y1) and P2(x2, y...

Open this answer on its own page →

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]

"The method of making operators to work for user defined class and having the ability to provide operators with a special user defined meaning is known as operator overloading." In simple terms, operator overloading allows us to redefine the behavior of existing C++ operators (such as +, -, ==, ,...

Open this answer on its own page →

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]

--- Operator overloading is a compile-time polymorphism feature in C++ that allows the programmer to redefine or extend the meaning of built-in operators (such as +, -, , ==, etc.) for user-defined data types (classes/objects). When an operator is overloaded, it performs a different operation dep...

Open this answer on its own page →

Data Conversion

2079 · 5 marks

What are possible data conversion types? Write a program to show basis to user defined conversion. [5]

Show solved 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)

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 TypeDirectionMechanism Used
Basic to User-Definedfloat -> classConstructor with parameter
User-Defined to Basicclass -> floatConversion 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++.

Open this answer on its own page →

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 answer

Type Conversion in C++

Given

  • Source class: Meter with data members meter (m) and centimeter (cm).
  • Destination class: Distance with data members feet and inch.
  • 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 Distance object; 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
Open this answer on its own page →

2075 · 10 marks

Explain the concept of user-defined to user-defined data concession with the conversion routine located in the destination class.[10]

In C++, type conversion refers to converting a value from one data type to another. When both the source and destination are user-defined data types (i.e., classes), a special conversion routine must be written., "classes are user-defined data types and behave like built-in types of a programming...

Open this answer on its own page →

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]

This problem uses type conversion between class objects using a conversion operator (casting operator) defined inside the source class. The conversion operator converts an object of one class type to another class type. Rate: 1 Dollar = 133 Rupees --- --- Case 1: Rupee to Dollar Case 2: Dollar to...

Open this answer on its own page →

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]

Binary Operator Overloading occurs when an operator works on two operands. When overloaded using a friend function, the function is not a member of the class but has access to all private and protected members of the class. A friend function takes both operands as explicit parameters (unlike memb...

Open this answer on its own page →