Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a default constructor required when storing in a map?

I'm getting the error:

error: no matching function for call to 'A::A()'
note: candidates are: A::A(const A&)
note:                 A::A(const std::string&, size_t)

From this:

#include <map>
#include <string>

using std::map;
using std::string;

class A {
public:
    string path;
    size_t size;
    A (const string& p, size_t s) : path(p), size(s) { }
    A (const A& f) : path(f.path), size(f.size) { }
    A& operator=(const A& rhs) {
        path = rhs.path;
        size = rhs.size;
        return *this;
    }
};

int main(int argc, char **argv)
{
    map<string, A> mymap;

    A a("world", 1);
    mymap["hello"] = a;      // <----- here
    A b(mymap["hello"]);     // <----- and here
}

Please tell me why the code wants a constructor with no parameters.

like image 319
William Morris Avatar asked Jan 04 '13 20:01

William Morris


People also ask

Does MAP require default constructor?

The default constructor is not required. Certain container class member function signatures specify the default constructor as a default argument. T() must be a well-defined expression ...

Why are default constructors used?

They are used to initialize member objects. If default values are supplied, the trailing arguments can be omitted in the expression list of the constructor. Note that if a constructor has any arguments that do not have default values, it is not a default constructor.

Why do we need constructors in CPP?

C++ Constructors. Constructors are methods that are automatically executed every time you create an object. The purpose of a constructor is to construct an object and assign values to the object's members. A constructor takes the same name as the class to which it belongs, and does not return any values.

Do you need a default constructor CPP?

For example, all members of class type, and their class-type members, must have a default constructor and destructors that are accessible. All data members of reference type and all const members must have a default member initializer.


1 Answers

Because map requires DefaultConstructible values, since when using subscript operator and the key is not found it adds it mapped to a default constructed value.

like image 63
K-ballo Avatar answered Oct 31 '22 05:10

K-ballo