VinylScratch
VinylScratch

Reputation: 127

How can I use inheritance properly while still being efficient?

I have some classes here:

class weapons
{
protected:
    int damage, armor, cost;
};

class sword : public weapons
{
public:
    // Initialization for the sword class.
    void initialize()
    {

    }
};

class shield : public weapons
{

};

I started working on these and I do not remember how to set the damage, armor, and cost for each inherited class. How do I do this? What is a quick way (does not have to be easy)?

Upvotes: 1

Views: 111

Answers (3)

perreal
perreal

Reputation: 98118

class weapons
{
protected:
    int damage, armor, cost;
    weapons(int d, int a, int c): 
      damage(d), armor(a), cost(c) { }
};

class sword: public weapons {
  public:
    sword(): weapons(10, 12, 31) { }
}
class shield: public weapons {
  public:
    shield(): weapons(1, 22, 48) { }
}

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

The proper way of setting up variables in a class is through the constructor of their class. Derived classes should use initializer list to set variables in their base classes.

class weapon {
protected:
    int damage, armor, cost;
    weapon(int d, int a, int c) : damage(d), armor(a), cost(c) {}
};

class sword : public weapon {
private:
    int weight;
public:
    sword(int d, int a, int c, int w) : weapon(d, a, c), weight(w) {}
};

Alternatively, if the subclass controls the values in the base (i.e. the user does not pass damage, armor, or cost you can do this:

sword(int w) : weapon(30, 5, 120), weight(w) {}

The compiler will optimize this code to inline things properly, so you should not worry about the performance suffering from adding an extra layer of constructors.

Upvotes: 6

Linuxios
Linuxios

Reputation: 35788

Just use them in the child class. Because the properties are defined as protected in the parent, they can be accessed like normal variables in the child. Like this:

damage = 60;
armor = 0;
cost = 42;

Upvotes: 1

Related Questions