C++ / Object-Oriented Programming in C++

Operator Overloading in C++

This tutorial will cover operator overloading in C++. You'll learn how to define your own meanings for operators in your classes.

Tutorial 5 of 5 5 resources in this section

Section overview

5 resources

Covers OOP principles such as classes, objects, inheritance, and polymorphism.

Operator Overloading in C++

1. Introduction

In this tutorial, we'll explore operator overloading in C++.

Operator overloading allows you to redefine the way operators work with your classes. By the end of this tutorial, you will be able to overload various operators in C++, allowing you to create intuitive interfaces for your classes.

Prerequisites:
- Basic knowledge of C++
- Understanding of Classes and Objects in C++

2. Step-by-Step Guide

Operator overloading is a type of polymorphism in which an operator is overloaded to provide the special meaning to the user-defined data type. Operator overloading is used to overload or redefines most of the operators available in C++. It is used to perform operation on user-defined data type. For example '+' operator can be overloaded to perform addition on various data types, like for Integer, String(concatenation) etc.

All operators can be overloaded except :: (Scope Resolution Operator), .(Member Access Operator), .*(Member dereference Operator) and ?: (Ternary or Conditional Operator).

Syntax for Operator Overloading:
return_type class_name::operator op(argument_list)

3. Code Examples

Example 1: Overloading '+' Operator

class Complex {
   private:
      int real, imag;
   public:
      Complex(int r = 0, int i =0)  {real = r;   imag = i;}

      // This is automatically called when '+' is used with
      // between two Complex objects
      Complex operator + (Complex const &obj) {
         Complex res;
         res.real = real + obj.real;
         res.imag = imag + obj.imag;
         return res;
      }
      void print() { cout << real << " + i" << imag << endl; }
};

int main() {
   Complex c1(10, 5), c2(2, 4);
   Complex c3 = c1 + c2; // An example call to "operator+"
   c3.print();
}

In this code:
- We're defining a class named Complex.
- We're overloading the + operator to add two Complex objects.
- When c1 + c2 is executed, it calls the overloaded + operator, which returns a new Complex object.
- The expected output is 12 + i9.

Example 2: Overloading '<<' Operator

class Complex {
   private:
      int real, imag;
   public:
      Complex(int r = 0, int i =0)  {real = r;   imag = i;}

      friend ostream & operator << (ostream &out, const Complex &c) {
         out << c.real;
         out << "+i" << c.imag << endl;
         return out;
      }
};

int main() {
   Complex c1(10, 5);
   cout << c1;
}

In this code:
- We're overloading the << operator to print a Complex object.
- Since << is a binary operator, which requires two arguments, we make it a friend function to access private members.
- When cout << c1 is executed, the overloaded << operator is called.
- The expected output is 10 + i5.

4. Summary

In this tutorial, you've learned how to overload operators in C++. You can overload most of the operators available in C++ to work with your classes in a way that makes sense for your program.

Next steps for learning include:
- Overloading other operators like -, *, ==, !=, >, <, etc.
- Understanding the situations where operator overloading is beneficial.

Additional resources:
- C++ Operator Overloading Guidelines
- Cplusplus.com Operator Overloading

5. Practice Exercises

  1. Overload the - operator for the Complex class.
  2. Overload the * operator for the Complex class.
  3. Overload the == operator for the Complex class.

Solutions:

  1. Overloading - operator:
Complex operator - (Complex const &obj) {
   Complex res;
   res.real = real - obj.real;
   res.imag = imag - obj.imag;
   return res;
}
  1. Overloading * operator:
Complex operator * (Complex const &obj) {
   Complex res;
   res.real = real*obj.real - imag*obj.imag;
   res.imag = real*obj.imag + imag*obj.real;
   return res;
}
  1. Overloading == operator:
bool operator == (Complex const &obj) {
   return (real == obj.real && imag == obj.imag);
}

These exercises should help you solidify your understanding of operator overloading in C++. Practice by creating your own classes and overloading operators to perform the operations you want.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Timestamp Converter

Convert timestamps to human-readable dates.

Use tool

Random Number Generator

Generate random numbers between specified ranges.

Use tool

Unit Converter

Convert between different measurement units.

Use tool

Keyword Density Checker

Analyze keyword density for SEO optimization.

Use tool

URL Encoder/Decoder

Encode or decode URLs easily for web applications.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help