Overloading the Subscript Operator

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

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.

Operator Overloading

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

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Overloading the Function Call Operator
What is the purpose of overloading the function call operator ()?
Overloading Comparison Operators
How can I overload comparison operators like == and < for my custom type?
Overloading Arithmetic Assignment Operators
How can I overload arithmetic assignment operators like += and *= for my custom type?
Overloading the Stream Insertion Operator
How can I overload the << operator to print objects of my custom type?
Overloading Operators for Type Conversions
Can I overload operators to perform type conversions for my custom type?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant