I am trying to create a constructor in the context of an object. After creating the object using the reference, I need to print the field value of both the objects. Then I have to delete the first object, and once again the values of the fields of both objects will be displayed. My class person looks like this:
class person {name four; name; Old age; Public: Individual () {int size = 0; Cout & lt; & Lt; "Give length of time" & lt; & Lt; Endl; Cin & gt; & Gt; Shape; Name = new four [size]; Age = 0; } ~ Person () {cout & lt; & Lt; "Destroying resources" & lt; & Lt; Endl; Delete [] Name; Lifting; } Zero init (char * n, int a) {name = n; Age = a; }};
Here's my implementation (with the use of the function show ()). My professor said that if this work is written properly then it will return an error.
#include & lt; Iostream & gt; using namespace std; Class person {four * names; Old age; Public: Individual () {int size = 0; Cout & lt; & Lt; "Give length of time" & lt; & Lt; Endl; Cin & gt; & Gt; Shape; Name = new four [size]; Age = 0; } Person (Constant and P) {name = p.name; Age = pg; } ~ Person () {cout & lt; & Lt; "Destroying resources" & lt; & Lt; Endl; Delete [] Name; Lifting; } Zero init (char * n, int a) {name = n; Age = a; } Zero shows (four * n, int a) {cout & lt; & Lt; "Name:" & lt; & Lt; Name & lt; & Lt; "," & Lt; & Lt; "Age:" & lt; & Lt; Age & lt; & Lt; "," & Lt; & Lt; Endl; }}; Int main (zero) {person * p = new person; P-> Init ("mary", 25); P-> Show (); Person & amp; P = PRF; PRF-> Name = "tom"; Prf- & gt; Age = 18; Person * p2 = new person (prf); P-> Show (); P2-> Show (); System ("pause"); Return 0; }
The problem with your copy maker is that it only provides p.name Is:
name = p.name // Now hold this p and a pointer in the same memory
both this
And P
now hold a pointer at the same memory location, whichever is deleted will free the memory, while the second one will place a pointer for a non-existent object. After that using or removing that pointer will be undefined behavior. Its solution is to allocate a new array for the name and PNN It is to copy the contents of that array so that memory is not shared.
Similarly, your init functions overwrite the name, ignoring the fact that memory is allocated (this is a memory leak) and it is also ignoring the fact that the string Will be destroyed later (even if the caller probably expects himself and himself to wade). Also, I should tell you that your show takes the function parameter "n", but instead uses "name". Your show ceremony probably should not take any parameters (in fact, the way you say it does not mean it), given that all the required fields are already present in your class (or maybe Is that a freestanding function that takes the area of the square?). For additional errors, you should take a closer look at your code.
Comments
Post a Comment