Search code examples
c++functionmethodsstructdeclare

Why don't methods of structs have to be declared in C++?


Take, for example, the following code:

#include <iostream>
#include <string>

int main()
{
    print("Hello!");
}

void print(std::string s) {
    std::cout << s << std::endl;
}

When trying to build this, I get the following:

program.cpp: In function ‘int main()’:
program.cpp:6:16: error: ‘print’ was not declared in this scope

Which makes sense.

So why can I conduct a similar concept in a struct, but not get yelled at for it?

struct Snake {
    ...

    Snake() {
        ...
        addBlock(Block(...));
    }

    void addBlock(Block block) {
        ...
    }

    void update() {
        ...
    }

} snake1;

Not only do I not get warnings, but the program actually compiles! Without error! Is this just the nature of structs? What's happening here? Clearly addBlock(Block) was called before the method was ever declared.


Solution

  • A struct in C++ is actually a class definition where all its content is public, unless specified otherwise by including a protected: or private: declaration.

    When the compiler sees a class or struct, it first digests all its declarations from inside the block ({}) before operating on them.

    In the regular method case, the compiler hasn't yet seen the type declared.