0

I have the following code:

class Cohomology;

struct EMField
{
     std::unique_ptr<Cohomology> coh;
     std::array<DIM> data;

     EMField() {coh -> initializeField(*this);};
}

class Cohomology
{
     private:
        // private members
     public:
        Cohomology(PList params)
        {
             // Constructor of the class
        }

        void initializeField(EMField& field)
        {
             field.coh.reset(this);
             // other methods to initialize field.data using the private members
        }
}

In this answer it is explained that calling a method of an incomplete type is not possible, nor dereferencing the pointer.

In fact, when I try to compile it I get:

warning: invalid use of incomplete type ‘class Cohomology‘

note: forward declaration of ‘class Cohomology‘

My question is: How can I delegate the construction of EMField to the Cohomology class if I cannot use a member of std::unique_ptr<Cohomology> coh ?

rungekutta
  • 39
  • 5
  • You can separate `EMField` to header and implementation. In the header you can use a forward declaration (and avoid #including the header for `Cohomology`) but in the cpp you should #include it and then be able to call `Cohomology`'s methods. – wohlstad Aug 09 '22 at 14:15
  • 2
    See method 2 in dupe: [C++ class declaration after using it](https://stackoverflow.com/a/72474240/12002570). In particular, just move implementation of `EMField::EMField()` after the classes have been defined. – Jason Aug 09 '22 at 14:16

1 Answers1

2

Just move the definition of EMField::EMField() until after both classes have been defined.

class Cohomology;

struct EMField
{
     std::unique_ptr<Cohomology> coh;
     std::array<DIM> data;

     EMField();
};

class Cohomology
{
     private:
        // private members
     public:
        Cohomology(PList params)
        {
             // Constructor of the class
        }

        void initializeField(EMField& field)
        {
             field.coh.reset(this);
             // other methods to initialize field.data using the private members
        }
};

inline EMField::EMField()
{
    coh -> initializeField(*this);
}
john
  • 85,011
  • 4
  • 57
  • 81