Hey guys, If I have a Vector of pointers, how can I iterate through that vector, to access the name function of each object in the vector? There seems to be a problem with my implementation, the output returns only random symbols.
Implementation of the name() function in Drug.cpp:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
//name() is a function returning the name in the parent class
string Drug::name()
{
string out = "Drug: ";
out += mName + " [ ";
//The problem is with this loop
for (int k = 0; k < mComponents.size(); k++)
{
out += mComponents[k]->name() + ", ";
}
out += " ]";
return out;
}
There are concrete classes defining different types of drugs, a drug named "Miracuru" for example will be created by:
Drug* d = new Miracuru();
However the point is, given the following vector: vector<Component*> mComponents;
How can I iterate through the vector of object pointers to access the name() function of each component object in the vector? The following code produces the incorrect results:
1 2 3 4
for (int k = 0; k < mComponents.size(); k++)
{
out += mComponents[k]->name() + ", ";
}
For Example, in concrete class Miracuru, which is a drug to be created:
Miracuru.h
1 2 3 4 5 6 7 8 9 10 11 12 13
#ifndef MIRACURU_H
#define MIRACURU_H
#include "Drug.h"
class Miracuru: public Drug
{
public:
Miracuru();
void mix();
};
#endif
Miracuru.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include "Miracuru.h"
Miracuru::Miracuru()
:Drug("Miracuru")
{
}
void Miracuru::mix()
{
Component* c = new Chemical("trifluoperazine");
Component* b = new Chemical("methylprednisolone");
Component* d = new Chemical("acetaminophen");
Drug* f = new Drug("Miracle Worker");
add(c);
add(b);
add(d);
}
I think I fixed another small error in elsewhere in my code, where I forgot to return a needed value, anyway, I learned a lot about Vectors from this :)
I apologize for the misunderstanding, but thanks for trying to help!