-1

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?

Community
  • 1
  • 1
Post Self
  • 1,471
  • 2
  • 14
  • 34
  • 2
    The standard classes aren't meant for deriving in most cases. Just use these as a member. – πάντα ῥεῖ Oct 21 '16 at 20:23
  • @πάνταῥεῖ Really? But that is unnecessary hassle. I have to make a getter and setter and so on. And this works fine for me – Post Self Oct 21 '16 at 20:36
  • My example: `class Grid`, `std::vector grid`. Those sound too similar, so why not merge them? I also tried getter and setter via `operator()` but that was hard to distinguish from the class itself as well. – Post Self Oct 21 '16 at 20:38
  • @πάνταῥεῖ Sorry. I have learned by now. Always learning... – Post Self Jan 22 '17 at 09:11

1 Answers1

3

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.

Barry
  • 286,269
  • 29
  • 621
  • 977