Search code examples
c++inheritancestdvectorthis-pointer

Use operator[] inside class that inherits std::vector


Doesn't work

class A : public std::vector<int>
{
    explicit A()
    {
        push_back(5);
        std::cout << *this[0]; 
    }
}

error: no match for 'operator*' (operand type is 'A')
std::cout << *this[0];'

Replacing *this[0] with at(0) makes it work, though. I find it very wierd that *this[0] returns an object of type A and not int, as at(0) does. Shouldn't they work the same way in this example?


Solution

  • The error message gives it away:

    error: no match for 'operator*' (operand type is 'A')
    

    Where does that A come from? this is an A* const, and the way to get objects from pointers is dereferencing - so that'd be this[0].

    You want:

    std::cout << (*this)[0]; 
    

    The precedence of operator[] is higher than dereference - you need to ensure that *this happens first. Of course, alternatively, you could write this mess:

    std::cout << this->operator[](0);
    

    but I'd recommend the parentheses.