Sobes.tech
Junior

What is inheritance in object-oriented programming?

sobes.tech AI

Answer from AI

Inheritance is an object-oriented programming (OOP) mechanism that allows creating a new class (derived, child) based on an existing class (base, parent). The derived class inherits fields and methods from the base class, and can also add its own or modify inherited ones.

Main types of inheritance in C++:

  1. Public (public): The members of the base class retain their access levels in the derived class.
  2. Protected (protected): Public and protected members of the base class become protected in the derived class. Private members remain inaccessible.
  3. Private (private): Public and protected members of the base class become private in the derived class. Private members remain inaccessible.

Example of public inheritance:

#include <iostream>

class Base {
private:
    int private_member;
protected:
    int protected_member;
public:
    int public_member;

    void publicMethod() {
        std::cout << "Base - publicMethod" << std::endl;
    }
};

class Derived : public Base { // Public inheritance
public:
    void derivedMethod() {
        // Access to public_member is possible
        // Access to protected_member is possible
        // Access to private_member is not possible
        std::cout << "Derived - public_member: " << public_member << std::endl;
        std::cout << "Derived - protected_member: " << protected_member << std::endl;
        publicMethod(); // Access to publicMethod is possible
    }
};

// int main() {
//     Derived d;
//     d.public_member = 10; // Access from outside is possible
//     // d.protected_member = 20; // Access from outside is not possible
//     // d.private_member = 30; // Access from outside is not possible
//     d.publicMethod(); // Access from outside is possible
//     d.derivedMethod();
//     return 0;
// }

Advantages of inheritance:

  • Code reuse: Avoiding duplication of logic.
  • Polymorphism: Ability to handle objects of derived classes through pointers or references to the base class.
  • Establishing hierarchies: Modeling "is-a" relationships between objects.

Inheritance is a fundamental concept in C++ and a key element for building flexible and extensible systems.