Define namespaces and structs after main | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 52

Define namespaces and structs after main

I was wondering if there is a way to define namespaces and structs after the main function, not including external files with them declared there, just by maybe declaring them before the main, the same way you do with functions. Thank you!

10th Nov 2018, 12:45 PM
Andrea Leoni
Andrea Leoni - avatar
6 Answers
+ 12
Very good question. Forward declarations appear to be possible for structs (and classes), but with a catch. struct foo; //fwd decl struct bar { foo obj; // error: incomplete type foo* obj; // ok }; struct foo { // foo def here }; Forward declarations only tell the compiler that something exists, but not how much memory to allocate to the initialization of an object of its type. A pointer to the object, on the other hand, has a fixed memory size which can be resolved during compile time. As for forward declarations for namespaces, a brief lookup doesn't show any examples. I'm sticking with "not possible" for now. If there's a way, I'm clearly oblivious to it.
10th Nov 2018, 1:37 PM
Hatsy Rei
Hatsy Rei - avatar
+ 8
Thank you so much, this really helped! Hope there was a way for namespaces too xD
10th Nov 2018, 1:40 PM
Andrea Leoni
Andrea Leoni - avatar
+ 6
Thanks a lot for the explanation. I just wanted to find if I could make the main function more visible by defining everithing after it.
10th Nov 2018, 7:27 PM
Andrea Leoni
Andrea Leoni - avatar
+ 5
Sorry, just one more thing. Now, doing like this struct foo; int main() {     foo *var;     return 0; } struct foo {     int num; }; it doesn't give me error. The question is: how do I use the structured type variable from here the same way I would if I defined the struct before the main function? (I can't find a way to legaly access to and manipulate the foo.num integer variable of the example)
10th Nov 2018, 5:51 PM
Andrea Leoni
Andrea Leoni - avatar
+ 2
A forward declaration is usually used in headers to solve cyclic dependencies or to improve compile times. In actual code such as your example you cannot use it, as from the moment you do more than declaration you need to know the specifics (and: var in your example is probably optimised away as it is not used). As for why you'd want forward declaration of namespaces? I have no idea but to me it doesn't make sense. Namespaces are not more than fences that enable you to have multiple types, etc with the same name. A namespaces therefor is nothing that you can declare...
10th Nov 2018, 7:12 PM
Freddy
0
You can put the rest in other files.
11th Nov 2018, 3:43 PM
Freddy