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 PortalCC-211Operator Overloading
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    CC-211

    Object Oriented Programming

    Progress0 / 24 done
    Topics24
    1History and Advantages
    2Terminology and Features3Classes and Objects4Data Encapsulation5Constructors and Destructors6Access Modifiers7Const vs Non-Const Functions8Static Data Members and Functions9Function Overloading10Operator Overloading11Identification of Classes and Their Relationships12Composition13Aggregation14Inheritance15Multiple Inheritances16Polymorphism17Abstract Classes18Interfaces19Generic Programming Concepts20Function Templates21Class Templates22Standard Template Library
    23Data and Object Serialization24Exception Handling
    8 min read
    Topic 10 of 24
    Topic Study Note Illustration
    10

    Operator Overloading

    Operator Overloading is a feature in C++ that allows you to redefine the behavior of operators (like + , - , * , == , etc.) for...

    Operator Overloading in C++

    Operator Overloading is a feature in C++ that allows you to redefine the behavior of operators (like +, -, *, ==, etc.) for user-defined types (e.g., classes). With operator overloading, you can give these operators new meanings when applied to objects of a class. It enables you to use operators intuitively with objects, making code more readable and expressive.

    Why Use Operator Overloading?

    1. Improved Readability: By overloading operators, you can use familiar syntax for operations involving user-defined types, like objects of a class.
    2. Intuitive Syntax: It allows you to define operations on custom types in a way that’s similar to built-in types.
    3. Consistency with Built-in Types: If you define a class that mimics a mathematical object (like complex numbers, vectors, or matrices), overloading operators ensures that the syntax is consistent with regular mathematical operations.

    How to Overload Operators

    To overload an operator, you define a special function (called an operator function) in the class. The syntax for overloading an operator is:

    returnType operator op (parameter_list);
    

    Where:

    • op is the operator being overloaded (e.g., +, -, =, etc.).
    • The parameter list specifies the types of arguments the operator will work with.

    General Syntax:

    class ClassName {
    public:
        returnType operator symbol (parameter_list);
    };
    

    Examples of Common Operator Overloading

    1. Overloading the + Operator

    Let's start with overloading the + operator to add two objects of a class. For example, let's consider a Point class that holds x and y coordinates.

    #include <iostream>
    using namespace std;
    
    class Point {
    private:
        int x, y;
        
    public:
        // Constructor to initialize the coordinates
        Point(int x = 0, int y = 0) : x(x), y(y) {}
    
        // Overload the '+' operator to add two Point objects
        Point operator + (const Point& p) {
            return Point(x + p.x, y + p.y);  // Return a new Point object
        }
    
        // Function to display the coordinates
        void display() const {
            cout << "Point(" << x << ", " << y << ")" << endl;
        }
    };
    
    int main() {
        Point p1(2, 3), p2(4, 5);
        Point p3 = p1 + p2;  // Calls the overloaded '+' operator
        p3.display();  // Output: Point(6, 8)
        
        return 0;
    }
    

    Explanation:

    • The operator+ function is overloaded to add two Point objects.
    • It returns a new Point object, whose x and y values are the sum of the corresponding values from the two objects being added.
    • The + operator can now be used intuitively to add two Point objects.

    2. Overloading the = (Assignment) Operator

    The assignment operator = can be overloaded to allow copying of objects. This is useful when dealing with dynamic memory or deep copying.

    #include <iostream>
    using namespace std;
    
    class Box {
    private:
        int length;
    
    public:
        // Constructor to initialize length
        Box(int len) : length(len) {}
    
        // Overload the assignment operator
        Box& operator = (const Box& b) {
            // Check for self-assignment
            if (this != &b) {
                length = b.length;
            }
            return *this;  // Return the current object
        }
    
        // Function to display the box's length
        void display() const {
            cout << "Length: " << length << endl;
        }
    };
    
    int main() {
        Box box1(10);
        Box box2(20);
    
        box2 = box1;  // Calls the overloaded '=' operator
        box2.display();  // Output: Length: 10
    
        return 0;
    }
    

    Explanation:

    • The operator= function is overloaded to copy the contents of one Box object into another.
    • The this pointer is used to check for self-assignment (i.e., when an object is assigned to itself).
    • The assignment operator returns a reference to the current object (*this) to allow chained assignments like box3 = box2 = box1;.

    3. Overloading the == Operator

    You can overload the == operator to compare objects of a class for equality. Here's an example:

    #include <iostream>
    using namespace std;
    
    class Person {
    private:
        string name;
        int age;
    
    public:
        // Constructor to initialize name and age
        Person(string name, int age) : name(name), age(age) {}
    
        // Overload the '==' operator to compare two Person objects
        bool operator == (const Person& p) {
            return (name == p.name && age == p.age);
        }
    
        // Function to display person's details
        void display() const {
            cout << name << " (" << age << " years)" << endl;
        }
    };
    
    int main() {
        Person person1("John", 30);
        Person person2("Alice", 25);
        Person person3("John", 30);
    
        if (person1 == person3) {  // Calls the overloaded '==' operator
            cout << "person1 and person3 are equal." << endl;
        } else {
            cout << "person1 and person3 are not equal." << endl;
        }
    
        return 0;
    }
    

    Explanation:

    • The operator== function is overloaded to compare two Person objects for equality based on their name and age.
    • The comparison is done using the == operator for the name and age member variables.
    • The result of the comparison is returned as a boolean value (true or false).

    Types of Operator Overloading

    1. Unary Operators: Operators that work with a single operand (e.g., ++, --, -, !, etc.)

      class Counter {
      private:
          int count;
      
      public:
          Counter() : count(0) {}
      
          // Overloading the pre-increment operator
          Counter& operator ++ () {
              ++count;
              return *this;
          }
      
          void display() const {
              cout << "Count: " << count << endl;
          }
      };
      
    2. Binary Operators: Operators that work with two operands (e.g., +, -, *, ==, etc.)

      // Already shown in the previous examples for operators like '+' and '=='
      
    3. Stream Operators (<<, >>): These are overloaded to handle input/output operations with objects.

      class Box {
      private:
          int length;
      
      public:
          Box(int len) : length(len) {}
      
          // Overloading the stream insertion operator (<<)
          friend ostream& operator << (ostream& out, const Box& b) {
              out << "Length: " << b.length;
              return out;
          }
      };
      
      int main() {
          Box box(10);
          cout << box << endl;  // Calls the overloaded << operator
          return 0;
      }
      
    4. Type Conversion Operators: You can overload operators to convert objects of one type to another.

      class Distance {
      private:
          int feet;
      
      public:
          Distance(int f) : feet(f) {}
      
          // Conversion operator to convert Distance to int
          operator int() {
              return feet;
          }
      };
      
      int main() {
          Distance d(5);
          int x = d;  // Implicit conversion to int
          cout << "Distance in feet: " << x << endl;  // Output: Distance in feet: 5
          return 0;
      }
      

    When Not to Overload Operators?

    1. Avoid overloading operators that confuse the meaning: For example, overloading the + operator to perform subtraction might confuse users of your class.
    2. Complexity: If operator overloading makes your code harder to understand or leads to ambiguity, it's better to avoid it.

    Summary

    • Operator Overloading allows you to redefine the behavior of operators for user-defined types.
    • It enables more intuitive and readable code, especially for mathematical and logical operations on objects.
    • C++ supports overloading both unary and binary operators, as well as stream insertion (<<) and extraction (>>) operators.
    • It’s important to use operator overloading judiciously to avoid confusion and maintain the readability of your code.
    ← Previous topic 9
    Function Overloading
    Next topic 11 →
    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%
    8mremaining
    1.3kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Object Oriented Programming