The Copy Constructor |
|
After creating an object and assigning appropriate values to its member variables, you can perform any regular operation on it. We have already learned:
Assigning a variable to another is equivalent to making a copy of that variable. As you assign a variable to another, you can assign one object to another. Both objects must be recognizably equivalent types to the compiler. Here is an example: int main() { CFlower ^ flower = gcnew CFlower(L"Lilies", L"Pink", L"Bouquet", 45.65); Show(flower); Console::WriteLine(L""); CFlower ^ inspiration; inspiration = flower; Show(inspiration); Console::WriteLine(L""); return 0; } This would produce: Flower Type: Lilies Flower Color: Pink Arrangement: Bouquet Price: $45.65 Flower Type: Lilies Flower Color: Pink Arrangement: Bouquet Price: $45.65 Press any key to continue . . . Notice that both orders display the same thing.
The copy constructor takes one argument, which is the same as the class itself. When a copy is made, it holds and carries the building construction of the object. This object is specified as the argument. As a copy whose value still resides with the object, this argument should be passed as a reference and it should not be modified. It is only used to pass a copy of the object to the other objects that need it. Therefore, the argument should not be modified. As a result, it should be declared as a constant. The syntax of the copy constructor becomes: ClassName(const ClassName^ & Name); To copy one object to another, first create a copy constructor: public ref class CFlower { public: String ^ Type; String ^ Color; String ^ Arrangement; double UnitPrice; CFlower() : Type(L"Roses"), Color(L"Red"), Arrangement(L"Basket"), UnitPrice(35.95) { } CFlower(String ^ type); CFlower(String ^ type, String ^ color, String ^ argn, double price); CFlower(const CFlower ^ &copier); }; To implement the copy constructor, at a minimum, assign a member variable of the copy constructor to the equivalent member of the object: CFlower::CFlower(const CFlower ^ &copier) { Type = copier->Type; Color = copier->Color; Arrangement = copier->Arrangement; UnitPrice = copier->UnitPrice; } In some cases, instead of a one-to-one assignment of member variables from one object to another, you can change how the target object would receive the values. |
|
||
Previous | Copyright © 2006-2016, FunctionX, Inc. | Next |
|