How can I put a variable of the same class as the class I am defining?

3

I'm doing a problem of A * and I need to save the father and then print the route. Everything works correctly until I ask the parent node in the printing method and it gives me this error:

  

"error.EXC_BAD_INSTRUCTION (code = EXC_I386_INVOP, subcode = 0x0)"

I leave you all the pieces where this variable appears.

class node{

private:

    node *padre;
    vector<vector <string>>situacion;
    int profundidad;
    int g = 0;
    int h = 0;
    int f = 0;
    string paso;

public:

    node getPadre(){

     return *padre;
   }

   void setPadre(node newPadre){

    padre = &newPadre;
   }
};

// ...

newNode.setPadre(nodo); //Donde "nodo es una variable de la clase node"

// ...

node itNode = itNode.getPadre(); // donde it node

The problem is that I save the nodes in a vector<nodes> and reorganize it with sort in each iteration, with which the memories change, and therefore when trying to access the parent node, it is not there.

Do you know if there is any way to do a sort with a vector<*node> ?

Many thanks in advance to all who answer or try.

    
asked by Alfonso Rodríguez 15.12.2017 в 12:00
source

1 answer

3
void setPadre(node newPadre){
  padre = &newPadre;
}

Notice that you are passing a copy , not the original object. Therefore, what you are storing is a memory position that stops being correct as soon as you leave your function .

The solution is simple:

void setPadre( node &newPadre){
  padre = &newPadre;
}

That is: pass it by reference , not by value.

    
answered by 15.12.2017 / 12:18
source