vendredi 19 mars 2021

Why does this work without a class definition, but fails when including the class header?

I was making a little game with the following code:

A.hpp:

#pragma once

#include <vector>
#include <array>
#include <memory>
#include "B.hpp"

class A
{
public:
    A();
    ~A() = default; // Irrelevant

public:
    std::array<std::array<std::unique_ptr<B>, 3>, 3> matrix {}; // Matrix of std arrays of B type unique pointers
};

A::A()
{
    // Fill the matrix with B type unique_ptrs
    for (auto &&aColumn : this->matrix)
    {
        for (auto &&ptrB : aColumn)
        {
            ptrB = std::make_unique<B>();
            ptrB->ptrGame = this; // I need every B class access to the matrix
        }       
    }   
}

B.hpp:

#pragma once

class A;

// #include "A.hpp" --> If I include this the compiler says that B is undefined

class B
{
public:
    A* ptrGame = nullptr;
};

And lastly: main.cpp

#include "A.hpp"

int main(int argc, char const *argv[])
{
    A a;
    return 0;
}

This code compiles without any warning. My big two questions are (apart from why this works) the following:

  1. How does the compiler know how is class A, if the only definition in the B.hpp header was a forward declaration, without defining anything?
  2. Why is B undefined when I include A.hpp header?

Thank you for reading this! Any help is vastly appreciated!!

Edit: I also tested with valgrind to see any memory errors, but none were prompted.

Aucun commentaire:

Enregistrer un commentaire