prosseek
prosseek

Reputation: 190859

c++ "no matching function for call to" error with structure

I have C++ code that maps GUID(unsigned long) to structure.

#include <string>
#include <map>
#include <iostream>

typedef unsigned long GUID;

enum Function {
  ADDER = 1,
  SUBTRACTOR = 2,
  MULTIPLIER = 3,
  SQUAREROOT = 4
};

struct PluginInfo
{
    GUID guid;
    std::string name;
    Function function;

    PluginInfo(GUID _guid, std::string _name, Function _function) {guid = _guid, name = _name, function = _function;}
};

typedef std::map<GUID, PluginInfo> PluginDB;

PluginInfo temp1(1, "Adder", ADDER);
PluginInfo temp2(2, "Multiplier", MULTIPLIER);

PluginDB::value_type pluginDbArray[] = {
    PluginDB::value_type(1, temp1),
    PluginDB::value_type(2, temp2)
};

const int numElems = sizeof pluginDbArray / sizeof pluginDbArray[0];
PluginDB pluginDB(pluginDbArray, pluginDbArray + numElems);

int main()
{
    std::cout << pluginDB[1].name << std::endl;
}

When I compile it, I got error message.

/usr/include/c++/4.2.1/bits/stl_map.h: In member function ‘_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = long unsigned int, _Tp = PluginInfo, _Compare = std::less, _Alloc = std::allocator >]’: mockup_api.cpp:58: instantiated from here /usr/include/c++/4.2.1/bits/stl_map.h:350: error: no matching function for call to ‘PluginInfo::PluginInfo()’ mockup_api.cpp:29: note: candidates are: PluginInfo::PluginInfo(GUID, std::string, Function) mockup_api.cpp:24: note:
PluginInfo::PluginInfo(const PluginInfo&)

What might be wrong?

Upvotes: 2

Views: 4062

Answers (2)

user2100815
user2100815

Reputation:

The problem is that when you say:

 pluginDB[1]

you try to create an entry in the map (because [1] does not exist) and to do that as Jason points out, you need a default constructor. However, this is NOT a general requirement of standard library containers, only of std::map, and only of operator[] for std::map (and multimap etc.), which is a good reason why IMHO operator[] for maps et al should be done away with - it is far too confusing for new C++ programmers, and useless for experienced ones.

Upvotes: 3

Jason
Jason

Reputation: 32520

Any objects you place in a STL container initialized with an initial number of objects (i.e., you're not initializing an empty container) must have at least one default constructor ... yours does not. In other words your current constructor needs to be initialized with specific objects. There must be one default constructor that is like:

PluginInfo();

Requiring no initializers. Alternatively, they can be default initializers like:

PluginInfo(GUID _guid = GUID(), 
           std::string _name = std::string(), 
           Function _function = Function()): 
           guid(_guid), name(_name), function(_function) {}

Upvotes: 3

Related Questions