Reputation: 86
I'm trying to understand friendly classes in C++. I made two classes: Lada ( Car ), and Mechanic. Lada is friendly class to Mechanic, so Mechanic can view and change Lada's private variables. Where you're itializing Lada, it takes one argument, bool isBroken ( no need to explain ). And Mechanic class has method, that repairs Lada ( changes isBroken to false ). I don't know why, but it shows an error: >
C:\C++\FriendlyClassesTests>c++ Lada.cpp Lada.h Mechanic.cpp Mechanic.h main.cpp -std=c++20
In file included from Lada.h:3:
Mechanic.h:11:25: error: 'Lada' has not been declared
11 | void RepairLada(Lada& lada);
| ^~~~
Mechanic.cpp:9:1: error: no declaration matches 'int Mechanic::RepairLada(Lada&)'
9 | Mechanic::RepairLada(Lada& lada) {
| ^~~~~~~~
Mechanic.h:11:14: note: candidate is: 'void Mechanic::RepairLada(Lada*)'
11 | void RepairLada(Lada& lada);
| ^~~~~~~~~~
Mechanic.h:6:7: note: 'class Mechanic' defined here
6 | class Mechanic
| ^~~~~~~~
In file included from Lada.h:3,
from main.cpp:2:
Mechanic.h:11:25: error: 'Lada' has not been declared
11 | void RepairLada(Lada& lada);
| ^~~~
I included "Lada.h" file in both Mechanic.cpp and Mechanic.h files.
Mechanic.h file:
#ifndef MECHANIC_H
#define MECHANIC_H
#include "Lada.h"
class Mechanic
{
public:
Mechanic();
void RepairLada(Lada& lada);
protected:
private:
};
#endif // MECHANIC_H
Mechanic.cpp file:
#include "Mechanic.h"
#include "Lada.h"
Mechanic::Mechanic()
{
// Constructor!
}
Mechanic::RepairLada(Lada& lada) {
lada.isBroken = false;
}
Lada.h file: https://pastebin.com/7mBd5H0A
Lada.cpp file: https://pastebin.com/fj4PqazW
Sorry, for any mistakes in my english, i'm Ukrainian. Hope for your help.
Upvotes: 0
Views: 67
Reputation: 184
The error here is that you are including Mechanic
in Lada
and Lada
in Mechanic
, this leads to an infinite loop as the compiler does not know which one should be included first.
You can use forward declarations
to declare Mechanic
in Lada
without having to include it:
#ifndef SOMECLASS_H
#define SOMECLASS_H
class Mechanic; // Use this instead of #include
class Lada {
public:
// ...
};
#endif
Upvotes: 1