Cross references in C++ classes

What are cross references?

It’s named cross references the situation in which a class A needs to reference to class B, and class B also needs to make reference to class A.

For instance, suppose we have an application responsible of the management of a car workshop, where each mechanic is repairing an only car at every moment. We need references from the mechanic to the car, and from the car to the mechanic. We can have something like this:

Mechanic.h

1
2
3
4
5
6
7
8
9
10
11
12
13
#ifndef _MECHANIC_H_
#define _MECHANIC_H_
 
#include "Car.h"
 
class Mechanic {
public:
    void repairCar(Car* car);
private:
    Car* _car;
}
 
#endif // _MECHANIC_H_

Car.h

1
2
3
4
5
6
7
8
9
10
11
12
13
#ifndef _CAR_H_
#define _CAR_H_
 
#include "Mechanic.h"
 
class Car {
public:
    void assignMechanic(Mechanic* mechanic);
private:
    Mechanic* _mechanic;
}
 
#endif // _CAR_H_

If we try to compile the previous code we will get an error, because the compiler tries to compile one of the classes, for example Mechanic. Then it sees that for compile the class Mechanic, it needs the class Car. So then it tries to compile the class Car but now it finds that is needed the class Mechanic, which is not compiled yet. As two classes are needed mutually, it’s not possible to continue for the compiler.

Solution

The way we can fix this issue in C++ is very simple. We will have one of these classes exactly as shown before. For example, we leave as earlier the class Mechanic:

Mechanic.h

1
2
3
4
5
6
7
8
9
10
11
12
13
#ifndef _MECHANIC_H_
#define _MECHANIC_H_
 
#include "Car.h"
 
class Mechanic {
public:
    void repairCar(Car* car);
private:
    Car* _car;
}
 
#endif // _MECHANIC_H_

However, in the class Coche we will make two changes. On the one hand, we need to delete the #include of Mechanic.h. And on the other hand, we need to declare that exists a class named Mechanic, but we don’t define it.

Car.h

1
2
3
4
5
6
7
8
9
10
11
12
13
#ifndef _CAR_H_
#define _CAR_H_
 
class Mechanic;
 
class Car {
public:
    void assignMechanic(Mechanic* mechanic);
private:
    Mechanic* _mechanic;
}
 
#endif // _CAR_H_

Now we can compile our program saving the problem with cross references.

Regards!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*