1

I have a vector of pointers to Mouse objects called 'mice'. I'm passing the mice to the cat by reference.

vector <Mouse*> mice;
Cat * c;

c->lookForMouse(&mice);

And here's my lookForMouse() member function

void Cat::lookForMouse(vector <Mouse*> *mice)
{
  ...
}

And now to the problem! Within the function above, I can't seem to access my mice. This below will not work

mice[i]->isActive();

The error message I receive suggests to use mice[i].isActive(), but this throws an error saying isActive() is not a member of std::vector<_Ty> ...

This works though...

vector <Mouse*> miceCopy = *mice;
miceCopy[i]->isActive();

I understand that I shouldn't be creating another vector of mice here, it defeats the whole point of passing it by reference (let me know if I'm wrong)...

Why can't I do mice[i]->isActive() What should I be doing?

Thanks for your time and help :D

James.

2
  • As can be seen from multiple answers, the title of this question has nothing to do with vector of pointers, but rather with handling of pointer references. Commented Apr 15, 2010 at 13:50
  • Oops... If I could turn back time, If I could find a way, I'd take back those words that hurt you, And you'd stay, If I could reach the stars, I'd give them all to you, Then you'd love me, love me, Like you used to do... Commented Apr 15, 2010 at 14:08

3 Answers 3

4

The problem is that you are not passing a reference, but a pointer.
A reference would be passed like an object:

c->lookForMouse(mice);

and the function taking it would look like this:

void Cat::lookForMouse(vector <Mouse*> &mice)

Note that containers of dumb pointers are prone to leaking. For example:

void f()
{
   std::vector<Mouse*> mice = g();
   h(); // throws!

   cleanup(mice); // deletes objects in vector, is never called if h() throws
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that solved it for me! Can you elaborate on what you mean about dumb pointers being prone to leaking? I don't understand.
If an exception is thrown, the destructor of a vector of pointers only frees the pointers, not the things they point to. You'll leak all the pointed-to things if they're on the heap. On the other hand, so long as the things in the vector have destructors which clean up memory (eg. smart pointers), you're good.
2

mice[i] will index the pointer to the vector. To get an item from the vector you need to first dereference the pointer to it, so do:

(*mice)[i]->isActive()

Or perhaps better, pass the vector as a reference instead of a pointer.

1 Comment

This rings a bell. I was trying to do that but had the syntax wrong.
0
(*mice)[i]->isActive();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.