0

I've read several questions here about circular dependencies when using #include in the header files of classes , so for example: // sorry edited the example to be clear

File Car.h

#include "Wheel.h"
#include <vector>

class Car
{
    std::vector<Wheel> wheels;
};

File Wheel.h

#include "Car.h"
class Wheel
{
    Car* car;
};

A compile error happens due to the circular dependency occurring between the 2 classes. My question is why if I just used #include "Wheel.h" in the .cpp of class Car or #include "Car.h" in the .cpp of class Wheel, the problem is solved. Isn't it still a circular dependency?

1 Answers1

0
//A.h
#include "B.h"
class A
{}

//////////////

//B.h
#include "A.h"
class B
{}

There is no circular dependency in the shown code. Neither class depends on the other. (The code won't compile however, due to syntax errors).

Circular include simply means that one header is not before the other despite having been included at the top. This is simply because both cannot be before the other at the same time. If the class defined in the header that was included first depends on the one that was included second, then there would be an error.


Update for the new example:

In this case, Car depends on the definition of Wheel and Wheel depends on the declaration of Car. Note that Wheel does not depend on the definition of Car. It does not need to know what kind of class Car is, only that it is a class.

My question is why if I just used #include "Wheel.h" in the .cpp of class Car or #include "Car.h" in the .cpp of class Wheel, the problem is solved.

This is not correct, this does not solve the problem. It might make the problem disappear, but the program will remain buggy.

The correct solution is to include the definition of Wheel before Car is defined, and declare Car before Wheel is defined. Like this:

class Car;

class Wheel
{
    Car* car;
};

class Car
{
    std::vector<Wheel> wheels;
};
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
eerorika
  • 232,697
  • 12
  • 197
  • 326