Search code examples
c++stlvirtualabstract-base-class

STL map and pure virtual base class


I have not used C++ in a long time. I'm trying to display some polymorphic behavior:

class func {
    public:
    virtual void print() = 0;
};

class func1 : public func {
    public:
    void print () { cout << "FUNC 1" << endl; };
};

class func2 : public func {
   public:
     void print () { cout << "FUNC 2" << endl; };
};


static map<string,func *> myMap;
static func1 f1 = func1 ();
static func2 f2 = func2 ();
myMap["func1"] = &f1;
myMap["func2"] = &f2;

So In my main function, when I call:

myMap["func1"]->print();
myMap["func2"]->print();

I would expect:

FUNC 1
FUNC 2

Not sure if this is the right way to do this. When I compile the code, it gives me this error:

test.cc:31: error: expected constructor, destructor, or type conversion before ‘=’ token
test.cc:32: error: expected constructor, destructor, or type conversion before ‘=’ token

Which refers to these lines:

myMap["func1"] = &f1;
myMap["func2"] = &f2;

Thank you.


Solution

  • Expression statements, like those assignment statements, can only go inside functions.

    In C++11, you can initialise the static map using brace-initialisation:

    static map<string,func *> myMap = {
        {"func1", &f1},
        {"func2", &f2}
    };
    

    If you're stuck in the past, then either populate it in a function (perhaps main, or something you call before doing anything with the map), or write a function to return a populated map:

    std::map<string,func*> make_map() {
        std::map<string,func*> map;
        map["func1"] = &f1;
        map["func2"] = &f2;
        return map;
    }
    
    static std::map<string,func *> myMap = make_map();
    

    A better idea might be to avoid non-trivial global variables, if possible; they often bring a world of pain.