Hi,
please don't be too harsh if I made stupid errors creating this simple
example from my more complex case.
Suppose I have a class like this:
class BOOK
{
const string title;
const string author;
const int pages;
const double price;
static map<string, BOOK> MyBooks;
BOOK(const string& title_, const string& author_,
const int pages_, const double price_);
BOOK(const string& title_);
const BOOK& findByTitle(con st string& title);
}
I fill the map with books created by the 4-argument constructor. I use
findByTitle to look up books in the map. My problem is with the
constructor that takes a title. About the only way to define this
seems to be:
BOOK::BOOK(cons t string& title_)
: title(title_),
author(findByTi tle(title_).aut hor)
pages(findByTit le(title_).page s)
price(findByTit le(title_).pric e)
{}
The problem is that findByTitle is called 3 times. That's not very
efficient. If my members were non-const I could do
BOOK::BOOK(cons t string& title_)
: title(title_)
{
BOOK book = findByTitle(tit le_);
author = book.author;
pages = book.pages;
price = book.price;
}
But since my books don't have a habit of suddenly changing their
author, I think those members *should* be const. Any elegant
solutions?
Thanks,
Wolfram
please don't be too harsh if I made stupid errors creating this simple
example from my more complex case.
Suppose I have a class like this:
class BOOK
{
const string title;
const string author;
const int pages;
const double price;
static map<string, BOOK> MyBooks;
BOOK(const string& title_, const string& author_,
const int pages_, const double price_);
BOOK(const string& title_);
const BOOK& findByTitle(con st string& title);
}
I fill the map with books created by the 4-argument constructor. I use
findByTitle to look up books in the map. My problem is with the
constructor that takes a title. About the only way to define this
seems to be:
BOOK::BOOK(cons t string& title_)
: title(title_),
author(findByTi tle(title_).aut hor)
pages(findByTit le(title_).page s)
price(findByTit le(title_).pric e)
{}
The problem is that findByTitle is called 3 times. That's not very
efficient. If my members were non-const I could do
BOOK::BOOK(cons t string& title_)
: title(title_)
{
BOOK book = findByTitle(tit le_);
author = book.author;
pages = book.pages;
price = book.price;
}
But since my books don't have a habit of suddenly changing their
author, I think those members *should* be const. Any elegant
solutions?
Thanks,
Wolfram
Comment