7 Operator Overloading And Type Conversion

Object Oriented Programming · Unit 7

Operator Overloading and Type Conversion

Exam-focused notes for Operator Overloading and Type Conversion (Object Oriented Programming, BIT153): what the TU syllabus asks and how it has actually been tested, with 9 solved past questions from this unit.

Operator Overloading and Type Conversion in short

Operator overloading lets us give the usual operators a meaning for our own classes. Type conversion lets values of one type change into another, including class types.

Operator Overloading and Type Conversion: notes

Operator overloading definition and purposes

Operator overloading is giving an existing operator an extra meaning for user-defined types. It is a form of compile-time polymorphism. The syntax uses the keyword operator:

return_type operator symbol (arguments) { ... }

Purposes:

  • Makes code for objects as natural as for built-in types, such as c3 = c1 + c2.
  • Improves readability.
  • The meaning of the operator for basic types does not change.

Operators that cannot be overloaded: :: (scope), . (member access), .*, ?: (ternary) and sizeof. We cannot create new operators or change precedence.

A member function overload of a binary operator takes one argument (the right operand). A unary operator takes none. A friend function takes one more argument in each case.

Overloading arithmetic operators

class Complex {
    int re, im;
public:
    Complex(int r = 0, int i = 0) { re = r; im = i; }
    Complex operator+(Complex c) {
        return Complex(re + c.re, im + c.im);
    }
    Complex operator-(Complex c) {
        return Complex(re - c.re, im - c.im);
    }
    void show() { cout << re << "+" << im << "i\n"; }
};

int main() {
    Complex a(2, 3), b(4, 5);
    Complex c = a + b;     // a.operator+(b)
    c.show();              // 6+8i
}

In a + b, the object a calls the function and b is the argument.

What this unit covers

  • Operator overloading definition and purposes
  • Overloading arithmetic operators
  • Overloading comparison operators
  • Overloading unary operators: pre-increment and post-increment
  • Type conversion: basic to user-defined
  • Type conversion: user-defined to basic
  • Conversion between objects of different classes

Operator overloading definition and purposes

2082 · 10 marks

Explain operator overloading with example?Write a C++ class Number to store an integer. Overload addition (+) and comparison (==) operators, and show conversion between int and Number. Write a program to perform these operations.[2+8]

Show solved answer

Operator Overloading in C++

(a) Explanation of Operator Overloading

Operator overloading is a feature of C++ that allows existing operators (such as +, -, ==, <<, etc.) to be given additional meaning when applied to user-defined types (classes/objects). It enables objects of a class to be used with operators in a natural, intuitive way, just like built-in data types.

Key Points:

  • The keyword operator followed by the operator symbol is used to define the overloaded function.
  • Syntax: return_type operator symbol (parameter list)
  • It does not change the precedence or associativity of operators.
  • At least one operand must be a user-defined type.

(b) C++ Program

#include <iostream>
using namespace std;

class Number {
private:
    int value;

public:
    // Default constructor
    Number() {
        value = 0;
    }

    // Parameterized constructor
    Number(int v) {
        value = v;
    }

    // -----------------------------------------------
    // Conversion: int to Number (done via constructor)
    // Conversion: Number to int (conversion operator)
    // -----------------------------------------------
    operator int() {
        return value;
    }

    // -----------------------------------------------
    // Overload addition operator (+)
    // Number + Number
    // -----------------------------------------------
    Number operator+(const Number& obj) {
        Number temp;
        temp.value = this->value + obj.value;
        return temp;
    }

    // -----------------------------------------------
    // Overload comparison operator (==)
    // -----------------------------------------------
    bool operator==(const Number& obj) {
        if (this->value == obj.value)
            return true;
        else
            return false;
    }

    // Display function
    void display() {
        cout << "Value = " << value << endl;
    }
};

// -----------------------------------------------
// Main function to demonstrate operations
// -----------------------------------------------
int main() {
    // int to Number conversion (via constructor)
    int x = 10;
    Number n1 = x;          // implicit conversion: int -> Number
    Number n2(20);          // direct initialization
    Number n3 = 10;         // implicit conversion: int -> Number

    cout << "n1: "; n1.display();
    cout << "n2: "; n2.display();
    cout << "n3: "; n3.display();

    // Addition operator overloading
    Number n4 = n1 + n2;    // calls operator+
    cout << "\nAfter n4 = n1 + n2:" << endl;
    cout << "n4: "; n4.display();

    // Comparison operator overloading
    cout << "\nComparing n1 and n3 (both have value 10):" << endl;
    if (n1 == n3)
        cout << "n1 == n3: TRUE" << endl;
    else
        cout << "n1 == n3: FALSE" << endl;

    cout << "\nComparing n1 and n2:" << endl;
    if (n1 == n2)
        cout << "n1 == n2: TRUE" << endl;
    else
        cout << "n1 == n2: FALSE" << endl;

    // Number to int conversion (via conversion operator)
    int result = n4;        // implicit conversion: Number -> int
    cout << "\nNumber to int conversion (n4 -> int): " << result << endl;

    return 0;
}

Output

n1: Value = 10
n2: Value = 20
n3: Value = 10

After n4 = n1 + n2:
n4: Value = 30

Comparing n1 and n3 (both have value 10):
n1 == n3: TRUE

Comparing n1 and n2:
n1 == n2: FALSE

Number to int conversion (n4 -> int): 30

Explanation of Key Concepts Used

FeatureHow it is done
int to NumberVia constructor Number(int v) - implicit conversion
Number to intVia conversion operator operator int()
+ overloadingNumber operator+(const Number& obj)
== overloadingbool operator==(const Number& obj)
  • Number n1 = x; calls the constructor Number(int v), converting int to Number.
  • int result = n4; calls operator int(), converting Number to int.
  • n1 + n2 calls operator+, returning a new Number object with the sum.
  • n1 == n3 calls operator==, returning true if values are equal.
Open this answer on its own page →

2081 · 5 marks

What are the purposes of operator overloading? Address the problem in multiple inheritance. [5]

Show solved answer

Operator Overloading and Problems in Multiple Inheritance


Purposes of Operator Overloading

Operator overloading allows existing C++ operators to be given additional meanings when applied to user-defined data types (classes). The main purposes are:

  1. Readability and Natural Syntax Allows objects to be used with operators in a natural, intuitive way. For example: c3 = c1 + c2 for complex number objects instead of c3 = c1.add(c2).

  2. Code Simplicity Reduces the need for verbose function calls, making code cleaner and easier to maintain.

  3. Extensibility of Built-in Operators Extends the capability of built-in operators to work with user-defined types without changing the original meaning for primitive types.

  4. Consistency Provides consistent interface for user-defined types similar to built-in types, so the same operator behaves logically across different data types.

  5. Supports Data Abstraction Helps in implementing abstract data types (ADT) more effectively by hiding implementation details behind familiar operator syntax.


Problems in Multiple Inheritance

Multiple inheritance allows a derived class to inherit from more than one base class. However, it introduces several problems:

1. Ambiguity Problem (Name Conflict)

When two or more base classes have a member function or data member with the same name, the derived class becomes ambiguous about which one to use.

Example:

class A {
public:
    void show() { cout << "Class A"; }
};

class B {
public:
    void show() { cout << "Class B"; }
};

class C : public A, public B {
    // Ambiguous: which show() to call?
};

int main() {
    C obj;
    obj.show();  // ERROR: ambiguous
}

Solution: Use scope resolution operator:

obj.A::show();  // calls A's show()
obj.B::show();  // calls B's show()

2. Diamond Problem (Duplicate Inheritance / Deadly Diamond)

When a class inherits from two classes that both inherit from a common base class, the derived class ends up with two copies of the base class members, causing ambiguity and redundancy.

        A
       / \
      B   C
       \ /
        D

Example:

class A {
public:
    int x;
};

class B : public A { };
class C : public A { };

class D : public B, public C {
    // D has two copies of A::x
    // Ambiguous: B::x or C::x?
};

Solution: Use virtual base class to ensure only one copy of the base class is inherited.

class B : virtual public A { };
class C : virtual public A { };

class D : public B, public C {
    // Now only ONE copy of A exists
};

Summary Table

ProblemCauseSolution
AmbiguitySame name in multiple base classesScope resolution (::)
Diamond ProblemCommon base class inherited twiceVirtual base class (virtual)

Note: These are standard C++ OOP concepts. No specific curriculum notes were available, so this answer is based on standard CS knowledge consistent with TU BSc CSIT syllabus.

Open this answer on its own page →

2080 · 10 marks

What is operator overloading? Write a complete C++ program to overload + operator to add two objects of class 'Time'.[10]

Operator overloading is a feature of C++ that allows the programmer to redefine or extend the meaning of existing operators (such as +, -, , ==, etc.) for user-defined data types (classes and structures). It enables objects of a class to be used with standard operators in a natural and intuitive ...

Open this answer on its own page →

2080.1 · 5 marks

What is operator overloading? Explain with an example. [5]

Operator overloading is a compile-time polymorphism feature in C++ that allows existing operators (such as +, -, , ==, etc.) to be given additional meaning or redefined for user-defined data types (classes/structures), while keeping their original functionality for built-in types intact. In simpl...

Open this answer on its own page →

Overloading unary operators

2081 · 5 marks

Write a program to create a class named STUDENT with data member age, then overload the unary operator (++) to increment the age of any object of above class. [5]

Unary operator overloading allows operators like ++, --, - etc. to work with user-defined class objects. The operator function is defined inside the class using the keyword operator followed by the operator symbol. --- --- --- Step Description ------------------- STUDENT s1(20) Object s1 is creat...

Open this answer on its own page →

Type conversion

2081 · 5 marks

How do you convert basic data type to user defined data type? Explain. [5]

In C++, converting a basic (built-in) data type (such as int, float, double, char) to a user-defined data type (such as a class or struct) is achieved using a special constructor called a conversion constructor. --- A conversion constructor is a single-argument constructor defined inside a class ...

Open this answer on its own page →

2078 · 5 marks

Lost out various type conversion techniques? Explain basic to user-defined type conversion with example. [5]

Type conversion refers to the process of converting a value from one data type to another. C++ supports several type conversion techniques. --- - Done automatically by the compiler. - Converts lower data type to higher data type (no data loss). --- - Done manually by the programmer using cast ope...

Open this answer on its own page →

0 · 5 marks

Write a program to convert floating point value to object of distance class with data members feet and inch. [5]

This problem uses a conversion constructor (or single-argument constructor) to convert a floating point value (representing total inches) into a Distance object with feet and inches data members. Note: Reference notes were not available for this topic; the answer is based on standard C++ type con...

Open this answer on its own page →

Conversion between objects of different classes

2080.1 · 10 marks

Why data conversion is needed?How Conversion between objects of different classes is carried out.Write a program containing classes Kilogram and Gram to convert Gram to Kilogram. (1 Kilogram = 1000 grams)[2+4+4]

Data conversion (type conversion) is needed in programming for the following reasons: - Compatibility between different types: When we perform operations between variables of different data types (e.g., int and float), conversion is necessary to make them compatible. - Meaningful computation: Dif...

Open this answer on its own page →