vendredi 3 février 2017

is it ok to abuse reinterpret_cast to convert an object to a derive class when it is not?

The following code compiles and works correctly, allowing me to gain access to protected fields of a class. But is this an ok thing to do? Feel dirty, but what do i know coming from Java:

#include <iostream>

class Base {
  public:
    Base() : _f(42) {
    }
    int getF() { return _f; }
  protected:
    int _f;
};

class Der : public Base {
  public:
    void setF(int f) { _f = f; }
};

int main(int argc, char ** argv) {
  Base *b = new Base();
  std::cout << b->getF() << std::endl;
  Der *d = reinterpret_cast<Der*>(b);
  d->setF(37);
  std::cout << b->getF()<< std::endl;
}

And if I am right and this is not ok, what is a good way expose internal encapsulated data fields of an object which normally don't need to be modified, but do need to be changed in testing? The instance is created deep inside other components, so changing its type is not trivial.

Aucun commentaire:

Enregistrer un commentaire