lundi 17 juillet 2017

Call derived class non virtual member functions from base class pointer

We know that, derived class members functions can be accessed through a base class pointer in C++ , provided that these member functions have to be virtual. Is there a means to access derived class member functions whicg are NOT virtual or pure virtual from base class pointer.

i.e. I want to call derived class member functions which are present only in derived class & not in base class through base class pointer. How would I achieve this ?

For example, if i design a factory design pattern,

class Vehicle {
public:
    virtual void printVehicle() = 0;
    static Vehicle* Create(VehicleType type);
};
class TwoWheeler : public Vehicle {
public:
    void printVehicle() {
        cout << "I am two wheeler" << endl;
    }
    void Some2WheelerONLYSpecificOPeration()
    {

    }
};
class ThreeWheeler : public Vehicle {
public:
    void printVehicle() {
        cout << "I am three wheeler" << endl;
    }
void Some3WheelerONLYSpecificOPeration()
    {

    }
};
class FourWheeler : public Vehicle {
    public:
    void printVehicle() {
        cout << "I am four wheeler" << endl;
    }
void Some4WheelerONLYSpecificOPeration()
    {

    }
};

// Factory method to create objects of different types.
// Change is required only in this function to create a new object type
Vehicle* Vehicle::Create(VehicleType type) {
    if (type == VT_TwoWheeler)
        return new TwoWheeler();
    else if (type == VT_ThreeWheeler)
        return new ThreeWheeler();
    else if (type == VT_FourWheeler)
        return new FourWheeler();
    else return NULL;
}

int main()
{
Vehicle* basePtr =   Vehicle::Create(VT_TwoWheeler);
basePtr->Some2WheelerONLYSpecificOPeration();   //HOW TO ACHIEVE THIS CALL

basePtr =   Vehicle::Create(VT_ThreeWheeler);
basePtr->Some3WheelerONLYSpecificOPeration(); //HOW TO ACHIEVE THIS CALL

basePtr =   Vehicle::Create(VT_FourWheeler);
basePtr->Some4WheelerONLYSpecificOPeration(); // //HOW TO ACHIEVE THIS CALL
}

Aucun commentaire:

Enregistrer un commentaire