Reputation: 59
I have the following code in c++, involving templates :
#include <assert.h>
#include <map>
#include <limits>
template<class K, class V> class interval_mapping {
private:
std::map<K,V> aMap;
public:
interval_mapping( V const& val) {
aMap.insert(
aMap.begin(),
std::make_pair(std::numeric_limits<K>::min(),val)
);
}
void assign( K const& keyBegin, K const& keyEnd, const V& val ) {}
V const& operator[]( K const& key ) const {
return ( --m_map.upper_bound(key) )->second;
}
};
int main()
{
interval_mapping<int, char> myMap;
}
I get the error:
no default constructor exists for class "interval_mapping"
Upvotes: 1
Views: 834
Reputation: 3765
The error should be pretty self-explanatory: you're constructing an interval_mapping
object without passing any arguments, so the class needs a default constructor. Default constructors are only auto-generated by the compiler if you don't provide any other constructors yourself.
You don't need the default constructor to do anything special, so you can just add
interval_mapping() {}
to the class, or
interval_mapping() = default;
if your compiler supports C++11.
If you genuinely didn't want the class to have a default constructor, you need to give an argument in the line in main()
where you create the object.
Upvotes: 2
Reputation: 956
You declare a constructor for interval_mapping
that takes a V const& val
. This is the only constructor declared for interval_mapping
and no default constructors are provided since you have implemented your own.
Then when you try to instantiate an interval_mapping<int, char>
you fail to provide the V const& val
needed by the constructor (in this case that would be a char
it seems). And since there is no available constructor that takes no parameters you see this error.
Upvotes: 0
Reputation: 254431
As the error says, there's no default constructor, since you've declared your own constructor.
Either use that constructor
interval_mapping<int, char> myMap(some_char_value);
or add a default constructor; you probably want it to be empty initially:
interval_mapping() {}
Upvotes: 2