Sobes.tech
Junior

Tell us about the principles of inheritance in object-oriented programming in C++.

sobes.tech AI

Answer from AI

In C++, inheritance allows creating a new class (derived class) based on an existing class (base class). The derived class inherits members from the base class, including data and methods, and can add its own.

Main principles:

  1. Code reuse: Enables using the functionality of the base class without rewriting.
  2. Extensibility: The new class can extend or modify the behavior of the base class.
  3. Polymorphism (via virtual functions): Allows handling objects of different classes in a unified way (through pointers or references to the base class).

Types of inheritance in C++:

  • Single: One derived class inherits from one base class.
  • Multiple: One derived class inherits from multiple base classes.
  • Hierarchical: Several derived classes inherit from one base class.
  • Multilevel: A class inherits from another class, which in turn inherits from another.
  • Hybrid: Combination of two or more inheritance types.

Access specifiers in inheritance:

  • public: Public members of base remain public, protected remain protected, private are inaccessible.
  • protected: Public and protected members of base become protected, private are inaccessible.
  • private: Public and protected members of base become private, private are inaccessible.

Example:

// Base class
class Animal {
public:
    void eat() {
        // Implementation of eating
    }

protected:
    int age; // Accessible in derived classes

private:
    std::string name; // Not accessible in derived classes
};

// Derived class
class Dog : public Animal {
public:
    void bark() {
        // Implementation of barking
    }
};