CyberShot
CyberShot

Reputation: 2335

How to inherit constructor from a non-direct-parent base class

In the very bottom Word class definition, I wanted to be able to inherit Dict's constructor, the Dict(string f) one. However, I can't do that directly since it's not a direct inherit; it follows a tree and its last parent is the Element class.

How would I be able to let the compiler know to let Word class inherit from the base class's instructor(Dict), so that I can perform the Word test("test.txt"); instantiation in main?

#include <iostream>
#include <vector>
#include <sstream>
#include <string.h>
#include <fstream>

using namespace std;

class Dict {
public:
    string line;
    int wordcount;
    string word;
    vector <string> words;

    Dict(string f) { // I want to let Word inherit this constructor
        ifstream in(f.c_str());
        if (in) {
            while(in >> word)
            {
                words.push_back(word);
            }
        }
        else
            cout << "ERROR couldn't open file" << endl;

        in.close();
    }
};

class Element : public Dict {
public:
    virtual void complete(const Dict &d) = 0;
    virtual void check(const Dict &d) = 0;
    virtual void show() const = 0;
};

class Word: public Element {
public:
    Word(string f) : Dict(f) { }; // Not allowed (How to fix?)

    void complete(const Dict &d) { };
};
};

int main()
{
    //Word test("test.txt");
    return 0;
}

Upvotes: 0

Views: 612

Answers (2)

Michael Price
Michael Price

Reputation: 9028

The Element class must expose the ability to call the Dict constructor in question.

In C++98/03, this means that Element must define a constructor with exactly the same parameters which simply calls the Dict constructor, and then Word would use that Element constructor instead of the Dict constructor.

In C++11, you can use constructor inheritance to save lots of typing and prevent possible errors.

Upvotes: 4

Mr_Hic-up
Mr_Hic-up

Reputation: 389

Your Element class should provide the following constructor to:

Element( string iString ) : Dict( iString ) {;}

You'll then be able to call the Element constructor from your Word class which will propagate the call up to Dict.

Upvotes: 2

Related Questions