0

I have two base classes Vehicle and WorkerUnit and they have derived classes Bus and Maintenance respectively.

The Maintenance class has to be initialized with a variable of class Vehicle (or the derived classes of Vehicle), and the function print() inside class Bus is to be called. How do I achieve this?

#include <iostream>
using namespace std;

// Vehicle Class
class Vehicle {
public:
    virtual void print() {
        cout << "Vehicle print() called" << endl;
    }
};

class Bus : public Vehicle {
public:
    void print() {
        Vehicle::print();
        cout << "   Bus print() called" << endl;
    }
};

// Worker Unit Class
class WorkerUnit {
protected:
    Vehicle vehicle;
public:
    WorkerUnit(Vehicle vehicle) : vehicle(vehicle) {}
    virtual void print() {}
};

class Maintenance : public WorkerUnit {
public:
    Maintenance(Vehicle vehicle) : WorkerUnit(vehicle) {}
    void print() {
        // Problem here where function calls base class Vehicle's print()
        // How do I actually call the derived class's print()?
        vehicle.print();
    }
};

int main(void) {
    Bus *bus = new Bus();
    Maintenance *m = new Maintenance(*bus);
    m->print();

    return 0;
}
L.C. Wong
  • 43
  • 5
  • http://stackoverflow.com/questions/7223613/c-polymorphism-without-pointers http://stackoverflow.com/questions/15188894/why-doesnt-polymorphism-work-without-pointers-references – LogicStuff Jan 14 '17 at 23:39
  • 1
    @LogicStuff Thanks for the quick reply. I've never really encountered this until now. – L.C. Wong Jan 14 '17 at 23:43

0 Answers0