Module lessons (1/2)
Inheritance in 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.
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:
privatemembers of the base class are not directly accessible from the derived class.protectedmembers 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.
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
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.
Show hint
Use the `:` syntax followed by `public Animal` to extend the base class, then write the `play()` method.
Solution available after 3 attempts
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.
Show hint
In the `Car` constructor, use the syntax `: Vehicle(b)` immediately after the parameter parentheses to delegate the initialization of brand to the base class.
Solution available after 3 attempts