# Class in a vector in a class

## Recommended Posts

Cedric_    151
### Class1.h.###
#include <vector>

using namespace std
class firstClass
{
public:
myFunction();
vector<class secondClass> classCollection;
};

### Class1.cpp###
firstClass::myFunction()
{
classCollection.push_back( ?? );
}

### Class2.h.###
class secondClass
{
secondClass(string Var1, string Var2);
}


How do I get this to work? I want to stack several objects from the same class in my classCollection vector. What should I add in push_back( ); ?

##### Share on other sites
If I understood you right in what you wanted to do, it will become something like this:

### Class1.h.####include <vector>#include "Class2.h" // so we know about theseusing namespace stdclass firstClass{	public:		myFunction(const secondClass& Object); // is this what you want?        private: // i added private because otherwise it doesn't make much sense to have myFunction		vector<secondClass> objectCollection; // You can't store classes, only objects, so I renamed the vector.                };### Class1.cpp###firstClass::myFunction(const secondClass& Object) // pass by const reference{	objectCollection.push_back(Object); // makes a copy}### Class2.h.###class secondClass{	secondClass(string Var1, string Var2);};

##### Share on other sites
BTownTKD    205
First of all, you try to create a vector of Class2 before your compiler even knows what Class2 is! (you just need to include "class2.h").

As another point, you may want a vector of pointers to class 2, depending on how big class 2 is. If you have a long list of Class2's, then your vector will ave to copy all the data every time you push a new one in -- pointers would be much faster (just watch out for memory leaks!)

HTH
-Brian

##### Share on other sites
Cedric_    151
Weird, I thought I replied some time ago, but now I see my message never stuck. Anyways, thanks for the help, just what I was looking for DeadX. It's working fine now after some changes. And thanks for the advice about the pointers BTown, the class will probably grow over time.

Thanks a bunch!

Oohh, and that code was just a simplified example of my main problem, therefor much critical code is unavailable. Perhaps it just confused you, sorry if that's the case.