-3

I have this class named soldier,in my project every soldier must have a weapon,and I have 5 different types of weapons,every class of the weapon types inherited from the 'weapon' class. how can I make a constructor in the soldier class so that the soldier can get any type of weapon? I thought about making 5 different constructors for every type of weapon but that doesn't make much sense

Liana
  • 15
  • 1
  • 8
  • 4
    [Get a couple of good beginners books](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and read about inheritance and *polymorphism*. – Some programmer dude Dec 30 '17 at 13:24
  • Have a constructor that accepts a `Weapon` by reference or pointer (or smart equivalents), and then registers the weapon provided somehow. Look up polymorphism. – Peter Dec 30 '17 at 13:25
  • @Peter like this soldier(Weapon &weapon)? – Liana Dec 30 '17 at 13:28
  • @Liana - that's one way (at least, in terms of argument list of a constructor). – Peter Dec 30 '17 at 13:32

2 Answers2

0

Say the Weapon is the base class of all weapons. Say you have 2 weapon types Gun and Knife:

class Weapon { virtual void shot() = 0; }

class Gun : public Weapon { virtual void shot() { cout << "Gun"; }


class Knife : public Weapon { virtual void shot() { cout << "Knife"; }

class Soldier {
   Weapon *weapon;
  public:
   Soldier() : weapon(nullptr) {}
   Soldier(Weapon* w) : weapon(w) {}
   void SetWeapon(Weapon* w) { weapon = w; }
   Weapon* GetWeapon() { return weapon; }
}

In a Real word code you would consider RAII or smart_pointers for holding and deleting Weapon* objects, otherwise memory leaks could occur.

StPiere
  • 4,113
  • 15
  • 24
-2

On your Soldier class you can have the following:

#include "weapon.h"

class Soldier {
    Weapon *weapon;
public:
    Soldier(Weapon *weapon) {
        this->weapon = weapon;
    }
};

When you are going to instanciate the class soldier:

Weapon *w1 = new Knife(), *w2 = new M1();
Soldier s1(w1), s2(w2);
kato2
  • 535
  • 4
  • 15
  • Please, if you are going to down vote my answer, leave a comment, explaining why. I don't understand because people down vote my answer. – kato2 Jan 01 '18 at 16:58