Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does C++ know the container class has a push_back function?

Tags:

c++

When I look at std::back_insert_iterator http://en.cppreference.com/w/cpp/iterator/back_insert_iterator

It says the container's push_back method will be called. How does it know if the container has a method of push_back? Does it require a class that extends any virtual class and where is it defined?

like image 538
SwiftMango Avatar asked Nov 30 '22 20:11

SwiftMango


2 Answers

How does it know if the container has a method of push_back?

It doesn't. You'll get a compile error if you try to use it on a container that doesn't have push_back.

Does it require a class that extends any virtual class and where is it defined?

No, it just requires a class that defines it. In general, templates don't use dynamic polymorphism via virtual functions; they just require the code they contain (like container.push_back(thing)) to be valid after argument substitution.

like image 41
Mike Seymour Avatar answered Dec 05 '22 18:12

Mike Seymour


It says the container's push_back method will be called. How does it know if the container has a method of push_back? Does it require a class that extends any virtual class and where is it defined?

No, push_back() is usually not a virtual method.

The std::back_insert_iterator is a template, which is going to call push_back() on the passed object. It the method is missing, you are going to get a compile error.

like image 115
BЈовић Avatar answered Dec 05 '22 18:12

BЈовић