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
?
vector::push_back() vector::pop_back() It is used to add a new element at the end of the vector. It is used to remove a new element at the end of the vector.
Insertion in Vector of Vectors Elements can be inserted into a vector using the push_back() function of C++ STL. Below example demonstrates the insertion operation in a vector of vectors. The code creates a 2D vector by using the push_back() function and then displays the matrix.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With