C++ What is Inheritance?

https:‮w//‬ww.theitroad.com

Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class to be derived from another class. The derived class, also called the subclass or child class, inherits the properties (data members and member functions) of the base class, also called the superclass or parent class.

In C++, the syntax for defining a derived class is as follows:

class DerivedClass : public BaseClass {
    // additional members and functions
};

The public keyword here is called an access specifier, which determines how the base class members are inherited by the derived class. A derived class can inherit members of the base class with public, protected or private access specifiers, which determines their access levels within the derived class.

The protected keyword means that the inherited members are accessible only within the derived class and its derived classes. The private keyword means that the inherited members are not accessible outside of the base class.

Here's an example to demonstrate inheritance in C++:

class Animal {
public:
    void make_sound() {
        std::cout << "Generic animal sound\n";
    }
};

class Cat : public Animal {
public:
    void make_sound() {
        std::cout << "Meow!\n";
    }
};

int main() {
    Animal animal;
    Cat cat;

    animal.make_sound();  // "Generic animal sound"
    cat.make_sound();     // "Meow!"
}

In this example, the Animal class defines a single member function called make_sound(). The Cat class is derived from Animal and overrides the make_sound() function with its own implementation. When you create objects of these classes and call their make_sound() functions, you can see the different outputs.

Inheritance allows you to reuse the code and functionality of existing classes, which can save time and improve the design of your programs. It also facilitates the creation of complex hierarchies of classes that reflect real-world relationships and structures.