I am learning to use objects and inheritance and I'm having some trouble to write the constructors for the derived class.
The base class is a simple 'item' with a title, an author, the year the item was written and some notes. I want that when building the item the title and author fields are mandatore, but the other optional. So I have written a constructor with two of the parameters optional.
// item.hpp
class Item
{
public:
std::string title;
std::string author;
unsigned int year;
std::string notes;
Item(const std::string &t,
const std::string &a,
const unsigned int y = 0,
const std::string &n = "")
: title{t}, author{a}, year{y}, notes{n}
{ };
}
Now I have a derived class: 'Book', and I am trying to write the constructors but keep getting errors that 'call to constructor of Book is ambiguous'
// book.hpp
class Book : public Item
{
public:
unsigned int pages;
std::string series;
// Fill only the fields for Item
Book(const std::string &t,
const std::string &a,
const unsigned int y = 0,
const std::string &n = "")
: Item(t, a, y, n)
{ };
// Fill all the fields for Book
Book(const std::string &t,
const std::string &a,
const unsigned int y = 0,
const std::string &n = "",
const unsigned int p = 0,
const std::string &s = "")
: Item(t, a, y, n), pages{p}, series{s}
{ };
// Maybe there's no notes
Book(const std::string &t,
const std::string &a,
const unsigned int y = 0,
const unsigned int p = 0,
const std::string &s = "")
: Item(t, a, y), pages{p}, series{s}
{ };
}
Now, if I try to build a book like so:
Book b("a", "b");
I get the error that the constructor call is ambiguous.
My question is this: How should I solve the problem of 'wanting to have more than one constructor with default parameters so that I don't have to fill all the parameters'?
I think that the first constructor of 'Book' can be removed, as it is a 'subset' of the second one. But I don't know how to handle the third one. Any suggestions?
EDIT: I had also thought of building empty objects and just fill all the members later by b.member = whatever but that seemed not very good.
Thanks in advance.
Bookare sameItem's constructor be default values wrapped with round brackets instead of braces: Item(const std::string &t, const std::string &a, const unsigned int y = 0, const std::string &n = "") : title(t), author(a), year(y), notes(n)