Creating Better Classes

Started by
13 comments, last by wise_Guy 23 years, 11 months ago
I think you actually have the basic idea down fine. Since you seem to not want/aren''t able to create a specific type of weapon for initialization and then assign it to your general array you are left with two solutions.

If you just need to initialize your objects differently, then you should use a constructor so that you say simply say:

pWeapon = new automatic(fire_rate);

and then you don''t need to worry about accessing the automatic variables through the weapon pointer.

If you need to muck with the variables (or functions) later in the program, then you have two options. If you know for sure that a weapon pointer points to an automatic you can use a simple type cast:

((automatic*)weapon)->fire_rate = 20;

and that should do what you want.

If, on the other hand, you are trying to find out what type the object is and if you can call a certain function of access a certain variable, then you need to do a dynamic cast. This is similar to a normal cast, but it checks the object type and if it is a correct cast it will be done and if not, it will return null:

automatic* pAutomatic = dynamic_cast(pWeapon);

if (pAutomatic) // it was an automatic weapon
pautomatic->fire_rate = 20;

You should probably check the syntax for the dynamic cast, I haven''t used it much, but I''m pretty sure its something like th above.

Good luck!


Check out the GPI project today!
Advertisement
The code in the original post will compile if you make a constructor for all the classes.

IOW, here''s a snippet of something I did a LOOONGGGG time ago:

class CMob : public CObject { // ugh MFC sucks.public:  CMob();  virtual void	Init();  virtual BOOL	Move();  // etc};class CPlayer : public CMob {public:  CPlayer();  BOOL	Move();  //etc...};NOW:CMob *playerList;playerList = new CPlayer(); // note different class! 


That compiles just fine.
BTW, anyone know how to get the code statement to make text that isn''t micro-freakin-scopic?
Thanks a lot everyone! I really appreciate it!


wiseGuy


(btw people say that this group is negative but how can they say that when there are so many helpful souls here?)
quote:Original post by Buster
BTW, anyone know how to get the code statement to make text that isn''t micro-freakin-scopic?


Put <FONT SIZE=+1> before the <quote>, and </font> after the </quote>

aig
aig

This topic is closed to new replies.

Advertisement