Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) operator[]()

 

operator[]() (pronounced as 'the index operator') is an operator used to retrieve an indexed element from a container.

 

#include <cassert>
#include <vector>

struct StoreTenInts
{
  StoreTenInts() : mV(std::vector<int>(10,0)) {}

  int& operator[](const int i)
  {
    //Calls the const version of operator[]
    //To avoid duplication in const and non-const member functions [1]
    return const_cast<int&>(const_cast<const StoreTenInts&>(*this)[i]);
  }

  const int& operator[](const int i) const
  {
    //The actual work of operator[]
    assert(i >= 0 && i < 10);
    return mV[i];
  }

private:
  std::vector<int> mV;
};

 

 

 

 

 

Advice

 

 

 

 

 

 

Reference

 

  1. Scott Meyers. Effective C++ (3rd edition). ISBN:0-321-33487-6. Item 3, paragraph 'Avoid duplication in const and non-const member functions'
  2. Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 19.5. Advice. page 576: '[1] Use operator[]() for subscripting and for selection based on a single value'

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict