Jump to content
  • Advertisement
Sign in to follow this  
SiS-Shadowman

offsetof and multiple inheritance

This topic is 3788 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
Advertisement
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!