Can anyone explain to me why the following segment compiles but the commented line after doesn't?
struct tObj
{
int data;
int moreData;
}
...
void funcToCall (tObj *obj, int moreData)
{
//Useful stuff here
}
void mainFunction ()
{
vector<tObj>::iterator it = vectorOfObjects.begin(); //assumes vectorOfObjects is already defined
while (it != vectorOfObjects.end())
{
funcToCall (&(*it), 0); //This line works
funcToCall (it, 0); //This line produces an error
it++;
}
}
The error produced is this:
error: cannot convert ‘std::vector<tObj>::iterator {aka __gnu_cxx::__normal_iterator<tObj*, std::vector<tObj> >}’ to ‘tObj*’
Any ideas on why &(*it)
works but just plain it
doesn't? Logically they are the same, aren't they?
Because doesn't *
mean to dereference and &
mean pass by reference aka cancelling each other out?
You could pass a const reference, but usually iterators are small enough that it gives no advantage over passing by value.
To pass an element of an array to a function, use the subscripted name of the array element as an argument in the function call. In Chapter 6, we showed how to pass scalars (i.e., individual variables and array elements) by reference with references. In Chapter 8, we show how to pass scalars by reference with pointers.
it
is an iterator object, passing it as-is would mean you're trying to pass an object of type vector<tObj>::iterator
for a function expecting tObj*
, and thus the error.
When you do *it
you'd get the underlying object the iterator is representing and when you apply &
atop that, you get that object's address, which is of type tObj*
which agrees with the function's argument type and thus no error.
That the code would be compiled you have to declare an overloaded function like
void funcToCall ( std::vector<tObj>::iterator it, int moreData)
{
//Useful stuff here
}
In general case types tObj *
and vector<tObj>::iterator
are different types though in some old realizations of std::vector its iterator is indeed defined as a pointer..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With