C++ Access derived class member variable in virtual function

class Car {
    class BaseState {
       explicit BaseState(Car* vehicle) : mVehicle(vehicle) {}
       virtual void run() = 0;

       Car* mVehicle;
    }
    class State1 : public BaseState {
       explicit State1(Car* vehicle) : BaseState(vehicle) {}
       virtual void run() {
           // use data of Car
           ...
           doSomething();
       }
       virtual void doSomething() {
       }
    }
    class State2 : public BaseState {
    }
    ...
}

class Convertible: public Car {
    class State1 : public Car::State1 {
       explicit State1(Convertible* vehicle) : Car::State1(vehicle) {}
       virtual void doSomething() {
           static_cast<Convertible*>(mVehicle)->foldTop();
       }
    }
    class State2 : public Car::State2 {
    }
    ...
    void foldTop() {}
}

All States are derived from the BaseState so that they have the member variable mVehicle to access outer class variables.
However, in each derived class, in all functions of each State, static_cast is needed to access derived class member variables and functions.

Any better solution?

  1. In each State of derived classes, add another pointer (e.g., Convertible *mConvertible). Each State has duplicate pointers (mConvertible and mVehicle) point to the same object. Does not look right.
  2. Use a virtual Getter instead of mVehicle in base class. There will be excessive Getter calls in base class.


Source: c++

Leave a Reply