ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Object Oriented Programming
    COMP2111
    Progress0 / 23 topics
    Topics
    1. Introduction to object oriented design2. History and advantages of object oriented design3. Introduction to object oriented programming concepts4. Classes and objects5. Data encapsulation6. Constructors and destructors7. Access modifiers8. Const vs non-const functions9. Static data members & functions10. Function overloading11. Operator overloading12. Identification of classes and their relationships13. Composition and aggregation14. Inheritance15. Multiple inheritance16. Polymorphism17. Abstract classes and interfaces18. Generic programming concepts19. Function & class templates20. Standard template library21. Object streams22. Data and object serialization using object streams23. Exception handling
    COMP2111›Operator overloading
    Object Oriented ProgrammingTopic 11 of 23

    Operator overloading

    6 minread
    968words
    Intermediatelevel

    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 load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time6 min
      Word count968
      Code examples0
      DifficultyIntermediate