Slicing Breaks Polymorphism

#include <iostream>
using namespace std;

class Driver {
public:
    // virtual destructor is good practice for polymorphic bases
    virtual ~Driver() {} 
    
    virtual void run() {
        cout << "Generic driver running" << endl;
    }
};

class SpiDriver : public Driver {
public:
    void run() override {
        cout << "SPI driver running" << endl;
    }
};

class I2cDriver : public Driver {
public:
    void run() override {
        cout << "I2C driver running" << endl;
    }
};

/**
 * FIXED: Changed parameter to Driver& (Reference)
 * This prevents object slicing and allows the virtual function 
 * table to correctly resolve the derived method at runtime.
 */
void processDriver(Driver& driver) {
    driver.run();
}

int main() {
    int mode;
    if (!(cin >> mode)) return 0;

    SpiDriver spi;
    I2cDriver i2c;

    if (mode == 0) {
        processDriver(spi);
    } else if (mode == 1) {
        processDriver(i2c);
    }

    return 0;
}

Solving Approach

 

 

 

 

 

Upvote
Downvote
Loading...

Expected Output

SPI driver running