ChrisD ChrisD - 3 months ago 7
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 {
public:
Foo(std::string s) : _s(s) {}
private:
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
push_back
a valid statement, even though
str
is not a
Foo
?

Answer

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 {
public:
    explicit Foo(std::string s) : _s(s) {}
//  ~~~~~~~~
private:
    std::string _s;
};

and then

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