Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does class/function order matter in C++?

Tags:

c++

function

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.

like image 399
Aviv Cohn Avatar asked Sep 30 '14 13:09

Aviv Cohn


1 Answers

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
like image 131
Cory Kramer Avatar answered Sep 21 '22 15:09

Cory Kramer