الانتقال إلى المحتوى الرئيسي
eLearner.app
الوحدة 6 · الدرس 1 من 213/18 في الدورة~12 min
دروس الوحدة (1/2)

الميراث في C++

Inheritance is one of the key pillars of Object-Oriented Programming (OOP). It allows a new class (called the derived or child class) to inherit members (attributes and methods) from an existing class (called the base or parent class), promoting code reuse.

Basic Syntax

In C++, inheritance is specified using the : operator after the derived class name, followed by an access specifier (usually public) and the base class name.

Code
class Shape {
public:
    void setColor(std::string c) {
        color = c;
    }
protected:
    std::string color; // Accessible by derived classes
};

// Rectangle inherits publicly from Shape
class Rectangle : public Shape {
public:
    double getArea() {
        return width * height;
    }
private:
    double width {0.0};
    double height {0.0};
};

Access Specifier: protected

Along with public and private, inheritance introduces the protected specifier:

  • private members of the base class are not directly accessible from the derived class.
  • protected members of the base class are inaccessible from the outside, but are directly accessible inside derived classes.

Base Class Initialization

Constructors are not automatically inherited. When instantiating a derived class, the base class constructor is called first. If the base class requires arguments, we must invoke it explicitly in the member initializer list of the derived constructor.

Code
class Parent {
public:
    Parent(int x) {
        std::cout << "Parent: " << x << std::endl;
    }
};

class Child : public Parent {
public:
    // Explicit call to Parent constructor
    Child(int x, int y) : Parent(x) {
        std::cout << "Child: " << y << std::endl;
    }
};

Try it yourself

تمرين#cpp.m6.l1.e1
المحاولات: 0جارٍ التحميل…

Create a Dog class that publicly inherits from the Animal class. The Dog class must include a public play() method that prints 'Playing' using std::cout.

جارٍ تحميل المحرر…
إظهار التلميح

Use the `:` syntax followed by `public Animal` to extend the base class, then write the `play()` method.

الحل متاح بعد 3 من المحاولات

تمرين#cpp.m6.l1.e2
المحاولات: 0جارٍ التحميل…

Complete the Car class by inheriting from Vehicle. Write a constructor for Car that accepts std::string b and passes it to the Vehicle constructor via the member initializer list.

جارٍ تحميل المحرر…
إظهار التلميح

In the `Car` constructor, use the syntax `: Vehicle(b)` immediately after the parameter parentheses to delegate the initialization of brand to the base class.

الحل متاح بعد 3 من المحاولات