tags:

views:

56

answers:

2

With c++, Is there a way to get a derived class to inherit its own static initializer? I am trying to do something like the following:

class Base {

public:
        class StaticInit {
                public:
                virtual StaticInit() =0;
        };
};



class Derived: public Base {
  public:
        virtual StaticInit::StaticInit() {
           //do something with the derived class
        }
        static StaticInit init;
  }

static Derived::StaticInit init;

it would also be nice if I didn't have to define the init var in each derived class. I am currently redefining the StaticInit internal class in each derived class but it seems redundant.

Each derived class is a singleton, and I need the instance to be stored in a lookup table at program startup.

+2  A: 

I use templates to do this, rather than inheritance - something like:

template <typename T>
struct StaticInit {
     StaticInit() {
         // do whatever with T
     }
};

in use:

static StaticInit <SomeClass> init;
anon
I basically went with your solution.
AC
+2  A: 

Use the CRTP:

template <class D>
class Base {
public:
    class StaticInit {
    public:
        StaticInit() { D::initStatic(*this); }
    };
    static StaticInit init;
};

template <class D>
Base<D>::StaticInit init;

class Derived: public Base<Derived> {
public:
    initStatic(Base<Derived>::StaticInit& s) {
        // Do derived-specific initialisation on s.
    }
}
Marcelo Cantos
That's what I was looking for. Thank you
AC
I am getting a compiler error at the line Base<D>::StaticInit init;expected constructor, destructor, or type conversion before ‘init’I think that should be Base<D>::StaticInit Base<D>::init;but I still get same error but now before Base<D>
AC