How to create a class copy

How to create a class copy

The object-oriented programming paradigm is prevailing in all modern means and languages intended for creation of the software. The industrial standard is the object-oriented programming language of C ++ today. It is possible to create a class copy in C ++ several different ways.

It is required to you

  • - compiler C ++.

Instruction

1. Create a class copy as the auto-variable in local area of the visibility determined by function, method of a class or the operator block. Use declarative or imperative object definition of a class in the selected place of the program. If necessary carry out an explicit call of any designer with parameters. Create an object by means of the code similar to the following: void CMyClass:: SomeMethod () {    COtherClass oSomeObject1; //creation of an object by means of the designer by default    COtherClass oSomeObject2 (1980, ""Victor V. Vakchturov""); //creation of an object by means of the designer with parameters } Memory under objects of the classes created in the similar way as well as under any other auto-variables, is selected on a stack. Therefore at an output from area of visibility and removal of a frem of a stack, the object will be destroyed (with a destructor call).

2. Create a class copy in the field of dynamically distributed memory through new operator. Define the variable of a pointer type on objects of a class which copy should be created. Assign it the value which is result of calculation of new operator. Cause the suitable designer. Use the code fragment similar to the following: CSomeClass * poSomeObject; //definition of the pointer on class CSomeClasspoSomeObject objects = new CSomeClass; //Creation of an object klassaCSomeClass * poSomeObject_2 = new CSomeClass (111, ""3V""); //creation with the designer's call with parameters During creation of objects by this method is used the memory allocation mechanism determined by new operator (if it is not redefined and own distribution function is not installed) therefore the address of a new object is not known in advance. All objects created in this way should be obviously deleted by delete operator.

3. Create a class copy through new operator on independently selected memory fragment. Use the code similar to the following: void * p0 = malloc(sizeof(CSomeClass));//selection pamyativoid * p1 = malloc(sizeof(CSomeClass));//selection pamyatinew (p0) of CSomeClass;//initialization of an object on the allocated memory (default constructor) of new (p1) of CSomeClass (111, ABC);//initialization of an object (the designer with parameters) Before destruction of the objects created by this method it is worth causing their destructor obviously: ((CSomeClass *) p0)-> ~ (); Creation of objects in this way is generally used in sample classes containers of different libraries (such as STL).

Author: «MirrorInfo» Dream Team


Print