4

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

Nick Bolton
  • 38,276
  • 70
  • 174
  • 242

5 Answers5

10

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) = ...
Todd Gamblin
  • 58,354
  • 15
  • 89
  • 96
8

Try the following

(*this)[0] = ...
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
0
 ClassA::ClassA()
 {
     this->operator[]( someindex ) = whatever;
 }

But make sure that whatever member data the operator may depend on is fully constructed before you use it.

0

Here's another way, not sure if it's useful...

ClassA::ClassA()
{
    ClassA &_this = *this;
    _this[0] = someValue;
    _this[1] = someValue;
    _this[2] = someValue;
    _this[3] = someValue;
    _this[4] = someValue;
}
Nick Bolton
  • 38,276
  • 70
  • 174
  • 242
0

Two different ways:

( *this ) [ index ] or this -> operator [ ] ( index )
Tanveer Badar
  • 5,438
  • 2
  • 27
  • 32