Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force to reimplement a static function in inherit classes

Tags:

c++

I have a program in C++ with plugins (dynamic libs). In the main program, I want to execute a static function to check if i can create a object of this type.

An example without dynamic libs (aren't neccesary to understand the problem):

#include "libs/parent.h"
#include "libs/one.h"
#include "libs/two.h"

int main(int argc, char * argv[])
{
    Parent* obj;

    if (One::match(argv[1]))
        obj = new One();
    else if (Two::match(argv[1]))
        obj = new Two();
}

Now, i have a interface class named Parent. All plugins inherit from this class. Ideally, I have a virtual static function in Parent named match, and all the plugins need to reimplement this function.

The problem with this code is that i can't do a static virtual function in C++, so i don't know how to solve the problem.

Sorry for mi english, i did my best

like image 273
pacopepe222 Avatar asked Apr 25 '10 12:04

pacopepe222


1 Answers

What you have here is classic factory pattern. You want to create an interface named IPluginFactory which would have two methods - match and create (or, optionally, combine them both in a single method). Then each of your plugin DLLs would have a class that implements this interface.

    Parent obj;
    IPluginFactory *one = new OneFactory();
    IPluginFactory *two = new TwoFactory();

    if (one->match(argv[1]))
        obj = one->createObj();
    else if (two->match(argv[1]))
        obj = two->createObj();
like image 83
Fyodor Soikin Avatar answered Sep 30 '22 12:09

Fyodor Soikin