Neophyte
Neophyte

Reputation: 125

Maintaining scope with class pointers in c++

I have a class that is responsible for creating and initializing a number of large objects, as the objects are all of the same Type and I don't want to repeat the same initializing code for all the objects, I call an Init method for each object, for example:

InitObject(objMember);

void Test::InitObject(LargeObject * obj)
{
    obj = new LargeObject;
    obj->Load();
    obj->SetSomeProperty(false);
}

Once this has been done, from a public method I call a set of methods to get a pointer to each of the objects:

//public
LargeObject * Test::GetObject()
{
    return objMember;
}

The issue is that the objects are losing scope, when InitObject is called, the objects are correctly constructed and populated, but when I call GetObject, it has lost everything.

I'm probably missing something trivial, but I can't see why it's going out of scope.

Upvotes: 0

Views: 101

Answers (1)

Luchian Grigore
Luchian Grigore

Reputation: 258608

It is trivial, yes. You're initializing a copy of the original pointer. You probably want to pass it by reference:

void Test::InitObject(LargeObject*& obj)

Passing by value means that you're assigning the return of new to a copy of the pointer. The one outside the function InitObject remains unchanged.

A few more things - initializing objects after construction should be done with care. If the object isn't valid after construction, it's a bad design (excluding some rare cases). You can signal invalid initialization by throwing an exception from the constructor.

Also, consider using smart pointers instead of raw pointers.

Upvotes: 2

Related Questions