ChrisD ChrisD - 11 months ago 44
C++ Question

Pushing back string to vector of objects

I was browsing some code I wrote for a school project, that at a closer inspection looked weird to me. I had a class similar to the one below:

class Foo {
Foo(std::string s) : _s(s) {}
std::string _s;

int main() {
std::string str = "Hiyo";

std::vector<Foo> f;
f.push_back(str); // Compiles. Weird to me though.
f.push_back(Foo(str)); // Predictably, this compiles as well.

return 0;

Why is the first call to
a valid statement, even though
is not a

Answer Source

Class Foo has a non-explicit ctor taking one argument of type std::string (i.e. Converting constructor), which means it could be implicitly casted from a std::string.

f.push_back(str);      // implicit casting from std::string to Foo
f.push_back(Foo(str)); // explicit casting from std::string to Foo

Note if you make the ctor explicit, the implicit casting will be prohibited.

class Foo {
    explicit Foo(std::string s) : _s(s) {}
//  ~~~~~~~~
    std::string _s;

and then

f.push_back(str);      // invalid now
f.push_back(Foo(str)); // still valid