Go back to Richel Bilderbeek's homepage.

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

 

 

 

(C++) operator[]

 

Operator commonly used to retrieve an indexed element from a container.

 

Avoid duplication in const and non-const member functions [1].

 

 

#include <vector>

#include <cassert>

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;

};

 

 

 

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'.

 

 

 

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

Go back to Richel Bilderbeek's homepage.