I am reading a book and got some code for class designing that I do not really understand.
class Queue {
public:
Queue(size_t capacity) {}
explicit Queue(int capacity) : entries_(capacity) {}
...
private:
vector<int> entries_;
...
};
And another similar one,
class LruCache {
public:
LruCache(size_t capacity) {}
explicit LruCache(int capacity) : capacity_(capacity) {}
...
private:
int capacity_;
...
};
I have two questions,
Could we overload methods purely on the
explicit
keyword, like theconst
keyword? In my case, the argument type is a little different though, anint
and asize_t
.A more important question is why. Why do we need a overloaded
explicit
constructor? In C++ primer, I believe it says overloading functions with similar argument types is not recommended.
edit:
My 2nd question is more about the code piece above. Why does it have a constructor with an int
argument and then an explicit
constructor with a size_t
argument, and int
and size_t
are types that are really close. So it should not be necessary to define two constructors, for each of them. I believe the author defines two constructors for a reason, but I do not know why, and that should be my 2nd question about. Not a general question about what does explicit
keyword do. Sorry.