I meet a problem like this: UPDATE
class A
{
public:
A(){}
int i;
B b;
};
class B
{
public:
B(){}
int j;
A a;
};
When I define it in one .h file, it would give an error. I think the problem is the recursive definition. But could someone help me how to solve such issue?
error C2146: syntax error : missing ';' before identifier 'b' c:\users\xingyo\documents\visual studio 2010\projects\cppalgo\recudef\test1.h 9 1 RecuDef
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\users\xingyo\documents\visual studio 2010\projects\cppalgo\recudef\test1.h 9 1 RecuDef
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\users\xingyo\documents\visual studio 2010\projects\cppalgo\recudef\test1.h 9 1 RecuDef
Recursion is a method in C++ which calls itself directly or indirectly until a suitable condition is met. In this method, we repeatedly call the function within the same function, and it has a base case and a recursive condition.
The process in which a function calls itself is known as recursion and the corresponding function is called the recursive function. The popular example to understand the recursion is factorial function. Factorial function: f(n) = n*f(n-1), base condition: if n<=1 then f(n) = 1.
This is not possible verbatim in C++. The explanation is that the compiler needs full, not just forward, declaration of a class to be able to use it as a member of another class. It simply needs the size of a class object.
The workaround in C++ (and in C) is to use a pointer or a reference as a member of one of the classes. That way you can use forward declaration as follows:
class A; // forward declaration
class B {
// ...
A* pa;
};
class A { // full declaration
// ...
B b;
};
It's your (not the compiler or runtime) responsibility to keep the instance of A
that instance of B
points to (or references) valid.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With