Operator Overloading

Overloading the Subscript Operator

How can I overload the subscript operator [] for my custom type?

Abstract art representing computer programming

To overload the subscript operator [] for your custom type, you need to define a member function named operator[]. This function should take an index parameter and return a reference to the element at that index.

Here's an example of overloading the subscript operator for a custom Vector class:

#include <iostream>

class Vector {
private:
  float elements[3];

public:
  float& operator[](int index) {
    return elements[index];
  }

  const float& operator[](int index) const {
    return elements[index];
  }
};

int main() {
  Vector v;
  v[0] = 1.0f;
  v[1] = 2.0f;
  v[2] = 3.0f;

  std::cout << v[1] << "\n";
}
2

In this example, we define two overloads of the operator[] function:

  • One for non-const objects, which returns a non-const reference to the element.
  • One for const objects, which returns a const reference to the element.

This allows us to use the subscript operator to access and modify elements of our Vector object, just like we would with a built-in array.

This Question is from the Lesson:

Operator Overloading

Discover operator overloading, allowing us to define custom behavior for operators when used with our custom types

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Operator Overloading

Discover operator overloading, allowing us to define custom behavior for operators when used with our custom types

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved