Search code examples
c#c++subscript-operator

How do I access a C++ subscript operator from within the class in which it resides?


Where, ClassA has an operator as such, that returns ClassB:

class ClassA
{
public:
    ClassA();
    ClassB &operator[](int index);
}

If I want to access said operator from within ClassA's constructor, as so:

ClassA::ClassA()
{
    // How do I access the [] operator?
}

At the moment, as a work-around I'm just using a method called GetAtIndex(int index) which the [] operator calls, and so does the constructor.

It would be nice if I could access it in the same as as C# works:

// Note: This is C#
class ClassA
{
   ClassB this[int index]
   {
       get { /* ... */ }
       set { /* ... */ }
   }

   void ClassA()
   {
       this[0] = new ClassB();
   }
}

Note: I'm using g++


Solution

  • Try the following

    (*this)[0] = ...