Skip to content

Instantly share code, notes, and snippets.

@Ajetski
Last active November 19, 2019 23:19
Show Gist options
  • Save Ajetski/98d4f65532f15471fdd5f180aea67e59 to your computer and use it in GitHub Desktop.
Save Ajetski/98d4f65532f15471fdd5f180aea67e59 to your computer and use it in GitHub Desktop.
A gist for a small code snippet that needs improvement
#include <iostream>
using namespace std;
class Test {
public:
Test();
int& operator[](const int& index);
const int& operator[](const int& index) const;
private:
int arr[10] = {};
};
Test::Test() {}
//non-constant access
int& Test::operator[](const int& index){
cout << "Inside Non-constant Method" << endl;
return arr[index];
}
//constant access
const int& Test::operator[](const int& index) const{
cout << "Inside Constant Method." << endl;
return arr[index];
}
int main() {
Test t;
int i = t[2];
const int j = t[2];
t[3] = 3;
cout << i << endl;
cout << j << endl;
cout << t[3] << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment