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.
Normal member functions are stored in the . text section of your program.
Yes, but always think carefully whether the function actually needs to be in a class, or should it be a free function altogether.
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.
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
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