Search code examples
c++header-filesforward-declaration

Co-Dependent .h files with forward declaration


I have 3 classes (A, B & C) in different .h files. How can I move the #includes and forward declarations in order for it to compile.

Currently I've used forward declaration in A.h and thought it would work from there. Instead C.h is throwing many compiler errors of 'class A' is inaccessible with in this context.

// A.h
#pragma once

...

class B;

class A {
  private:
    B *parent_;
};
// B.h
#pragma once

...

#include <A.h>

class B : A {
  public:
    virtual void func(A *arg);
};
// C.h
#pragma once

...

#include <A.h>
#include <B.h>

class C : B {
  public:
    virtual void func(A *arg);

  private:
    A *left_child;
    A *right_child;
};

Solution

  • The name A is private via B. You can either change to public or protected inheritance in B, or use (the fully-qualified name) ::A in C