vote up 1 vote down
star

Hello,

I am having issues figuring out a way to create an object from inside of another object. More specifically, I have a player that holds a gun that needs to fire a bullet.

What I have is a main World class which contains a vector of objects. This vector will run through a loop to do all the update logic/rendering for each object.

Now, I have a basic gun object. The player class will hold a pointer to this gun class. Where I am stuck is the creation of the bullet/projectile. The player will call a function on the gun class to initialize the bullet, but I don't have any idea how to get the bullet object into the objects vector in world in order to be displayed/etc.

Any ideas? Is my classes even right?

flag

2 Answers

vote up 0 vote down

There is a million ways to do this, I'll simply address your situation.

Seems like you just need to have an interface in the World that lets you add objects to it. I would have an AddObject function available to be used. Now all you need to do is make sure that when you initialize the bullet the player can pass a World reference into it's initialize function. This will let it set itself up and add itself in.

With that said you may want to avoid holding pointers for extended periods of time in multiple places. When you do that you increase the chance of accessing freed memory (the pointer gets cleaned up in World then the player accesses it, ouch). I would suggest putting the creation of object in the world via a CreateObject(ObjectType) and having another function to access the objects by index (string/int). That way every time you need to get the object you can query if it is even valid (cause the World would know).

link|flag
vote up 0 vote down

This sounds like the exact kind of problem that lends itself to a Factory.

The Factory is a design pattern commonly used in the creation of objects. You can find more information on the Factory pattern online. A great book on Design Patterns in general is the Design Patterns book by the "Gang of Four."

You should probably have some sort of bullet factory that the gun could call (or even send a message via message system) that would create and return a bullet. This bullet could be handed back up the chain to the World or even called from the World. If you would like help dealing specifically with your code, please post a sample of what you've got! (Unless that violates any NDAs you might have.)

link|flag

Your Answer

Get an OpenID
or

Not the answer you're looking for? Browse other questions tagged or ask your own question.