Search code examples
c++pointersinheritanceheader-filesvirtual-functions

How do I access the friend function objects with my derived classes in seperate files?


I have 3 separate header files. Class A, Class B is derived A and Class.

class A {
public:
    virtual void foo(C ...object...);
};

class B : public A {
public:
    void foo(C ...object...);
};

class C {
public:
    friend class A;
    friend class B;
private:
    A *arr[num][num];
};

Arr is pointer of 2D array.The inside of the 2D array is filled with B objects.How can I access the C class object from the header file of class B? Is it possible?If possible, how should the "include .h" seperates header files and foo function prototype be?


Solution

  • A common way to split your code into separate files is following:

    • A.h

      #pragma once
      class C;
      
      class A {
      public:
          virtual void foo(C c);
      };
      

      Class A doesn't need any type information of C. The declaration of member function foo doesn't need complete type information but a declaration because the function expects a parameter of type C.

    • A.cpp

      #include "A.h"
      #include "C.h"
      
      void A::foo(C c) {}
      

      The definition of function A::foo(C c) needs complete type information of C. Therefore the class definition of C is included.

    • B.h

      #pragma once
      #include "A.h"
      
      class C;
      
      class B : public A {
      public:
           void foo(C c) override;
      };
      

      Class B needs complete type information of A for inheritance. Therefore the class definition of A is included. Complete type information of class C is not necessary (see A.h).

    • B.cpp

      #include "B.h"
      #include "C.h"
      
      void B::foo(C c) {}
      

      Same as in A.cpp

    • C.h

      #pragma once
      class A;
      
      class C {
      public:
           friend class A;
           friend class B;
      private:
           A *arr[5][5];
      };
      

      Class C just contains friend declarations of A and B and a pointer to type A. A friend declaration don't need a declaration or full type information. Since all pointers to objects have same size complete type information for class A is not necessary. It will become necessary when the pointer is dereferenced.

    All source files also contain an include of the corresponding header file.