ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCOMP2111Operator Overloading
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    COMP2111

    Object Oriented Programming

    Progress0 / 23 done
    Topics23
    1Introduction to object oriented design2History and advantages of object oriented design3Introduction to object oriented programming concepts4Classes and objects5Data encapsulation6Constructors and destructors7Access modifiers8Const vs non-const functions9Static data members & functions10Function overloading11Operator overloading12Identification of classes and their relationships13Composition and aggregation14Inheritance15Multiple inheritance16Polymorphism17Abstract classes and interfaces18Generic programming concepts19Function & class templates20Standard template library21Object streams22Data and object serialization using object streams23Exception handling
    6 min read
    Topic 11 of 23
    Topic Study Note Illustration
    11

    Operator overloading

    Operator Overloading in C++

    Operator Overloading in C++

    Operator overloading is a feature in C++ that allows you to define how operators (like +, -, *, ==, etc.) behave when they are used with user-defined data types (classes). This allows you to use operators with objects in a natural and intuitive way, similar to how they work with built-in data types.


    Why Use Operator Overloading?

    1. Enhanced readability: Allows you to use familiar operators like + and - on custom data types, making your code more intuitive and easier to understand.
    2. Code reusability: Helps extend the functionality of built-in operators to work with user-defined classes without needing to write custom functions.
    3. Cleaner code: Makes code more concise and eliminates the need for function calls when working with objects.

    Key Points to Remember:

    1. You cannot change the meaning of built-in operators. You can only redefine them for user-defined types (like classes).
    2. Operator overloading is optional. You should overload operators only when it makes sense for your class and improves clarity.
    3. Overloaded operators must follow specific syntax.

    Basic Syntax for Operator Overloading:

    The syntax for overloading an operator involves defining a special function inside the class that uses the keyword operator followed by the symbol of the operator being overloaded.

    returnType operator symbol (parameter list) {
        // implementation
    }
    

    Example: Overloading the + Operator for a Complex Number Class

    Let’s take the example of a class Complex where we want to overload the + operator to add two complex numbers.

    Code Example:

    #include <iostream>
    using namespace std;
    
    class Complex {
    private:
        int real, imag;
    
    public:
        // Constructor to initialize complex numbers
        Complex(int r, int i) : real(r), imag(i) {}
    
        // Overloading the + operator to add two complex numbers
        Complex operator + (const Complex& obj) {
            Complex temp(0, 0);
            temp.real = real + obj.real;  // Add real parts
            temp.imag = imag + obj.imag;  // Add imaginary parts
            return temp;  // Return the sum of complex numbers
        }
    
        // Function to display the complex number
        void display() {
            cout << real << " + " << imag << "i" << endl;
        }
    };
    
    int main() {
        Complex num1(3, 4), num2(1, 2);
        Complex sum = num1 + num2;  // Using overloaded + operator
        sum.display();  // Output: 4 + 6i
        return 0;
    }
    

    Explanation:

    • We have a Complex class with two private data members: real and imag (real and imaginary parts of the complex number).
    • The + operator is overloaded using the syntax operator + to add the real and imaginary parts of two complex numbers.
    • The main function demonstrates the usage of the overloaded + operator, and the result is displayed using the display() function.

    Types of Operators You Can Overload

    1. Arithmetic Operators: +, -, *, /, %, etc.

      • Overloaded to perform arithmetic operations on objects.
      Complex operator - (const Complex& obj);  // Overload subtraction
      
    2. Comparison Operators: ==, !=, <, >, <=, >=

      • Overloaded to compare objects.
      bool operator == (const Complex& obj);  // Overload equality check
      
    3. Assignment Operator: =

      • Overloaded to assign one object to another.
      Complex& operator = (const Complex& obj);
      
    4. Increment and Decrement Operators: ++, --

      • Overloaded to increment or decrement an object.
      Complex operator ++ ();  // Pre-increment
      Complex operator ++ (int);  // Post-increment
      
    5. Stream Insertion and Extraction Operators: <<, >>

      • Overloaded to work with input and output streams for user-defined types.
      friend ostream& operator << (ostream& out, const Complex& obj);
      friend istream& operator >> (istream& in, Complex& obj);
      

    Overloading the Assignment Operator

    When you overload the assignment operator =, it's important to handle memory management properly, especially if the class involves dynamic memory allocation (using new or delete).

    Example:

    class Complex {
    private:
        int* real;
        int* imag;
    
    public:
        // Constructor
        Complex(int r, int i) {
            real = new int(r);
            imag = new int(i);
        }
    
        // Copy constructor
        Complex(const Complex& obj) {
            real = new int(*obj.real);
            imag = new int(*obj.imag);
        }
    
        // Assignment operator overloading
        Complex& operator = (const Complex& obj) {
            if (this != &obj) {
                *real = *obj.real;
                *imag = *obj.imag;
            }
            return *this;
        }
    
        // Destructor
        ~Complex() {
            delete real;
            delete imag;
        }
    };
    

    In this example, we overload the assignment operator to ensure that when one Complex object is assigned to another, it properly copies the data without causing memory issues (like shallow copying).


    Important Considerations

    1. Overloading the = Operator:

      • If your class dynamically allocates memory, the default assignment operator may not be sufficient. You will need to overload the = operator to manage memory properly (deep copying).
    2. Overloading [] (Array Subscript):

      • This operator is often overloaded to allow access to individual elements of an object, such as a matrix class.
      int& operator [] (int index) {
          // return the element at the given index
      }
      
    3. Friend Function for Overloading:

      • In some cases, the operator might need to access private members of the class. For such cases, you can declare the operator function as a friend function of the class.

    Summary:

    • Operator overloading allows you to redefine how operators work with objects of user-defined classes.
    • It makes your code cleaner, more readable, and intuitive by allowing you to use familiar operators like +, -, etc., with custom classes.
    • Important operators you might overload include arithmetic operators, comparison operators, assignment operators, and stream insertion/extraction operators.
    • Caution: Be mindful of managing resources, especially with dynamic memory allocation, when overloading operators like =.
    ← Previous topic 10
    Function overloading
    Next topic 12 →
    Identification of classes and their relationships

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    6mremaining
    968words
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Object Oriented Programming