Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No matching member function for call to 'push_back' error

//fleet.h 
#include "ship.h"
#include <vector>
#include <iostream>
#ifndef fleet_h
#define fleet_h
using namespace std;

class fleet
{
public:

//Add_ship and remove_ship method
bool add_ship(ship const &s);

private:
vector<ship*> ships;
};

//Add_ship method
bool fleet::add_ship(ship const & s){
    ships.push_back(&s); 
       return true;
}
#endif /* fleet_h */

The program gives me this error and I'm not sure what did I do wrong. ship objects are added to fleet via a method called add_ship, which takes a pointer to a ship.

No matching member function for call 'push_back'
like image 675
Neung Chung Avatar asked Oct 10 '18 07:10

Neung Chung


People also ask

What does no matching function for call mean?

No matching function for call means when we are calling some certain functions, but the id of that function is not matching the argument of the function that is defined. Hence we obtain an error 'no matching function for a call' to C++.

How do you add elements to a vector in C++?

The vector::insert() function in C++ Basically, the vector::insert() function from the STL in C++ is used to insert elements or values into a vector container. In general, the function returns an iterator pointing to the first of the inserted elements.


1 Answers

//Add_ship method bool     
fleet::add_ship(ship const & s)
{ 
    ships.push_back(&s); (No matching member function for call to 'push_back') 
    return true; 
} 

The error is because of the declaration:

std::vector<ship*> ships;

The vector contains pointers to mutable ships, but the code passes a pointer to a const ship to push_back. You either need to store const pointers in the vector:

 std::vector<const ship*> ships;

Or pass a non const pointer to the push_back:

fleet::add_ship(ship & s)
{ 
    ships.push_back(&s); (No matching member function for call to 'push_back') 
    return true; 
} 

Side note: move the above function to a cpp, move it to the body of the class, or declare/define it as inline, if you don't want to get linker errors.

like image 55
Michael Veksler Avatar answered Sep 18 '22 01:09

Michael Veksler