Object oriented design suggestion

Posted by pocoa on Stack Overflow See other posts from Stack Overflow or by pocoa
Published on 2010-04-06T14:52:10Z Indexed on 2010/04/06 14:53 UTC
Read the original article Hit count: 490

Here is my code:

class Soldier {
public:
   Soldier(const string &name, const Gun &gun);
   string getName();
private:
   Gun gun;
   string name;
};

class Gun {
public:
   void fire();
   void load(int bullets);
   int getBullets();
private:
   int bullets;
}

I need to call all the member functiosn of Gun over a Soldier object. Something like:

soldier.gun.fire();

or

soldier.getGun().load(15);

So which one is a better design? Hiding the gun object as a private member and access it with getGun() function. Or making it a public member? Or I can encapsulate all these functions would make the implementation harder:

soldier.loadGun(15); // calls Gun.load()
soldier.fire(); // calls Gun.fire()

So which one do you think is the best?

© Stack Overflow or respective owner

Related posts about c++

Related posts about object-oriented-design