gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

C/C++ > Static member inheritance

#144633 - Lick - Mon Nov 05, 2007 2:50 am

Hey, I've got a derived class, that I want to put a static "member" in. However doing it the normal way results in every derived class from the same base class spawning the compiler error: Multiple definition of "SomeDerivedClass::my_static_var" ... first defined here ...

How do I solve this without using a static global?
_________________
http://licklick.wordpress.com

#144642 - keldon - Mon Nov 05, 2007 8:03 am

What exactly is this "normal way"?

#144674 - Lick - Mon Nov 05, 2007 5:11 pm

Code:
class Base {};

class Derived1 : public Base { protected: static int member; };

class Derived2 : public Base {};


Gives the multiple definition error.
_________________
http://licklick.wordpress.com

#144692 - sajiimori - Mon Nov 05, 2007 8:54 pm

There's nothing wrong with the part you posted. Could you post a full example (including 'main'), along with the full text of the error message?

#155677 - Scorp - Fri May 02, 2008 3:29 pm

Are you talking about multiple inheritance / Diamond inheritance ?

(This is a real pig if i remember)...

e.g.

class base
{
int some_member;
}

class Deriv1 : public virtual base
{
}

class Deriv2 : public virtual base
{
}

Class Final : public Deriv1, Deriv2
{
Final() {
some_member = 123; // ok
}
}


Note the "public virtual" declaration, this uses virtual inheritance, so when Deriv1 + Deriv2 are joined they share the same base class (and not attempt to instantiate a 2nd copy of base which would cause the error you've given).

Hope that helps (could have done with an example snippet of code, i could be talking about completely the wrong thing)