Insert a reference into a vector<>

Hello everybody,
This is a simplification of my code. The error is on the last line, when i execute the push_back.
The error is: error:
1
2
no matching function for call to ‘std::vector<abbonato*, std::allocator<abbonato*> >::push_back(const abbonato&)’
/usr/include/c++/4.4/bits/stl_vector.h:733: note: candidates are: void std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = abbonato*, _Alloc = std::allocator<abbonato*>] 

I suppose that there is a mismatch between the vector's type and the variable abb.

1
2
3
4
5
6
7
8
9
10
11
#include <vector>
using namespace std;
class abbonato{
};
class filiale: public abbonato{
  private:
    vector<abbonato*>a;
  public:
    void inserisci(const abbonato &abb ){
    a.push_back(abb);
    };
you are trying to push variable to vector containing pointers to said variable.
Maybe you want to push its address?
a.push_back(&abb);
closed account (zb0S216C)
It's not safe to add "abb" to "abbonato::a" since the referent of "abb" may be a temporary object.

Wazzak
Last edited on
abb should be a pointer to type abbonato.
MiiNiPaa, thank you for the reply, but I want to save the value located in the abb's address
abb is const. You cannot push_back() it as a non const pointer. Try this:

a.push_back(new abbonato(abb));
Thank you coder777, and for example, if abbonato is an abstract class, from which I derive some subclasses and a is a vector of polymorphic pointers? I cannot allocate an object of abstract type.
Make abb non-const and pass address to push_back()
But so I save the address, not the value, or not?!
Make abb non-const and pass address to push_back()
and take care that you never pass the address of a local variable
Topic archived. No new replies allowed.