Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

No matching function for call to class constructor?

I am currently working on assignment for one of my classes.
I am trying to construct a class, but when I try to run the program I get this error:

no matching function for call to 'Word::Word()

here is the code that I created:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include <iostream>
//#include <iomanip>
//#include <string>
//#include <cctype>
//#include <cmath>
//#include <fstream>
//#include <vector>
//#include <algorithm>

using namespace std;

string wordToTest;

class Word{
    public: 
        int length;
        string word;
        void TestForPalindrome();
        Word(string w){
            word = w;
            length = word.length();
        }
};

void Word::TestForPalindrome(){
    string testWord;
    for(int i = length; i < 0; i--){
        testWord += word[i];
    }
    if (testWord == word){
        cout << word << " is a palindrome!";
    } else if (testWord != word){
        cout << word << " is not a palindrome";
    }
}

//error occurs here
void GetInput(){
    cout << "enter a word: \n";
    cin >> wordToTest;
    Word Palindrome(wordToTest);
    Palindrome.TestForPalindrome();
}



int main(){
    
    return(0);
}

the error occurs at the comment.
Thanks in advance for any help on this!

>Solution :

Because you only define one constructor that requires a string, so you must initialise Palindrome with a string. So you can use a temporary string to receive the input. By the way, global variable is not recommanded.

Here the update GetInput():

void GetInput(){
    string tmp; // Use a temporary string to receive.
    cout << "enter a word: \n";
    cin >> tmp;
    Word Palindrome(tmp); // Initialise with the temporary string.
    std::cout << Palindrome.word << std::endl;
    Palindrome.TestForPalindrome();
}

I also find another issue with your code: in the function TestForPalindrome():

for(int i = length; i < 0; i--){
        testWord += word[i];
    }

You want to create a reversed string of word, however, since length is greater or equal than 0, and the condition of loop is i < 0, so code in this loop will never be executed.

Here is an update of the loop:

for (int i = length - 1; i >= 0; i--) {
        testWord += word[i];
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading