Home > Net >  Forward declaration of structure pattern
Forward declaration of structure pattern

Time:11-23

I am forced to use the architecture which will be presented below. Forward declaration is the pattern I'm trying to implement to counter the issue.

Here is what I have so far :

class_with_config.h :

#include "config_file.h"
#include "i_class_with_config.h"

class ClassWithConfig : public I_ClassWithConfig
{
    // specific implem
};

config_file.h :

struct A {
   bool A1;
   bool A2;
}

struct B {
   bool B1;
   bool B2;
}

struct C {
   A a;
   B b;
}

i_class_with_config.h :

struct B; // forward declaration of struct B

class I_ClassWithConfig
{
  // definition of interface
};

side_class.h :

#include "i_class_with_config.h"

class SideClass
{
public :
   SideClass(B* config);

private :
   void Foo(void);
   B* my_config;
};

side_class.cpp :

SideClass::SideClass(B* argConfig) : my_config(argConfig) 
{
}

void SideClass::Foo(void)
{
   if (my_config->B1 == true)
   {
      // do something
   }
}

I need to use my_config in my SideClass implementation, but I get

pointer to incomplete class type "B" is not allowed

This looks like a forward declaration of structure issue but the pattern is unlike anything I've ever come across.

Main constraint is that I do not have the right to include config_file.h into side_class.h

EDIT 1: corrected typo based on @Stack Danny and @Vlad from Moscow anwsers.

CodePudding user response:

Main constraint is that I do not have the right to include config_file.h into side_class.h

You can solve the issue by including side_class.h and config_file.h into side_class.cpp as shown below.

side_class.cpp

#include "side_class.h"       //added this 
#include "config_file.h"      //added this 

SideClass::SideClass(B* argConfig) : my_config(argConfig) 
{
}

void SideClass::Foo(void)
{
   if (my_config->B1 == true)
   {
      // do something
   }
}

Working demo


Note also that you should use include guards in the headers as done in the above linked working demo.

  • Related