Advertisement

offsetof and multiple inheritance

Started by August 02, 2008 04:29 PM
0 comments, last by WitchLord 16 years, 4 months ago
I stumbled across and interesting article on the net, that dealt with multiple inheritance and the this pointer. But it also notes that offsetof might not always give the correct offset. I'm shure most of the c++ gurus here already knew this before their birth, but this is new to me. I thought it would be a good idea to share it with others. What this article says: Assume we have the classes defined as followed:

class Foo
{
public:
    int a;
    int b;
};

class Bar
{
public:
    int c;
};

class Multi:
	public Foo,
	public Bar
{
public:
	int y;
};

And we want to register some variables with angelscript, we certainly need to use offsetof. However we really need to be carefull wich class the chose to offset from:

Multi m;

offsetof( Multi, a ) returns 0
offsetof( Multi, b ) returns 4
offsetof( Multi, c ) returns 8
offsetof( Multi, y ) returns 12

However,

offsetof( Bar, c ) returns 0 // <--attention

I'm abit frightened that he even claims that offsetof( Multi, c ) doesn't compile on gcc (or other compilers as well), because certain casts don't work on NULL pointers (wich are required by the offsetof macro). Currently, I only create simple chains of inheritance, that is NPC inherits from BaseMonster wich inherits from ScenehraphNode. But this could cause problems when someone uses multiple inheritance.
You're absolutely right.

In addition to that when casting a pointer between base classes in a class with multiple inheritances the pointer may also change value.

AngelCode.com - game development and more - Reference DB - game developer references
AngelScript - free scripting library - BMFont - free bitmap font generator - Tower - free puzzle game

This topic is closed to new replies.

Advertisement