Skip to content

Teaching Notes: Module 03

  • Inheritance basics
  • Constructor/destructor chaining
  • Protected vs private members
  • Multiple inheritance and the diamond problem

  • Basic class design with OCF
  • Using protected for inheritance preparation
  • Constructor/destructor messages
AttributeValue
Hit points10
Energy points10
Attack damage0
  1. Making attributes private instead of protected

    • Derived classes need access
  2. Forgetting energy/HP checks

    void ClapTrap::attack(const std::string& target) {
    if (_energyPoints <= 0 || _hitPoints <= 0) {
    std::cout << "ClapTrap " << _name << " can't attack!" << std::endl;
    return;
    }
    _energyPoints--;
    // ...
    }

  • Basic inheritance
  • Constructor chaining
  • Function overriding
AttributeValue
Hit points100
Energy points50
Attack damage20
  1. Not calling base constructor

    // WRONG
    ScavTrap::ScavTrap(std::string name) {
    _name = name; // ClapTrap not properly initialized!
    }
    // CORRECT
    ScavTrap::ScavTrap(std::string name) : ClapTrap(name) {
    _hitPoints = 100;
    _energyPoints = 50;
    _attackDamage = 20;
    }
  2. Wrong construction/destruction order

    • Construction: Base -> Derived
    • Destruction: Derived -> Base
  • “When you create a ScavTrap, what gets constructed first?”
  • “How do you initialize the ClapTrap part of a ScavTrap?”

AttributeValue
Hit points100
Energy points100
Attack damage30

Same inheritance pattern as ScavTrap.


ClapTrap
/ \
ScavTrap FragTrap
\ /
DiamondTrap

Without virtual inheritance, DiamondTrap has TWO ClapTrap subobjects!

class ScavTrap : virtual public ClapTrap { };
class FragTrap : virtual public ClapTrap { };
class DiamondTrap : public ScavTrap, public FragTrap { };
  1. Forgetting virtual keyword

    • Must be on BOTH intermediate classes
  2. Not initializing virtual base in most-derived class

    DiamondTrap::DiamondTrap(std::string name)
    : ClapTrap(name + "_clap_name"), // Virtual base init
    ScavTrap(name),
    FragTrap(name),
    _name(name)
    { }
  3. Wrong attribute inheritance

    • HP: FragTrap (100)
    • Energy: ScavTrap (50)
    • Damage: FragTrap (30)
    • attack(): ScavTrap
  • “What happens if DiamondTrap inherits from both ScavTrap and FragTrap without virtual?”
  • “Why does the most-derived class initialize the virtual base?”
  • “How do you access the ClapTrap name vs DiamondTrap name?”

Draw class diagrams showing:

  • What each class inherits
  • Which members are overridden
  • Constructor call order
int main() {
std::cout << "--- Creating ScavTrap ---" << std::endl;
ScavTrap s("Scav");
std::cout << "--- End of main ---" << std::endl;
}
// Should show:
// ClapTrap constructor
// ScavTrap constructor
// ScavTrap destructor
// ClapTrap destructor