Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Calling overloaded operator from within a class

Tags:

c++

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!

like image 369
FreelanceConsultant Avatar asked Mar 05 '16 17:03

FreelanceConsultant


People also ask

How do you call an overloaded function?

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.

Can a class inherit overloaded operators?

Overloaded operators cannot have default arguments. All overloaded operators except assignment (operator=) are inherited by derived classes.

Can == be overloaded?

==, !=, <, >, <=, >=The comparison operators can be overloaded.

Can we overload operator in C?

C does not support overloading of operators or functions. There's no way you can redefine < , <= , > , >= , == , or != to compare struct types directly.


1 Answers

You could say (*this)[0].

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

like image 165
Matti Virkkunen Avatar answered Oct 13 '22 06:10

Matti Virkkunen