Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No appropriate default constructor available [duplicate]

I'm getting the following error in my C++ program:

1>          c:\users\thom\documents\cworkspace\barnaby\barnaby\timezone.cpp(14) : see reference to class template instantiation 'std::map<_Kty,_Ty>' being compiled

This is down a bit in the error stack but points to this line of code:

static std::map<const std::string, Timezone>    timezoneMap;

The reason is that Timezone has a rather elaborate constructor, but no default constructor. Here's that part of the error:

c:\program files\microsoft visual studio 10.0\vc\include\map(215): error C2512: 'Timezone::Timezone' : no appropriate default constructor available

1> c:\program files\microsoft visual studio 10.0\vc\include\map(210) : while compiling class template member function 'Timezone &std::map<_Kty,_Ty>::operator [](const std::basic_string<_Elem,_Traits,_Ax> &)'

My question is, why? Why is the map trying to construct a Timezone object? Why should it need too if I always put fully formed objects into my map? Especially, why this error when I initialize the map?

like image 465
Thom Avatar asked Nov 04 '11 17:11

Thom


People also ask

How do you call a default constructor in C++?

A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A() .

What is the primary purpose of a default constructor?

This is a constructor initializes the variables of the class with their respective default values (i.e. null for objects, 0.0 for float and double, false for boolean, 0 for byte, short, int and, long).

How does a default constructor differ from other constructors?

A Default constructor is defined to have no arguments at all as opposed to a constructor in general which can have as many arguments as you wish.


2 Answers

You're probably using the map's operator[] which does require the default constructor (if it didn't, how would it handle the case where the key doesn't exist in the map?). If you use insert instead you may be able to get away with not providing one (I can't recall if the standard requires a default constructor for all maps, or just when you use that operator).

like image 103
Mark B Avatar answered Sep 28 '22 10:09

Mark B


The map object needs a default constructor when you access the structure using [] (my previous explanation was so convoluted as to be meaningless - sorry). See: Why does the C++ map type argument require an empty constructor when using []?

like image 23
drdwilcox Avatar answered Sep 28 '22 10:09

drdwilcox