Search code examples
c++scopepass-by-reference

C++ object data being wiped clean after function goes out of scope


CS student here, first post.

I am working with two objects. obj1 is passed to obj2 by reference. obj2 processes data from a file and writes information to a char[] in obj1. obj1 then evaluates the information in the char array.

However, as soon as the function in obj2 that has been writing to the char[] goes out of scope, all the information that has been written is wiped clean. I have stepped through the code and it's clear to me that obj1 is not being passed by reference, but I can't figure out why. Can anyone help me see what I'm missing?

int main(int argc, char* argv[])
{
    //...
    Object1 obj1;   // obj1 created with &1
    Object2 obj2(filename, obj1);
    obj2.func1();   // void function that writes to obj1.arr -> writes fine but to a obj1.arr @ &2
    obj1.func1();   // obj1.arr @ &2 is gone, obj1.arr @ &1 is garbage.
}

// Object1.h
class Object1
{
    Object1() = default;
    char arr[size];
}

// Object2.h
class Object2 
{
    public: 
        Object1 obj1;
        string filename;
}

// Object2.cpp
Object2::Object2(string filename, Object1& obj1)
    : filename(filename), obj1(obj1)
{
}

Solution

  • I think your problem may be here:

    // Object2.h
    class Object2 
    {
        public: 
           Object1 obj1;
    

    Note that Object2 has a member-variable named obj1, and that your Object2 constructor is initializing that member-variable using the reference that was passed in as an argument to the constructor:

     Object2::Object2(string filename, Object1& obj1)
        : filename(filename), obj1(obj1)
     {
    

    Note also that the meaning of obj1(obj1) isn't obvious here -- you've named your second constructor argument obj1, but you also have the local member-variable named obj1. In order to avoid ambiguity for the human reader, you should change either the name of the argument or the name of the member-variable.

    You may also want to change the type of your Object2 class's member-variable from Object1 to Object1 &, if your intent is that the Object2 object should be continue to reference the original obj1 object directly rather than use its own separate Object1 member-object.