R. Clayton (rclayton@monmouth.edu)
(no date)
I used to think the input argument to vector.push_back() should match the
type of the vector.
It should match, or be convertible to, the type of the vector's element.
For example if you have a vector of objects of class A, you must pass an
object of type A to push_back(). I found out while coding assignment 2 that
you could pass not only an object of A but also any argument that the
constructor of A accepts.
That is correct not only for push_back(), but for any value that needs to type
check. Such constructors are known as (or I call them) conversion
constructors. The compiler may implicitly call conversion constructors to make
expressions type check.
The following code works -
string str = "test";
vector<CompressedString> vec;
vec.push_back(str);
Is this true for all containers and is it compiler specific?
It is true for all classes. If you want to prevent this behavior, tag the
conversion constructors' declarations with the explicit keyword:
explicit CompressedString(std::string &str);
The compiler is prevented from implicitly using conversion constructors tagged
with the explicit keyword.
See Section 12.4 of Koenig and Moo (which is when we'll cover this in class)
for more information.
This archive was generated by hypermail 2.0b3 on Mon May 03 2004 - 17:00:06 EDT