Mandar Sadye Mandar Sadye - 3 months ago 13
C++ Question

how to make instance of same class within class in c++ program

I am trying to make program to find shortest path between two points in grid; so I created a class called

FinalPath
and I am trying to keep track of position of surrounding region that is one step in north, south, east and west.

To keep track of this i created instance of array of type
Final
class but when I try to run program it shows
error-"error:field 'Find' has incomplete type of "FindPath[4]" "
.

Code that i entered in the class is as follow

#include <iostream>
#include<vector>
using namespace std;
int a=0,b=0,g=0;
class FinalPath
{
public:
vector<vector<int> >inputMat;
vector<vector<int> >saveMat[4];
int dist;
int goal[2];
int next[4][2];
FinalPath Find[4];
};


I wonder why the compiler is showing me error for creating instance of the class?
What is the correct approach for creatinginstance of same class?
image of code and error console

Answer

You cannot put an instance of a class into itself - that would result in infinite recursion, as each of those instances would have another instance in it, and so on.

Use a pointer to a class instead, like FinalPath * Find;