Ugrás a tartalomhoz

Szerkesztő:LinguisticMystic/cpp/Inheritance

A Wikiszótárból, a nyitott szótárból

🔷 What is Inheritance in C++?

[szerkesztés]

Inheritance is one of the four core principles of object-oriented programming (OOP), along with encapsulation, abstraction, and polymorphism. It allows you to create a new class based on an existing class. The new class (called the derived or child class) inherits data members and member functions from the existing class (called the base or parent class).



🔹 Why Use Inheritance?

[szerkesztés]

Inheritance is valuable for:

  • 🔁 Reusing existing code instead of rewriting similar logic.
  • 📦 Extending base classes with new, specialized behaviors.
  • 🧱 Organizing classes into meaningful hierarchies (e.g., Animal → Dog, Cat).



🔹 Basic Terminology

[szerkesztés]
Term Description
Base Class The class being inherited from (e.g., Animal)
Derived Class The class that inherits (e.g., Dog, Cat)
Public Inheritance Most common; base class members retain their access level in derived class



🧪 Example: The Animal Class

[szerkesztés]
class Animal {
public:
    int m_age;
    std::string m_name;

    void print() {
        std::cout << "I am an animal named " << m_name << std::endl;
    }
};

✅ Explanation:

[szerkesztés]
  • m_age and m_name are public data members, so they’re accessible from outside the class.
  • print() prints the name of the animal.



🐶 Derived Classes: Dog and Cat

[szerkesztés]
class Dog : public Animal {
public:
    void bark() {
        std::cout << "Woof!" << std::endl;
    }
};

class Cat : public Animal {
public:
    void meow() {
        std::cout << "Meow!" << std::endl;
    }
};

✅ Explanation:

[szerkesztés]
  • Dog and Cat inherit all public and protected members of Animal.
  • Each adds a unique method: bark() and meow() respectively.



🧪 Demonstrating Inheritance in main

[szerkesztés]
int main() {
    Animal fish;
    fish.m_name = "Nemo";
    fish.print();

    Dog dog;
    dog.m_name = "Barsik";
    dog.print();
    dog.bark();

    Cat cat;
    cat.m_name = "Murzik";
    cat.print();
    cat.meow();

    return 0;
}

🔎 Output:

[szerkesztés]
I am an animal named Nemo

I am an animal named Barsik
Woof!

I am an animal named Murzik
Meow!

🔄 Method Overriding

[szerkesztés]
class Dog : public Animal {
public:
    void print() {
        std::cout << "I am a dog and my name is: " << m_name << std::endl;
    }
};

✅ Explanation:

[szerkesztés]
  • The Dog class overrides the print() method.
  • Now, calling dog.print() will use the Dog version, not the Animal version.



🔐 Access Control: Public vs Protected vs Private

[szerkesztés]

Let’s move the members of Animal to private:

class Animal {
private:
    int m_age;
    std::string m_name;

public:
    void setName(std::string name) {
        m_name = name;
    }

    void print() {
        std::cout << "I am an animal named " << m_name << std::endl;
    }
};

🔥 Problem:

[szerkesztés]

Trying to access m_name from Dog or Cat will cause a compilation error, because private members are not accessible in derived classes.



🛠 Solution: Use protected

[szerkesztés]
class Animal {
private:
    int m_age;

protected:
    std::string m_name;

public:
    void setName(std::string name) {
        m_name = name;
    }

    void print() {
        std::cout << "I am an animal named " << m_name << std::endl;
    }
};

Now m_name is accessible from child classes, but still hidden from the outside world.



🧪 Overridden print() in Derived Classes

[szerkesztés]
class Dog : public Animal {
public:
    void bark() {
        std::cout << "Woof!" << std::endl;
    }

    void print() {
        std::cout << "I am a dog and my name is: " << m_name << std::endl;
    }
};

🔁 Multiple Inheritance in C++

[szerkesztés]

Let’s define movement capabilities:

class LandAnimal {
public:
    void move() {
        std::cout << "I am moving on land." << std::endl;
    }
};

class SwimmingAnimal {
public:
    void move() {
        std::cout << "I am swimming." << std::endl;
    }
};

Now create classes that inherit from both Animal and either movement class:

class Dog : public Animal, public SwimmingAnimal {
public:
    void bark() {
        std::cout << "Woof!" << std::endl;
    }

    void print() {
        std::cout << "I am a dog and my name: " << m_name << std::endl;
    }
};

class Cat : public Animal, public LandAnimal {
public:
    void meow() {
        std::cout << "Meow!" << std::endl;
    }

    void print() {
        std::cout << "I am a cat and my name: " << m_name << std::endl;
    }
};

🔎 Full Program Output:

[szerkesztés]
I am an animal named Nemo

I am a dog and my name: Barsik
I am swimming.
Woof!

I am a cat and my name: Murzik
I am moving on land.
Meow!

⚠️ Caution with Multiple Inheritance

[szerkesztés]

While powerful, multiple inheritance can be problematic:

  • Ambiguity: If both base classes have methods with the same name (move() in our case), it may cause conflicts.
  • Complexity: Increases cognitive load and risk of bugs.

You can solve such conflicts explicitly:

dog.SwimmingAnimal::move();
cat.LandAnimal::move();

✅ Benefits of Inheritance

[szerkesztés]
Benefit Description
🔁 Code Reuse Share common logic across classes
➕ Extensibility Add new features by extending existing classes
🧱 Organization Structure your code hierarchically and logically



❌ Downsides of Inheritance

[szerkesztés]
Drawback Description
📉 Complexity More classes = harder to understand and maintain
🔗 Tight Coupling Child classes depend on base class structure
🐞 Fragile Base Class Changes in base class can unintentionally break derived classes



🧾 Summary

[szerkesztés]

Inheritance is a foundational tool in C++ OOP:

  • Enables class hierarchies and reuse.
  • Helps avoid duplication.
  • Supports method overriding for custom behavior.
  • Should be used thoughtfully, especially when dealing with protected/private members or multiple inheritance.