jjxd
jjxd

Reputation: 11

C++ Beginner : calling default vs custom constructor

Beginner here - but i was uncertain what exactly to search for this (presumably common) question. I am working on a program where I have a given class (Dictionary). I am supposed to make a concrete class (Word) which implements Dictionary. I should mention that I am not to change anything in Dictionary.

After making a header file for Word, I define everything in word.cpp. I am unsure if I am doing this correctly, but I make the constructor read from a given file, and store the information in a public member of Word. (I understand that the vectors should be private, but I made it public to get to the root of this current issue)

dictionary.h

#ifndef __DICTIONARY_H__
#define __DICTIONARY_H__

#include <iostream>
#include <string>
#include <vector>
#include <fstream>

using namespace std;

class Dictionary
{
public:

    Dictionary(istream&);   
    virtual int search(string keyword, size_t prefix_length)=0;     
};

#endif /* __DICTIONARY_H__ */

word.h

#ifndef __WORD_H__
#define __WORD_H__
#include "dictionary.h"




class Word : public Dictionary{
public:
    vector<string> dictionary_words;
    vector<string> source_file_words;
    Word(istream &file);    
    int search(string keyword, size_t prefix_length);
    void permutation_search(string keyword, string& prefix, ofstream& fout, int& prefix_length);

};
 #endif /* __WORD_H__*/

word.cpp

#include "word.h"

    Word(istream& file) : Dictionary(istream& file)
    {
        string temp;
        while (file >> temp)
        {
            getline(file,temp);
            dictionary_words.push_back(temp);
        }

    }

In word.cpp, on the line "Word::Word(istream& file)", I get this error :' [Error] no matching function for call to 'Dictionary::Dictionary()'.

I've been told this is error is due to "Word's constructor invoking Dictionary's ", but I still don't quite grasp the idea well. I am not trying to use Dictionary's constructor, but Word's. If anyone has an idea for a solution, I would also appreciate any terms related to what is causing this issue that I could look up - I wasn't even sure how to title the problem.

Upvotes: 1

Views: 96

Answers (1)

lamik
lamik

Reputation: 99

Your child class should invoke parent constructor, because parent object are constructed before child. So you should write something like:

Word::Word(isteam& file) : Dictionary(file) 
{ 
   ... 
}

Seems its better described here What are the rules for calling the superclass constructor?

Upvotes: 2

Related Questions