Object Assignment. McGraw-Hill The Complete Reference Fourth Edition
Reklamë
Reklamë
324
C + + : T h e C o m p l e t e R e f e r e n c e
When an object is returned by a function, a temporary object is automatically created that holds the return value. It is this object that is actually returned by the function. After the value has been returned, this object is destroyed. The destruction of this temporary object may cause unexpected side effects in some situations. For example, if the object returned by the function has a destructor that frees dynamically allocated memory, that memory will be freed even though the object that is receiving the return value is still using it. There are ways to overcome this problem that involve overloading the assignment operator (see Chapter 15) and defining a copy constructor
(see Chapter 14).
Object Assignment
Assuming that both objects are of the same type, you can assign one object to another.
This causes the data of the object on the right side to be copied into the data of the object on the left. For example, this program displays 99:
// Assigning objects.
#include <iostream> using namespace std; class myclass { int i; public: void set_i(int n) { i=n; }
}; int get_i() { return i; } int main()
{ myclass ob1, ob2; ob1.set_i(99); ob2 = ob1; // assign data from ob1 to ob2 cout << "This is ob2's i: " << ob2.get_i();
} return 0;
By default, all data from one object is assigned to the other by use of a bit-by-bit copy. However, it is possible to overload the assignment operator and define some other assignment procedure (see Chapter 15).
Chapter 13
Arrays, Pointers, References, and the Dynamic Allocation
Operators
325
Copyright © 2003 by The McGraw-Hill Companies. Click here for terms of use.
Shkarko
Reklamë