19

I'm beginning to learn C++. In the IDE codeblocks, this compiles:

#include <iostream>
using namespace std;

struct A {};

struct B {
    A a;
}

void hi() {
    cout << "hi" << endl;
}

int main() {
    hi();
    return 0;
}

But this doesn't:

struct B {
    A a;
}

struct A {};

int main() {
    hi();
    return 0;
}

void hi() {
    cout << "hi" << endl;
}

It gives me the errors:

error: 'A' does not name a type
error: 'hi' was not declared in this scope

Should class/function order matter in C++? I thought it doesn't. Please clarify the issue.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
Aviv Cohn
  • 15,543
  • 25
  • 68
  • 131
  • 1
    Seems like this could be a duplicate... – crashmstr Sep 30 '14 at 13:40
  • 1
    Functions should at least be declared before being used. But once you declared them, the order does not matter (or very marginally). For short functions, it might be *slightly* better to group related functions (eg `f` before `g` if `g` calls `f`), perhaps because of cache issues. But this is often irrelevant (and the compiler will often reflush the generated function order). – Basile Starynkevitch Oct 02 '14 at 18:37
  • I would suggest that you get a book on C++ instead of trying to learn the language by playing in an IDE. – Raymond Chen Oct 02 '14 at 19:27

1 Answers1

48

Yes, you must at least declare the class/function before you use/call it, even if the actual definition does not come until afterwards.

That is why you often declare the classes/functions in header files, then #include them at the top of your cpp file. Then you can use the classes/functions in any order, since they have already been effectively declared.

Note in your case you could have done this. (working example)

void hi();    // This function is now declared

struct A; // This type is now declared

struct B {
    A* a; // we can now have a pointer to it
};

int main() {
    hi();
    return 0;
}

void hi() {    // Even though the definition is afterwards
    cout << "hi" << endl;
}

struct A {}; // now A has a definition
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218