I made a simple program to test an error I'm getting. Don't know why it doesn't compile even if the code shows no problems. It seems to be something with the included libraries cos if I delete the "include B.h" line from A.h file it solves the problem.
main.cpp:
#include "A.h"
#include "B.h"
int main()
{
A a;
B b;
b.funcion(a);
return 0;
}
A.h:
#pragma once
#include "B.h"
class A{};
B.h:
#pragma once
#include "A.h"
class B
{
public:
void funcion(A a);
};
B.cpp:
#include "B.h"
void B::funcion(A a){}
Terminal out:
> Executing task: bash -c make <
g++ -c -o src/main.o src/main.cpp
In file included from src/A.h:2,
from src/main.cpp:1:
src/B.h:7:18: error: ‘A’ has not been declared
7 | void funcion(A a);
| ^
src/main.cpp: In function ‘int main()’:
src/main.cpp:9:12: error: cannot convert ‘A’ to ‘int’
9 | b.funcion(a);
| ^
| |
| A
In file included from src/A.h:2,
from src/main.cpp:1:
src/B.h:7:20: note: initializing argument 1 of ‘void B::funcion(int)’
7 | void funcion(A a);
| ~~^
make: *** [<integrado>: src/main.o] Error 1
The terminal process "/bin/bash '-c', 'bash -c make'" failed to launch (exit code: 2).
Terminal will be reused by tasks, press any key to close it.
And that message has no sense to me, there is no 'int' variable anywhere. Using Ubuntu 20.04 and Visual studio Code. Please help.
The
int
is named because the C++ compiler assumes a type it does not know to be anint
.In the header files you have to work with forward declaration of the class.
C++ does not handle cyclic includes.
B.h
B.cpp
It is bad practice to pass a class variable by value, pass it by (const) reference.
B.h
B.cpp