kim366 kim366 - 1 year ago 92
C++ Question

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

Doesn't work

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

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

makes it work, though. I find it very wierd that
returns an object of type
and not
, as
does. Shouldn't they work the same way in this example?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download