tags:

views:

33

answers:

3

Hi,

I have a central list of implementations of an interface and would like for derived classes to be able to register themselves in that list without having to add them in some central place. For example:

// interface.h
struct MyInterface;
std::vector<MyInterface*>& InterfaceList();

struct MyInterface {
    MyInterface() {
       InterfaceList().push_back(this);
    }
    virtual ~MyInterface() {}
    // ...
};

// derived.cpp
#include "interface.h"
class MyImplementation: public MyInterface {
public:
    MyImplementation() {
    }
    // ...
};

MyImplementation impl;

This doesn't seem to work. For reasons I don't understand, the constructor of MyInterface never gets called - I would have thought that the instance of the derived class would call it at startup. I know it's possible to do something along these lines since I've seen other libraries doing it - but haven't managed to figure out what it is that I'm doing wrong.

Thanks :)

Edit: Sorry, missed a pair of braces and a reference. InterfaceList() is a function that returns a reference to a vector.

Edit part 2: Have now got it working in a reduced example, but can't get it to work in the files for the derived implementations - but that technique is working in another project. There must be something slightly different in those files which is causing it to fail - but it appears the problem isn't in the code I posted. Don't really want to post big chunks of my employer's projects though so I guess I'll have to keep fiddling myself. Thanks for the suggestions so far though :)

+1  A: 

This is the issue:

std::vector<MyInterface*> InterfaceList();

should be

std::vector<MyInterface*> InterfaceList;
Anders K.
+3  A: 

You example does not compile under VS2008. What compiler are you using? When you change the second line in interface.h to

std::vector<MyInterface*> InterfaceList;

it works correctly. Just drop the braces.

AOI Karasu
+1  A: 

Following definition of InterfaceList is a kind of function declaration which returns std::vector

std::vector<MyInterface*> InterfaceList();

Change this to

  std::vector<MyInterface*> InterfaceList;
Pardeep