Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

recursive definition in CPP [duplicate]

Tags:

c++

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?

  1. error C2146: syntax error : missing ';' before identifier 'b' c:\users\xingyo\documents\visual studio 2010\projects\cppalgo\recudef\test1.h 9 1 RecuDef

  2. 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

  3. 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

like image 499
Yongwei Xing Avatar asked Nov 29 '10 02:11

Yongwei Xing


People also ask

What is recursive in CPP?

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.

What is recursive function in C++ with example?

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.


1 Answers

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.

like image 98
Nikolai Fetissov Avatar answered Oct 25 '22 19:10

Nikolai Fetissov