Welcome to our deep dive into C++'s powerful feature - Overloading the [] (Subscript) Operator! This lesson is designed for both beginners and intermediates, so let's get started.
Operator Overloading is a feature in C++ that allows us to extend the functionality of existing operators to work with user-defined types. Today, we'll focus on the [] operator, which is often used to access elements in arrays.
[] Operator? š”Overloading the [] operator can make our code more readable and efficient. Instead of using functions to access elements in custom data structures, we can use the familiar square bracket notation, just like with standard arrays.
[] Operator Step by Step šÆMyVector šLet's create a simple class MyVector that mimics the behavior of a standard vector.
class MyVector {
private:
int* data;
int size;
public:
MyVector(int size) : size(size) {
data = new int[size];
}
// Overloaded [] operator
int& operator[](int index) {
// Check for bounds
if(index >= 0 && index < size) {
return data[index];
} else {
std::cout << "Index out of bounds!" << std::endl;
exit(EXIT_FAILURE);
}
}
};In the code above, we've created a class MyVector that has a private data array and a size variable. The constructor initializes the data array with the given size.
We've also defined an overloaded [] operator. If the index is within bounds, we return the corresponding element. Otherwise, we print an error message and exit the program.
MyVector šÆNow let's see how to use MyVector.
#include <iostream>
#include <vector>
// Your MyVector class here
int main() {
MyVector vec(5);
vec[0] = 10;
vec[1] = 20;
vec[2] = 30;
vec[3] = 40;
vec[4] = 50;
std::cout << vec[2] << std::endl; // Output: 30
// Accessing an out-of-bounds index
vec[5] = 60; // This will output "Index out of bounds!" and exit the program
return 0;
}In the main function, we create a MyVector object vec of size 5. We then assign values to various indices and print the third element. If we try to access an out-of-bounds index, our program will print an error message and exit.
What is Operator Overloading in C++?
Why overload the `[]` operator?
Keep learning and happy coding! š”š