Wednesday, May 6, 2009

Static data members in inheritance

A static data member means that one copy of data would be shared among all instances of the same class. It is true even when inheritance is involved.

class base
{
public: static wchar_t * s_pName;
};

wchar_t * base::s_pName = L"base";

class derived1 : public base { };

class derived2 : public base { };

int _tmain(int argc, _TCHAR* argv[])
{
derived1 d1;
d1.s_pName = L"derived1";

derived2 d2;
d2.s_pName = L"derived2";

wprintf(L"%s\n", d1.s_pName);
wprintf(L"%s\n", d2.s_pName);

return 0;
}

Since s_pName is a static data member in the base class, all the instances of the derived classes share one copy of the data member. Therefore, the output of the above program would be as following,

derived2
derived2.

Obviously, it is not a desirable output for the instances of derived1 class. To overcome this limitation, we could use a so-called "mixin-style" base class. I replace the angle brackets for a template with square brackets.

template[class T]
class base
{
public: static wchar_t * s_pName;
};

template[class T] wchar_t * base[T]::s_pName = L"base";

class derived1 : public base[derived1] { };

class derived2 : public base[derived2] { };

int _tmain(int argc, _TCHAR* argv[])
{
derived1 d1;
d1.s_pName = L"derived1";

derived2 d2;
d2.s_pName = L"derived2";

wprintf(L"%s\n", d1.s_pName);
wprintf(L"%s\n", d2.s_pName);

return 0;
}

The base class is turned into a template. The template part of the base class ensures that each derived class gets a different s_pName. The output from the above program would be as following,

derived1
derived2.

0 comments:

Post a Comment