106. Constructor Order Inheritance

#include <iostream>
using namespace std;

// Base driver class
class BaseDriver {
public:
    BaseDriver() {
        cout << "Base driver initialized" << endl;
    }
};

// Derived driver class
class DerivedDriver : public BaseDriver {
public:
    DerivedDriver(int v) : value(v) {
        cout << "Derived driver initialized" << endl;
    }

    void printValue() {
        cout << "Driver value " << value << endl;
    }

private:
    int value;
};

int main() {
    int value;
    cin >> value;

    DerivedDriver driver(value);
    driver.printValue();

    return 0;
}

Explanation & Logic Summary:

When an object of a derived class is created, C++ always calls the base class constructor first.
This behavior is automatic and does not require explicit function calls.

The printed output confirms this execution order.

Firmware Relevance & Real-World Context:

In firmware development:

  • Base drivers initialize shared hardware (clocks, buses, GPIO setup)
  • Derived drivers configure device-specific functionality

Constructor order ensures that hardware is ready before device access, preventing undefined behavior in embedded systems.

 

 

 

Loading...

Input

5

Expected Output

Base driver initialized Derived driver initialized Driver value 5