Teererai Marange
Teererai Marange

Reputation: 2132

cpp no matching function call for call to constructor. Why?

Below is my code:

// this code illustrates iterating through a nested hashmap.
#include <iostream>
#include "imported.hpp"
#include <string>
#include <iomanip>
#include <vector>
using namespace std;
#define MAX_LINE_LENGTH 999

using namespace std;

class State
{

  public:
    vector<string> vec;
    string state_string;
    State(string state_string, vector<string> vec);
};

State::State(string state_string, vector<string> vec)
{
    this->state_string = state_string;
    this->vec = vec;
}

class Heuristic
{

  public:
    State goal_state;
    string type;
    Heuristic(string type, State goal_state);
};

Heuristic::Heuristic(string type, State goal_state)
{
    this->type = type;
    this->goal_state = goal_state;
}

int main(int argc, char const *argv[])
{
}

When I try to compile it using:

g++ filename.cpp 

The following output is produced:

$ g++ main.cpp
main.cpp: In constructor ‘Heuristic::Heuristic(std::string, State)’:
main.cpp:36:51: error: no matching function for call to ‘State::State()’
 Heuristic::Heuristic(string type, State goal_state)
                                                   ^
main.cpp:21:1: note: candidate: State::State(std::string, std::vector<std::basic_string<char> >)
 State::State(string state_string, vector<string> vec)
 ^~~~~
main.cpp:21:1: note:   candidate expects 2 arguments, 0 provided
main.cpp:12:7: note: candidate: State::State(const State&)
 class State
       ^~~~~
main.cpp:12:7: note:   candidate expects 1 argument, 0 provided
main.cpp:12:7: note: candidate: State::State(State&&)
main.cpp:12:7: note:   candidate expects 1 argument, 0 provided

I am confused as to why this is happening since I am not even calling the constructor but rather am defining a function's method signature into which the user should be able to pass an existent State object. Please assist.

Upvotes: 2

Views: 899

Answers (1)

P.W
P.W

Reputation: 26800

The Heuristic constructor is built using assignment operators which involves the default construction of its member objects. Since State does not have a default constructor, this form of construction will fail.

There are two ways of solving this:

  1. If the members have user-defined constructors, provide default-constructors also for them .
  2. Use initializer lists for your constructor instead of assignments within the body of the constructor.

Of these two methods, the second one is more preferable. The reasons for this are outlined in the FAQ: Should my constructors use “initialization lists” or “assignment”?

Upvotes: 1

Related Questions