Search code examples
c++forward-declaration

Forward declaration within a class (not a nested class)


I came across this odd forward declaration (or something) where instead of having a normal:

class A;
class B{
    A* var;
}

You can do

class B{
   class A* var;
}

Now this might be an elaborated type specifier, but I'm not sure about that. I've tried it myself and I had no issues, even made my code a lot more cleaner, but I'm afraid it may cause scoping issues that I'm currently unaware of.

Does anyone have an insight on this? is this a valid forward deceleration?

example: https://youtu.be/EIptJ0YrYg0?t=412


Solution

  • Now this might be an elaborated type specifier, but I'm not sure about that.

    It is. In fact, class A; is a declaration to uses an elaborate class specifier.

    but I'm afraid it may cause scoping issues that I'm currently unaware of

    The only scoping related point you should be aware of is that if the elaborate type specifier (that is not a declaration by itself) is the first time class is referenced, the behavior is the same as if you introduced a forward declaration to the nearest namespace or block scope. So for instance

    namespace N {
      class foo {
         class bar {
           void func(class baz*);
         };
      };
    };
    

    ... is the same as

    namespace N {
      class baz;
      class foo {
         class bar {
           void func(baz*);
         };
      };
    };