mr5
mr5

Reputation: 588

function with pointer parameters

I cannot clearly state my problem in the title but this is really it.

void DChatbox::ClampObject(DTextbox _txtbox) {

    this->_txtbox = &_txtbox;

}

this one just create a copy of _txtbox not referencing it.

but this one works.

void DChatbox::ClampObject(DTextbox* _txtbox) {

    this->_txtbox = _txtbox

}

as I examined the first one, it just makes a copy of it, not referencing it. Why is it like that?

note: _txtbox on DChatbox is declared as this DTextbox* _txtbox

Upvotes: 0

Views: 96

Answers (2)

Oguz Meteer
Oguz Meteer

Reputation: 79

That is because the first version passes the argument by value, i.e. it makes a copy of the whole object. When the method is done it simply deletes the copy. Therefore the address of that local object is invalid when the method is done, since it points to a deleted object.

The second version passes the argument using a pointer, so the pointer references the real object and not a copy of the object. Therefore, when the method is done, the value of the pointer is still the same as it points to an object that still exists.

Upvotes: 1

Alok Save
Alok Save

Reputation: 206566

In your first case, the pointer member gets assigned the address of an DTextbox object which is local to the function and is guaranteed to live only till the function scope{ } ends.
When you refer this->_txtbox outside the function DChatbox::ClampObject what you get is Undefined Behavior.

In second case the pointer member gets assigned to the address of object which is passed to the function and probably(difficult to say unless you show the code which calls it) the lifetime of that object being passed to the function is long enough for your program to work correctly and hence it works correctly.

Upvotes: 2

Related Questions