2

I'd like to override the [] operator for an object which holds a std::vector object (that is, have the subscripting act as though it were directly applied to the member vector). This is what I have so far

using namespace std;
#include <string>
#include <iostream>
#include <vector>

class VectorWrapper
{
public:
    VectorWrapper(int N): _N(N), _vec(N) {}

    ~VectorWrapper() {delete &_vec;}

    string operator[](int index) const
    {
        return _vec[index];
    }

    string& operator[](int index)
    {
        return _vec[index];
    }


private:
    int _N;
    vector<string> _vec;
};

int main()
{
    VectorWrapper vo(5);
    vo[0] = "str0";
    std::cout << vo[0];
}

Which upon running produces the following error

Process finished with exit code 11

What am I doing wrong?

D.M.
  • 123
  • 3
  • 7
    `~VectorWrapper() {delete &_vec;}` nonono very bad idea. – Timo Feb 24 '20 at 20:40
  • 3
    Don't call delete on something that was not created with new. – Martin York Feb 24 '20 at 20:48
  • 2
    Handy reading: [The Rules of Three, Five, and Zero](https://en.cppreference.com/w/cpp/language/rule_of_three). Because `vector` observes the Rule of Five for you, your class can observe the Rule of Zero and do nothing. You want to write classes that use the Rule of Zero unless you need special resource handling, and in that case you observe Three or Five so everyone depending on the class can observe Zero. – user4581301 Feb 24 '20 at 20:54

1 Answers1

9

You are trying to delete your member in the destructor. Only use delete on objects that you created with new. Remove that destructor completely, the language will handle the destruction for you.

Also, your first index operator should return a const reference

string const& operator[](int index) const

instead of a value.

Furthermore, _N is an illegal name. You're not allowed to name things starting with an underscore followed by an uppercase letter.

Timo
  • 9,269
  • 2
  • 28
  • 58
  • 1
    Reference: [What are the rules about using an underscore in a C++ identifier?](https://stackoverflow.com/q/228783/14065) – Martin York Feb 24 '20 at 20:47
  • see "https://www.tutorialspoint.com/What-are-the-rules-to-declare-variables-in-Cplusplus": 2. All variable names must begin with a letter of the alphabet or an underscore(_). and other places. Is the "followed by an uppercase letter' a new rule? – 2785528 Feb 24 '20 at 23:07
  • @2785528 Quite old. At least as old as C++03, and possibly inherited from C. It doesn't get you very often, but when it does, the error messages and program behaviour (if you're unlucky enough for the code to still compile) are utterly bizarre. If you don't know the naming rules ahead of time debugging this can be a real mind. – user4581301 Feb 25 '20 at 00:27