Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I forward declare an inner class? [duplicate]

People also ask

Can you forward declare a nested class?

You cannot forward declare a nested structure outside the container. You can only forward declare it within the container.

What is the forward declaration of classes?

Forward Declaration refers to the beforehand declaration of the syntax or signature of an identifier, variable, function, class, etc. prior to its usage (done later in the program). In C++, Forward declarations are usually used for Classes.

How do you forward a function declaration?

To write a forward declaration for a function, we use a declaration statement called a function prototype. The function prototype consists of the function header (the function's return type, name, and parameter types), terminated with a semicolon. The function body is not included in the prototype.

Why do we need forward declaration in C++?

The compiler wants to ensure you haven't made spelling mistakes or passed the wrong number of arguments to the function. So, it insists that it first sees a declaration of 'add' (or any other types, classes, or functions) before it is used.


This is simply not possible. You cannot forward declare a nested structure outside the container. You can only forward declare it within the container.

You'll need to do one of the following

  • Make the class non-nested
  • Change your declaration order so that the nested class is fully defined first
  • Create a common base class that can be both used in the function and implemented by the nested class.

I don't believe forward declaring inner class of on an incomplete class works (because without the class definition, there is no way of knowing if there actually is an inner class). So you'll have to include the definition of Container, with a forward declared inner class:

class Container {
public:
    class Iterator;
};

Then in a separate header, implement Container::Iterator:

class Container::Iterator {
};

Then #include only the container header (or not worry about forward declaring and just include both)


I know of no way to do exactly what you want, but here is a workaround, if you are willing to use templates:

// Foo.h  
struct Foo
{
   export template<class T> void Read(T it);
};

// Foo.cpp
#include "Foo.h"
#include "Container.h"
/*
struct Container
{
    struct Inner { };
};
*/
export template<> 
  void Foo::Read<Container::Inner>(Container::Inner& it)
{

}

#include "Foo.h"
int main()
{
  Foo f;
  Container::Inner i;
  f.Read(i);  // ok
  f.Read(3);  // error
}

Hopefully, this idiom might be of some use to you (and hopefully your compiler is EDG-based and implements export ;) ).