no appropriate default constructor, func argument

So I have a class called Library:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Library{
public:
	void add_book(Book);
	void add_patron(Patron);
	void book_out(Book, Patron);

	struct Transaction{
		Transaction(Book, Patron, Date);

		Book book;
		Patron patron;
		Date date;
	};
private:
	vector<Transaction> trans;
	vector<Book> books;
	vector<Patron> patrons;
};


And I want to make a constructor for Transaction.

I figured this should work:

1
2
3
4
Library::Transaction::Transaction(Book b, Patron p, Date d)
{

}


However, I'm getting an error that there is no default constructor available for Book, Patron and Date(error c2512). I know how to fix this, by defining a default constructor for these classes. But why is this necessary? I'm not creating an object in the function's argument list, right?
Last edited on
A vector<T> requires T to be default constructible.

EDIT:

Also, unless you initialize the Transaction members using
an initialization list, they need to be default constructible.
Last edited on
This is hurting my brain, before I created a constructor for Transaction everything was fine. I didn't have a default constructor for vector<Book>, but I didn't get an error for that.
Some vector member functions won't
work unless T is default constructible:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <vector>

struct MyClass
{
    MyClass(int n) {}
};

int main()
{
    std::vector<MyClass> v;

    v.resize(5);
}

But your problem probably is that you don't use initialization lists:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
struct MyClass
{
    MyClass(int n) {}
};

struct MyOtherClass
{
    // this will work without MyClass::MyClass()
    MyOtherClass(MyClass mc): my_class(mc) {}

    MyClass my_class;
};

struct YetAnotherClass
{
    // this won't work without MyClass::MyClass()
    YetAnotherClass(MyClass mc) { my_class = mc; }

    MyClass my_class;
};

int main()
{
    MyClass mc(4);

    MyOtherClass moc(mc);

    YetAnotherClass yac(mc);
}
Last edited on
You're right, when I initialize like MyOtherClass from your example I get no error.

Thanks a lot, your example was a big help. :)
Topic archived. No new replies allowed.