Search code examples
c++classstructvirtualvtable

Modify protected value with structure


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 :)


Solution

  • 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.