Pergunta

I've got a class:

class Fruit
{
protected:
    int Vitamins
    [...]
public:
    [...]
}

a structure:

struct InTheMatrixFruit
{
  int           vitamins;
  virtual       ~InTheMatrixFruit();
};

and a function which takes a reference on Fruit:

void function(Fruit &fruit);

in this function if I write:

reinterpret_cast<InTheMatrixFruit&>(fruit).vitamins = 300;

It does modify the vitamins protected value.

But, If I remove the virtual like this:

struct InTheMatrixFruit
    {
      int           vitamins;
      ~InTheMatrixFruit();
    };

It doesn't work anymore.

Why it works with virtual and not without ?

I'm thinking about the VTables.

Thanks in advance :)

Foi útil?

Solução 2

Your declaration of Fruit probably contains at least a virtual function.

In common implementations of virtual functions a virtual table is used. A pointer to the virtual table is stored as the first element in the memory representation of your object. It doesn't matter where you declare a virtual function, the virtual table will always be at the beginning.

So by declaring a virtual function in InTheMatrixFruit you create a "padding" before the int vitamins so it matches with the vitamins of Fruit.

Outras dicas

Because the size of the class instance changes and, with it, the offset to the vitamins member. This is beacuse a virtual function will cause a vtable pointer to be stored inside the instance before the memory allocated to the member, as you guessed.

Beware! reinterpret_cast could kill your kittens!

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top