Declaration Scope

Hello there,

I am facing a problem of converting a large gnu fortran program that I've written myself to C++. I'm using g++ compiler in Ubuntu 14.04. I immediately noticed a bad feature that reminded me of the old Pascal days. If I want to use a class "A" in class "B" I must define class "A" before class "B" not after, otherwise I get an error: "A has not been defined in this scope."

Can anything be done to avoid that? I want to position classes in arbitrary order.

Thanks, - Alex

There is no way to avoid that. C++ uses "single pass" translation which means when something is parsed, you must have all used entities declared. With proper program structure this usually is not a problem: each class resides in own header and implementation unit, so there is no "order" for classes.
There is one way to partially avoid the problem which is to use forward class declarations.
1
2
3
4
5
6
class B;  // Forward declaration

class A
{  B *    p_b;
...
};

This only works for pointers or references. Does not work for direct declaration.


Thank you guys.

- Alex
Topic archived. No new replies allowed.