0
class Trie {
private:
    vector<Trie*> children;
    bool isEnd;

    Trie* searchPrefix(string prefix) {
        Trie* node = this;
        for (char ch : prefix) {
            ch -= 'a';
            if (node->children[ch] == nullptr) {
                return nullptr;
            }
            node = node->children[ch];
        }
        return node;
    }
}

Why can the Trie* type appear first in a Trie class definition. The Trie type has not yet been defined.How does the compiler know what Trie* is?

I tried looking online for an answer, but couldn't find it. I think it is a certain knowledge of mine that I have not figured out. Please help me and guide me. Thanks!

y z
  • 1
  • 1
    Compiler doesn't need to know what `Trie` is per se, only how much memory it requires. And from the fields it can easily tell how much. With pointer to `Trie` it's especially easy, all pointers always have the same size, regardless of the type they point to (it's just an address - 1 machine word) – Alexey S. Larionov Aug 03 '23 at 07:35
  • 1
    `class Trie` tells the compiler that `Trie` is a class, for a pointer that's all it needs – Alan Birtles Aug 03 '23 at 07:35
  • 1
    Using a pointer or reference doesn't need a fully defined type. – πάντα ῥεῖ Aug 03 '23 at 07:36
  • 1
    You could make your example more minimal: `class Trie { Trie* child; };`. Just don't drop the asterisk. ;) – JaMiT Aug 03 '23 at 07:36
  • 1
    Key concept: [incomplete type](https://stackoverflow.com/questions/tagged/incomplete-type). – hlovdal Aug 03 '23 at 07:43
  • Thanks everyone, I have understood the question, thank you for your answers! ! !Thank you! – y z Aug 03 '23 at 07:46
  • Explanation without using any programming jargon: you can know *where* something is without having any idea about *what* it is. – molbdnilo Aug 03 '23 at 09:11

0 Answers0