I’m currently building a set of classes intended to handle weapons in my current game. The basic idea is thus:
I have a base class named “GameObject”, of which a sub-class is “WeaponsFire” - the class that describes a single “shot” from a weapon.
I have a second class, “Weapon”, which describes, well, a weapon. Weapons have cooldown and maximum cooldown values (that is, the time between shots), and an “ammunition” variable, which stores a template WeaponsFire.
When “fire()-d”, a weapon should return a copy of its ammunition variable, initialised to the given position and direction.
And here is my problem: I don’t know how to create a proper copy constructor.
I suppose that I could extract the relevant values from the template and use the normal constructor, but surely there’s a way to create a proper copy constructor? I seem to recall that Vec3 has one (you can simply use “new_vec = Vec3(old_vec)”, I believe), for example.
I’ve already tried having two constructors (that is, two init methods), which seems to result in only the last-defined being valid. Searches of the 'net, including this forum, have thus far not turned up much of use. I have encountered mention of using a “copy” module, but from what I saw, the resulting syntax isn’t quite what I’m looking for.
So… How do I go about this?
Python doesn’t really have a concept of a copy constructor. You get one init() function. Some people define an init() function that can make a copy or create an original object, depending on the keyword parameters you pass it.
Other people implement a makeCopy() method which constructs a new instance and fills in the appropriate elements. Or, using the copy module is also a fine choice.
Many Panda classes, like Vec3(), do have a copy constructor because they come from C++, which has a concept of copy constructors. This is implemented by making a smart init() function that decides what kinds of parameters you passed it.
nods Fair enough, and thanks. That’s a pity.
I think that I’ll select a copy method, then (something that had previously occurred to me) - it seems to be the simplest of the approaches that you suggested.
On second thought, I’ve decided to instead create another class that holds the information used to construct a WeaponsFire object, and which provides a method that produces as new WeaponsFire object. Weapons now hold one of these descriptors instead of an actual Weaponsfire object.
(Of course, if this is a bad idea for some reason - efficiency in particular - please let me know! ^^; )
Sounds reasonable for situations.
I sometimes do that with scripted languages like Python and Ruby. I have a fancy object which does all the smarts but then I keep the details (usually read from a file/db or whatever) in the form of a hash table. The smarter objects then just hold those tables for each object.