how do you obtain a member of a class which is also a member of a class of the same type?

Viewed 51

I'm currently writing a program in c++ using recursion and I want to print out a vector of tuples that resides in a class member which has the same type as the class itself. Below, you can see the class "Data" which has a class member called "child" of the same type. It also has a vector of tuples I want to print out using the readTuples function.

class Data {
    public:
        vector<tuple<string, string, string>> myTuple;
        Data *child;

    void readTuples(){
        for (int i = 0; i < myTuple.size(); i++)
        {
            std::cout << "ID: " << get<0>(myTuple[i]) << "\tTYPE: " << get<1>(myTuple[i]) << "\tVALUE: " << get<2>(myTuple[i]) << "\n";
        }
    }
}

In the function below, I receive the Data object as a parameter. I add a child to the Data object using the typecheck function which returns a data object with a filled vector of tuples. I then read the vector using the readTuples function. This works...

 Data typecheck(Data data)
{
    Data* child = new Data();
    Data childData = statementList->typecheck(*child);
    child = &childData;
    data.child = child;
    data.child->readTuples();
    return data;
}

output
ID: a TYPE: integer VALUE: 1
ID: b TYPE: integer VALUE: 2
ID: c TYPE: integer VALUE: 3

The data object is then returned and caught in the object Data (i.e. the typecheck function has just been executed).

Data typecheck(Data data)
{
    data = block->typecheck(data);
    data.child->readTuples();
    
    return data;
}

But when I try to read the vector of tuples again, it crashes. The command line returns weird symbols, so I presume this has something to do with pointers and memory allocation.

Thanks in advance.

1 Answers
Data typecheck(Data data)
{
    Data* child = new Data();
    Data childData = statementList->typecheck(*child);
    child = &childData;
    data.child = child;
    data.child->readTuples();
    return data;
}

childData is a local variable whose reference you take. Once this function terminates, childData is destroyed, and any references to it invalidated. At that point, data.child points to garbage, and dereferencing it is undefined behavior.

If you want the pointer to last longer than the current function, either return it, or allocate it on the heap and store a pointer to that.

Related