Reputation: 532
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?
Upvotes: 15
Views: 33508
Reputation: 310980
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..
Upvotes: 7
Reputation: 32904
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.
Upvotes: 15