Abstract Function Object

How to use an abstract function object ?
I mean i want to define a class that only implements operator () , like this :
1
2
3
4
5
6
7
8
9
10
11
  
    class IndexCalculator{
    public:
        IndexCalculator();
        virtual int operator() (char c) = 0;
    };
    class Int_index:public IndexCalculator{
    int operator() (char c){
        return int(c - '0');
    }
    };

I use it as a pointer member in this class so i don't get the error :
Can't instantiate an abstract class .
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
    template<class S>
    class EHT{
    public:
        EHT(int num_sons,IndexCalculator* ic):
        num_sons(num_sons),ic(ic),root(new EHT_Node<S>(NULL,NULL,num_sons)){}
        ~EHT(){
            delete ic;
            root->destroy();
            delete root;
        }
        EHT_Error buildTree(std::list<std::string> keys,std::list<S> data);
        EHT_Error getSons(std::string id,Storage<class T> storage);
        void printEHT();
    private:
        int num_sons;
        IndexCalculator* ic;
        EHT_Node<S>* root;
    };

**This is the problematic function :**
1
2
3
4
5
6
7
8
9
10
11
    template<class S>
    EHT_Error EHT<S>::buildTree(std::list<std::string> keys,std::list<S> data){
    std::list<S>::iterator d_i=data.begin();
    std::list<std::string>::iterator i=keys.begin();
    for(;i!= keys.end() && d_i!= data.end();i++,d_i++){
        int len = strlen(*i);
        EHT_Node<S>* it = root;
        for(int j=0;j<len;j++){
            std::string str_key=*i;
            int index = (*ic)(str_key[j]);

This is the line i call the function object :
int index = (*ic)(str_key[j]);

This is in main function :
1
2
3
4
    Int_index* int_index;

    EHT<int> t(10,int_index);
    t.buildTree(keys,data);


the problematic line is :
int index = (*ic)(str_key[j]);

To explain :
ic - is a pointer to a function object that implements operator() .
Last edited on
On line 6, you are setting len to be strlen of a std::string - that shouldn't work. Rather, you would like something like this for your inner loop:
 
for (int j = 0; j < i->size(); ++j)


Also, you never allocated int_index in your main function, hence you will get some kind of segmentation fault. Try the following instead:
 
EHT<int> t(10, new Int_index);


Also, please tell us what errors or problems you are getting - give us the whole error message, there might be things there you are missing.
http://www.eelis.net/iso-c++/testcase.xhtml
A testcase consisting of randomly copy&paste'd bits of code that you thought were relevant can obviously not reproduce the problem.


You may want to initialize your variables before using them. `int_index' is pointing to garbage.
Topic archived. No new replies allowed.