Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling member functions of an object stored in a vector

Tags:

c++

stl

vector

This may sound like a newbie question. How do I call a member function of an object stored in a vector ? Supposedly, I have this class:

class A {
public:
void foo() {
std::cout << "Hello World"; }
};

Then I store some objects in a vector:

std::vector<A*> objects;
A* b;
A* c;
A* d;

objects.push_back(b);
objects.push_back(c);
objects.push_back(d);

Now I want to create a loop, in which every object stored in the vector would call it's own foo() function. How should I do this ? At first I thought I could just do something like this:

objects[2].foo();

But it seems that I can't do it like this.

like image 863
Andre Popa Avatar asked Jul 28 '13 05:07

Andre Popa


People also ask

Where are member functions stored?

Normal member functions are stored in the . text section of your program.

Can a member function defined within an object definition takes zero arguments?

Yes, but always think carefully whether the function actually needs to be in a class, or should it be a free function altogether.

What are members functions?

Member functions are operators and functions that are declared as members of a class. Member functions do not include operators and functions declared with the friend specifier. These are called friends of a class. You can declare a member function as static ; this is called a static member function.


1 Answers

std::vector::operator[] returns a reference to the object in std::vector. As your objects stores a pointer to A, you should call it:

objects[2]->foo();

Now I want to create a loop, in which every object stored in the vector would call it's own foo() function. How should I do this

The easiest loop is:

for (int i=0; i<objects.size(); ++i)
{
   objects[i]->foo();
}

use C++11 for loop:

for(auto ep : objects)
{
    ep->foo();
}

Or for_each(need to write a small lambda though)

for_each(objects.begin(), objects.end(), [](A* ep){ep->foo(); });

Side note: In practice you'd better store value in STL container.

std::vector<A> objects;
for(auto e : objects)
{
    ep.foo();    // call member function by "."
}

If you want to store pointer with STL container, better use smart pointer, e.g.

#include <memory>
std::vector<std::unique_ptr<A> > objects;

objects.push_back(new A());
objects.push_back(new A());
objects.clear(); // all dynamically allocated pointer elements will be de-allocated automatically
like image 169
billz Avatar answered Sep 24 '22 00:09

billz