-2

My question is about linking the files in g++ compiler.

I have a .cpp file named A.cpp containing a parent class and its children, each class uses an instance of another class defined in B.cpp, and in the class defined in B.cpp, we use an instance of all the classes defined in A!

How should I link these files? Is this a very poor programming style? I have tried including A.cpp in one B.cpp and B.cpp in A.cpp but it is incorrect.

icedwater
  • 4,701
  • 3
  • 35
  • 50
Elaheh
  • 1
  • 2

2 Answers2

0

You don't have to include A.cpp in B.cpp, you need to use an header file.

https://en.wikipedia.org/wiki/Header_file

Basically, an header file contains the definitions of your classes and methods.

If I've understand your example you need an A.h file that you will include in B.cpp

Marco Martinelli
  • 892
  • 2
  • 14
  • 27
0

You should define a class in a header file. only the function and static data member definitions should be in a .cpp file. You should also use compiler macros (#if defined / #define / #endif) to prevent multiple includes.

About A in B and B in A:

What you have stated would cause infinite recursion: Each A contains a B, each of which contains and A, each of which contains a B, each of which contains an A ... and so on.

You cannot do that obviously. You can nevertheless, have for example an A-pointer int B and an instance of B in A.

I don't know what you want to achieve but you could use a constructor of B to pass in a pointer to the A object it is contained in (if this is always the case for example).

B.h

#if !defined(B_CLASS_H)
#define B_CLASS_H
class A; // forward declare A, no include "A.h" here
class B 
{
  A * a_pointer;
public:
  B (A* another_A);
};
#endif

B.cc

#include "B.h"
B::B (A* another_A) : a_pointer(another_A) { }

A.h

#if !defined(A_CLASS_H)
#define A_CLASS_H
#include "B.h"
class A
{
  B b_instance;
public:
  A (void);
};
#endif

A.cc

#include "A.h"
A::A (void) : b_instance(this) { }
Pixelchemist
  • 24,090
  • 7
  • 47
  • 71