Skip to main content

Inheritance

Introduction to Inheritance in C++

Inheritance is one of the most fundamental concepts in object-oriented programming. It allows you to create a new class, known as a derived class, from an existing class, known as a base class. The derived class inherits all the features of the base class and can also add new features.

Understanding Inheritance

Imagine you have a class named Animal. This class has properties like age, weight, and methods like eat(), sleep(). Now you want to create a new class Dog, which has all the features of Animal, but also has a new property breed and a new method bark(). Instead of rewriting all the code of the Animal class, you can simply make the Dog class inherit from the Animal class.

Inheritance not only saves us from rewriting code but also organizes code better and makes it easier to understand and maintain.

Syntax of Inheritance

Here is the basic syntax to create a derived class from a base class:

class DerivedClass : visibility-mode BaseClass
{
// body of the derived class
};

Here, visibility-mode could be either public, private, or protected. This mode specifies how the members of the base class are accessible in the derived class. The most commonly used mode is public.

Here's an example:

class Animal {
public:
int age;
void eat() {
cout << "Eating...";
}
};

class Dog : public Animal {
public:
string breed;
void bark() {
cout << "Barking...";
}
};

Now if we create an object of the Dog class, we can access the age and eat() method from the Animal class along with breed and bark() of the Dog class.

Dog dog;
dog.age = 5;
dog.breed = "Bulldog";
dog.eat();
dog.bark();

Types of Inheritance

There are different types of inheritance in C++, namely:

  1. Single Inheritance: When a class is derived from a single base class, it's called single inheritance.

  2. Multiple Inheritance: When a class is derived from more than one base class, it's called multiple inheritance.

  3. Multilevel Inheritance: When a class is derived from a class which is also derived from another class, it's called multilevel inheritance.

  4. Hierarchical Inheritance: When one class serves as a base class for more than one derived class, it's called hierarchical inheritance.

  5. Hybrid Inheritance: A mix of two or more types of inheritances.

Conclusion

Inheritance is a powerful concept in C++ that allows you to build complex systems from simple building blocks. It promotes code reuse and helps in designing real-world scenarios in programming. Start practicing this concept and try different types of inheritance to get a solid understanding. Remember, practice is critical when learning programming, especially with complex concepts like inheritance.