What do you mean, non-standard constructor? You initialize it however you want. The default constructor for vector creates a vector with size = capacity = 0. You can specify whatever size you want and create a container of null pointers. I've no idea when you plan on constructing the tileSprite objects or what your requirements for that are. When you are ready to put actually objects into the vector you use operator[] or one of the insertion member functions. It depends on whether you construct it to be empty or with some number of null pointers. I'm sure that there are many ways to do it. Read the vector documentation and determine the best way for your situation. The actual insertion of data into the container can be done anywhere within the class that you want. I do not know what your TileSprite type is so I have shown a default constructor. You'd obviously have to call whichever constructor is appropriate.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Attributes::Attributes(void)
: tileSprite()
{
// tileSprite is empty
tileSprite.push_back(new TileSprite()); // do it as many times as you like
}
// or
Attributes::Attributes(void)
: tileSprite(10) // 10 zero initialized pointers
{
// tileSprite is empty
for(int i = 0; i < tileSprite.size(); i++)
{
tileSprite[i] = new TileSprite(); // construct 10 objects and copy the pointers
}
}
std::vector< TileSprite > tileSprite; // holds instances of TileSprite
std::vector< TileSprite* > tileSprite; // holds pointers to instances of TileSprite which you must manage with new and delete
All vectors are constructed in the same way. They are templates so the difference is in how you insert the elements. If you want pointers you insert pointers. If you want objects you insert using a temp object and let vector do the copying for you. Beyond that I am not sure what else you need help with.
Wow, thankyou very much! The power of C++ surprises me.
Is there any difference between doing TileSprite() and new TileSprite()? Or does it return a pointer, I think previously using C# has really mixed things up for me.
Also does the ":" operator have other uses besides allowing a private value be set by a local?
The colon separates the constructor signature from the ctor-initializor list. That is where member variables are initialised (whether private or public).
1 2 3 4 5 6 7 8 9 10
class MyType
{
int i;
std::string s;
private:
MyType() : i(2), s("hello") // list of initializers after the colon ';'
{
}
};