C++ Copy ConstructorA Copy constructor is an overloaded constructor used to declare and initialize an object from another object. Copy Constructor is of two types:
Syntax Of User-defined Copy Constructor:Consider the following situation: In the above case, copy constructor can be called in the following ways: Let's see a simple example of the copy constructor. // program of the copy constructor. Output: 20 When Copy Constructor is calledCopy Constructor is called in the following scenarios:
Two types of copies are produced by the constructor:
Shallow Copy
Let's understand this through a simple example: Output: value of a is : 4 value of b is : 5 value of *p is : 7 In the above case, a programmer has not defined any constructor, therefore, the statement Demo d2 = d1; calls the default constructor defined by the compiler. The default constructor creates the exact copy or shallow copy of the existing object. Thus, the pointer p of both the objects point to the same memory location. Therefore, when the memory of a field is freed, the memory of another field is also automatically freed as both the fields point to the same memory location. This problem is solved by the user-defined constructor that creates the Deep copy. Deep copyDeep copy dynamically allocates the memory for the copy and then copies the actual value, both the source and copy have distinct memory locations. In this way, both the source and copy are distinct and will not share the same memory location. Deep copy requires us to write the user-defined constructor. Let's understand this through a simple example. Output: value of a is : 4 value of b is : 5 value of *p is : 7 In the above case, a programmer has defined its own constructor, therefore the statement Demo d2 = d1; calls the copy constructor defined by the user. It creates the exact copy of the value types data and the object pointed by the pointer p. Deep copy does not create the copy of a reference type variable. Differences b/w Copy constructor and Assignment operator(=)
Next Topic# |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India