Software Development Exam  >  Software Development Notes  >  DSA in C++  >  Operator Overloading in C++

Operator Overloading in C++ | DSA in C++ - Software Development PDF Download

Introduction 

In the world of programming, C++ is a powerful and versatile language that allows developers to create complex and efficient programs. One of the features that make C++ stand out is its ability to overload operators. Operator overloading enables us to redefine the behavior of built-in operators to work with user-defined data types.
In this article, we will explore the concept of operator overloading in C++, understand its significance, and learn how to implement it. We will also provide multiple examples and simple code snippets to illustrate each context of the information we provide.

What is Operator Overloading?

Operator overloading, as the name suggests, allows us to redefine the operation of an operator. In C++, operators like +, -, *, /, etc., have predefined behaviors for built-in data types. However, by overloading these operators, we can make them work with our own custom data types.
For example, imagine you have created a class called 'Vector' to represent mathematical vectors, and you want to be able to add two 'Vector' objects using the + operator. By overloading the + operator, you can define how this operation should be performed on 'Vector' objects.

Syntax for Operator Overloading

Operator overloading is achieved by creating special member functions called operator functions. These functions are named with the keyword "operator" followed by the operator symbol we want to overload.
The general syntax for an operator function is:

return_type operator@ (parameters) {

    // Code to define the behavior of the operator

}

Here, '@' represents the operator symbol we want to overload.

Example 1: Overloading the + Operator

Let's start with a simple example of overloading the + operator for our 'Vector' class. Here's how the code would look:

#include <iostream>


class Vector {

private:

    int x, y;


public:

    Vector(int x, int y) {

        this->x = x;

        this->y = y;

    }


    Vector operator+(const Vector& v) {

        Vector result(x + v.x, y + v.y);

        return result;

    }


    void display() {

        std::cout << "x = " << x << ", y = " << y << std::endl;

    }

};


int main() {

    Vector v1(2, 3);

    Vector v2(4, 6);

    Vector sum = v1 + v2;


    sum.display();


    return 0;

}

Code Explanation:

  • We define a class called 'Vector' with two private data members, 'x' and 'y', representing the vector's coordinates.
  • Inside the class, we define the 'operator'+ function. It takes a constant reference to another 'Vector' object as a parameter and returns a 'Vector' object.
  • In the 'operator+' function, we create a new 'Vector' object called 'result', where we add the corresponding coordinates of the current vector ('this') and the passed vector ('v').
  • Finally, in the 'main' function, we create two 'Vector' objects, 'v1' and 'v2'. We then add them using the + operator, storing the result in the 'sum' variable. We call the 'display' function on 'sum' to print the result.

Output:

x = 6, y = 9

In this example, we have successfully overloaded the + operator to perform vector addition. The result is a new Vector object with the coordinates (6, 9).

Example 2: Overloading the << Operator

We can also overload the stream insertion operator (<<) to provide a custom representation of our objects when using the 'cout' stream. Let's see how this can be done:

#include <iostream>


class Complex {

private:

    double real;

    double imaginary;


public:

    Complex(double real, double imaginary) {

        this->real = real;

        this->imaginary = imaginary;

    }


    friend std::ostream& operator<<(std::ostream& out, const Complex& c) {

        out << c.real << " + " << c.imaginary << "i";

        return out;

    }

};


int main() {

    Complex c(3.5, 2.1);

    std::cout << c << std::endl;


    return 0;

}

Code Explanation:

  • We define a class called 'Complex' to represent complex numbers. It has two private data members, 'real' and 'imaginary'.
  • Inside the class, we declare the 'operator<<' function as a friend function. It takes a reference to the 'ostream' object ('out') and a constant reference to the 'Complex' object ('c') as parameters. It returns a reference to the 'ostream' object.
  • In the 'operator<<' function, we use the 'out' object to print the complex number in the desired format.
  • In the 'main' function, we create a 'Complex' object called 'c' and output it using the 'cout' stream.

Output:

3.5 + 2.1i

Here, we have successfully overloaded the << operator to provide a custom representation of the 'Complex' object when using the 'cout' stream.

Sample Problems

Now that we have learned the basics of operator overloading, let's tackle a few sample problems to solidify our understanding:

Problem 1: Create a class called 'Box' that represents a rectangular box. Implement the necessary operator overloads (+, -, *, and <<) to perform addition, subtraction, multiplication, and display the 'Box' object respectively.

#include <iostream>


class Box {

private:

    int length;

    int width;

    int height;


public:

    Box(int length, int width, int height) {

        this->length = length;

        this->width = width;

        this->height = height;

    }


    Box operator+(const Box& b) {

        Box result(length + b.length, width + b.width, height + b.height);

        return result;

    }


    Box operator-(const Box& b) {

        Box result(length - b.length, width - b.width, height - b.height);

        return result;

    }


    Box operator*(const Box& b) {

        Box result(length * b.length, width * b.width, height * b.height);

        return result;

    }


    friend std::ostream& operator<<(std::ostream& out, const Box& b) {

        out << "Length: " << b.length << ", Width: " << b.width << ", Height: " << b.height;

        return out;

    }

};


int main() {

    Box box1(3, 4, 5);

    Box box2(1, 2, 3);


    Box sum = box1 + box2;

    Box difference = box1 - box2;

    Box product = box1 * box2;


    std::cout << "Sum: " << sum << std::endl;

    std::cout << "Difference: " << difference << std::endl;

    std::cout << "Product: " << product << std::endl;


    return 0;

}

Output:

Sum: Length: 4, Width: 6, Height: 8

Difference: Length: 2, Width: 2, Height: 2

Product: Length: 3, Width: 8, Height: 15

In this problem, we have created a 'Box' class and overloaded the +, -, *, and << operators. We then used these operators to perform addition, subtraction, multiplication, and display the 'Box' objects.

Problem 2: Create a class called 'String' to represent a string of characters. Implement the necessary operator overloads (+, ==, and <<) to perform concatenation, comparison, and display the 'String' object respectively.

#include <iostream>

#include <cstring>


class String {

private:

    char* data;


public:

    String(const char* str) {

        int length = std::strlen(str);

        data = new char[length + 1];

        std::strcpy(data, str);

    }


    String operator+(const String& other) {

        int newLength = std::strlen(data) + std::strlen(other.data);

        char* newData = new char[newLength + 1];

        std::strcpy(newData, data);

        std::strcat(newData, other.data);

        String result(newData);

        delete[] newData;

        return result;

    }


    bool operator==(const String& other) {

        return (std::strcmp(data, other.data) == 0);

    }


    friend std::ostream& operator<<(std::ostream& out, const String& s) {

        out << s.data;

        return out;

    }

};


int main() {

    String s1("Hello");

    String s2(" World!");


    String concat = s1 + s2;

    bool isEqual = (s1 == s2);


    std::cout << "Concatenation: " << concat << std::endl;

    std::cout << "Equality: " << (isEqual ? "True" : "False") << std::endl;


    return 0;

}

Output:

Concatenation: Hello World!

Equality: False

In this problem, we have created a 'String' class and overloaded the +, ==, and << operators. We then used these operators to perform concatenation, comparison, and display the 'String' objects.

Conclusion

Operator overloading in C++ allows us to redefine the behavior of operators for user-defined types. It provides flexibility and expressiveness, making our code more intuitive and readable. In this article, we covered the basics of operator overloading, including the syntax, examples, and sample problems.
By mastering the concept of operator overloading, you can unlock the full potential of C++ and write elegant and efficient code.

The document Operator Overloading in C++ | DSA in C++ - Software Development is a part of the Software Development Course DSA in C++.
All you need of Software Development at this link: Software Development
153 videos|115 docs|24 tests

Top Courses for Software Development

153 videos|115 docs|24 tests
Download as PDF
Explore Courses for Software Development exam

Top Courses for Software Development

Signup for Free!
Signup to see your scores go up within 7 days! Learn & Practice with 1000+ FREE Notes, Videos & Tests.
10M+ students study on EduRev
Related Searches

past year papers

,

video lectures

,

Summary

,

practice quizzes

,

Sample Paper

,

MCQs

,

Operator Overloading in C++ | DSA in C++ - Software Development

,

ppt

,

Semester Notes

,

pdf

,

Exam

,

Important questions

,

Extra Questions

,

Free

,

Operator Overloading in C++ | DSA in C++ - Software Development

,

Previous Year Questions with Solutions

,

shortcuts and tricks

,

Operator Overloading in C++ | DSA in C++ - Software Development

,

Viva Questions

,

study material

,

Objective type Questions

,

mock tests for examination

;