Daniel
Daniel

Reputation: 57

Incomplete Type of Nested Class

I have a code in the following form:

class Trie{
public:
    Trie( ) : root( new TrieNode( ) ){ };

    // Inserts a word into the trie.
    void insert( std::string word );

    // Returns if the word is in the trie.
    bool search( std::string word );

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    bool startsWith( std::string prefix );

private:
    class TrieNode;
    std::unique_ptr<TrieNode> root;
};

class Trie::TrieNode{
public:
    TrieNode( ) : eow( false ){ };

    TrieNode* appendChar( char tar );

    void end( );

    bool isEnd( );

    TrieNode* getChar( char tar );

    int getInd( char tar );

private:
    std::array<std::unique_ptr<TrieNode>, 26> data;
    bool eow;                        // End of word
};

However, at the third line, Trie(): root( new TrieNode() ), compiler continue complains that TrieNode is incomplete. How can I fix it?

Thanks!

Upvotes: 1

Views: 509

Answers (1)

vsoftco
vsoftco

Reputation: 56557

Define Trie's constructor after the TrieNode definition

class Trie::TrieNode{...}

// must be AFTTER the class Trie is fully defined
Trie::Trie( ) : root( new TrieNode( ) ){ };

otherwise the constructor of Trie needs the full definition of TrieNode, as it needs to construct a new object, hence your error.

Upvotes: 3

Related Questions