Your compiler is not very verbose. That is inconvenient. Some other compiler points out that
the non-const reference parameter cannot take literal 2.
Lets try to illustrate something by adding an another member function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
int & Plant::element( int sub )
{
return pointer[sub];
}
int main ()
{
Plant foo(5);
for (int n = 0; n < 5 ; n++)
{
foo.element( n ) = (n * 2);
}
cout << foo.element( 2 );
return 0;
}
|
The element() and operator[] do exactly the same thing. The foo is one object. The foo has member foo.pointer, that points to dynamically allocated (line 15 in your code) array. If you do use invalid subscript, then the dereference operation
pointer[sub]
would refer to outside of the allocated block. Accessing some memory address does not convert anything into array.
Your code has "big issues" though.
1. What does your op[] return, if the subscript is invalid? Apparently nothing, but the function
must return a reference.
2. Your class manages some dynamically allocated memory. You
must implement:
- copy constructor
- copy assignment
- destructor
Reasoning: the default implementations for these do not manage that memory correctly.