Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 915
ChrisD Avatar asked Dec 31 '15 02:12

ChrisD


People also ask

What is push back in vector?

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.

How do you pushback a vector to a 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.


1 Answers

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
like image 122
songyuanyao Avatar answered Oct 11 '22 13:10

songyuanyao