5

I have a class which inherits from another class, and I wish to call [index] to access the index'th element of some allocated storage.

Here is a minimal example:

class A
{
    protected:
    double *mem;

    double operator[](const size_t index)
    {
        return mem[index];
    }
}

class B : public A
{
    void function()
    {
        double var = this->operator[](0);
    }
}

So here I step around the problem by calling this->operator[](0) which is kind of messy.

Is this the correct way to access elements of mem considering that I don't have access to that variable from the derived class, or is there an alternative way?

Edit: I think it might be significant that I'm conforming to C++11, so can't call mem[0]?

Edit, template classes

As discussed below, the compiler error I see isn't showing up for this example, because there are no templates here.

To reproduce the compiler error:

template <typename T>
class A
{
    protected:
    double *mem;

    double operator[](const size_t index)
    {
        return mem[index];
    }
}

template <typename T>
class B : public A<T>
{
    void function()
    {
        double var = this->operator[](0);
    }
}

Possible Solutions

return this->operator[](0);
return (*this)[0];
return (this->mem)[0];
return *((this->mem)+0);
return (*this).mem[0];
return *((*this).mem+0);

... I think all of these do what I expect them to. Any more suggestions?

Even better solution:

return A::mem[0];

Exactly what I wanted!

FreelanceConsultant
  • 11,249
  • 25
  • 98
  • 189
  • You can also do `(*this)[0];` or `mem[0]` directly. – James Adkison Mar 05 '16 at 17:49
  • 2
    "Is this the correct way to access elements of mem considering that I don't have access to that variable from the derived class" -- You do have access from the derived class because `mem` is declared `protected`. – James Adkison Mar 05 '16 at 17:53
  • Possible duplicate of [How to use base class's constructors and assignment operator in C++?](http://stackoverflow.com/questions/1226634/how-to-use-base-classs-constructors-and-assignment-operator-in-c) – mustafagonul Mar 05 '16 at 18:09

2 Answers2

6

You could say (*this)[0].

There's nothing stopping you from using mem[0] either though, in any version of C++.

Matti Virkkunen
  • 61,328
  • 9
  • 119
  • 152
0

Yes, this is a good approach. You can make the call more pleasing by writing it as (*this)[0].

However, if you don't mind bypassing the base class's interface (I wouldn't — I'd actually make mem private), you can write mem[0]!

If you're having trouble with that, it's due to something not in your testcase. For example, if it's a base member in a class template, you may need to write this->mem[0] due to a C++ oddity.

Community
  • 1
  • 1
Lightness Races in Orbit
  • 369,052
  • 73
  • 620
  • 1,021