Inheritance - Tryhardtocarry/2143-oop GitHub Wiki

Inheritance

Definition

Inheritance is an OOP concept where a class child class inherits properties and methods from another class parent class.
It allows code reuse and enables hierarchical classification.

#include <iostream>
using namespace std;

// Base class (Parent class)
class Character {
protected:
    string name;
    int hp;

public:
    // Constructor
    Character(string n, int h) {
        name = n;
        hp = h;
    }

    // Method to display character info
    void display() {
        cout << "Character: " << name << ", HP: " << hp << endl;
    }
};

// Derived class (Child class)
class Warrior : public Character {
private:
    int strength;

public:
    // Constructor (calls base class constructor)
    Warrior(string n, int h, int s) : Character(n, h) {
        strength = s;
    }

    // Method to display warrior info
    void display() {
        cout << "Warrior: " << name << ", HP: " << hp << ", Strength: " << strength << endl;
    }
};

int main() {
    // Creating a base class object
    Character c1("Mage", 100);
    c1.display();

    // Creating a derived class object
    Warrior w1("Knight", 150, 80);
    w1.display();

    return 0;
}
⚠️ **GitHub.com Fallback** ⚠️