user2979802
user2979802

Reputation:

How to call objects method from list of pointers to objects, which is in a vector?

I would like to ask how to call objects method (getName and get that name) if my object pointer list is in a vector which is in inner class of my class (this is called inner/nested) to hide private variables and methods. Here is what I wrote so far. I have no idea how to print out all of the objects:

   bool Program::checkCategory(string name){
      vector<Category> *ptr = &(impl->categories);
      int i;
      for (i = 0; i < ptr->size(); i++){
         cout << ptr->at(i).getName() << endl;
      }
      return 0;
   }

Upvotes: 0

Views: 94

Answers (2)

user4815162342
user4815162342

Reputation: 155056

The small snippet you included has several problems. By decreasing order of importance:

  • You need a semicolon, not comma, before i++ in the for loop.

  • If the vector really holds pointers to objects, then you need to call ptr->at(i)->getName(), not ptr->at(i).getName(). In that case you also (most likely) need to declare the vector as vector<Category*>, not vector<Category>.

  • There is no need to use a pointer to access the vector. If you want a shorter name for the vector, you can use a reference, vector<Category>& vec = impl->categories. This makes it clear to the reader that you are only referencing a single vector rather than an array of vectors, and it removes the need to dereference the vector for each method call.

Upvotes: 2

Bruce Dean
Bruce Dean

Reputation: 2828

Not sure if this is the full extent of your issue (looks mostly good) but I think you need a semicolon:

You have:

i = 0; i < ptr->size(), i++

but you need it after size rather than comma:

i = 0; i < ptr->size(); i++

Upvotes: 2

Related Questions