Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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++

like image 249
Nick Bolton Avatar asked Dec 03 '22 08:12

Nick Bolton


1 Answers

You can use:

this->operator[](0) = ...

or:

(*this)[0] = ...

But the syntax is a little awkward. I usually make another method called get and use that, e.g.:

ClassB& get(size_t index) {
    return this->operator[](0); // or something more direct
}

Then when you want to use it you can just say:

this->get(0) = ...
like image 181
Todd Gamblin Avatar answered Dec 04 '22 21:12

Todd Gamblin