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!
The function call operator () can be overloaded for objects of class type. When you overload ( ), you are not creating a new way to call a function.
Overloaded operators cannot have default arguments. All overloaded operators except assignment (operator=) are inherited by derived classes.
==, !=, <, >, <=, >=The comparison operators can be overloaded.
C does not support overloading of operators or functions. There's no way you can redefine < , <= , > , >= , == , or != to compare struct types directly.
You could say (*this)[0]
.
There's nothing stopping you from using mem[0]
either though, in any version of C++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With