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.
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 answerHide 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
operatorfollowed 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
| Feature | How it is done |
|---|---|
int to Number | Via constructor Number(int v) - implicit conversion |
Number to int | Via conversion operator operator int() |
+ overloading | Number operator+(const Number& obj) |
== overloading | bool operator==(const Number& obj) |
Number n1 = x;calls the constructorNumber(int v), convertinginttoNumber.int result = n4;callsoperator int(), convertingNumbertoint.n1 + n2callsoperator+, returning a newNumberobject with the sum.n1 == n3callsoperator==, returningtrueif values are equal.
2081 · 5 marks
What are the purposes of operator overloading? Address the problem in multiple inheritance. [5]
Show solved answerHide 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:
-
Readability and Natural Syntax Allows objects to be used with operators in a natural, intuitive way. For example:
c3 = c1 + c2for complex number objects instead ofc3 = c1.add(c2). -
Code Simplicity Reduces the need for verbose function calls, making code cleaner and easier to maintain.
-
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.
-
Consistency Provides consistent interface for user-defined types similar to built-in types, so the same operator behaves logically across different data types.
-
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
| Problem | Cause | Solution |
|---|---|---|
| Ambiguity | Same name in multiple base classes | Scope resolution (::) |
| Diamond Problem | Common base class inherited twice | Virtual 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.
2080 · 10 marks
What is operator overloading? Write a complete C++ program to overload + operator to add two objects of class 'Time'.[10]
2080.1 · 5 marks
What is operator overloading? Explain with an example. [5]
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]
Type conversion
2081 · 5 marks
How do you convert basic data type to user defined data type? Explain. [5]
2078 · 5 marks
Lost out various type conversion techniques? Explain basic to user-defined type conversion with example. [5]
0 · 5 marks
Write a program to convert floating point value to object of distance class with data members feet and inch. [5]
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]
Make Unit 7 stick
Practice BIT153 with flashcards & quizzes