2

I want to extend the C++ namespace of classes in a Linux shared object through inheritance. What are the issues that can arise, in particular involving static objects and member data?

// as a crude example (note: untested code)
// compiled into libBase.so
namespace foo
{
    class Cfoo
    {
    protected:
        static double Pi; // defined outside header
    public:
        Cfoo () {}
        double fooPi () { Pi *= Pi; return Pi; }
    };
}

// compiled into libDerived.so
namespace foo
{
    class Cbar : public Cfoo
    {
        double barPi () { Pi = sqrt(Pi); return Pi; }
    };
} 

Platform: GCC 4.5 on RHEL 5.

ThomasMcLeod
  • 7,603
  • 4
  • 42
  • 80

1 Answers1

2

The order of initialization of (class) global static variables in different translation units is undefined. However, if you wrap the class-static variable Pi into a member function, you replace it with a local static object. Effective C++ Item 4: "Avoid initialization order problems across translation units by replacing non-local static objects with local static objects.". If the object remains globally static, it may happen that it remains uninitialized before the other code uses it..

protected:
     static double PI()
     {
         static double PI = 3.141;
         return PI; 
     }
Community
  • 1
  • 1
tmaric
  • 5,347
  • 4
  • 42
  • 75