In your copy ctor, an instance of Grade object 'p' is passed in by a const reference. A reference is not a pointer. Const simply enforces that the passed in object will be "read-only".
What you need to do inside the copy constructor (ctor) is perform a member by member copy from object p.
You will need to perform a deep copy of the data pointed to by pointers d and e
For exampl, inside your ctor
1 2 3 4 5 6
|
this->e = 0; // set member pointer e initially to null
if( p.e )
{
this->e = new int;
*(this->e) = *(p.e);
}
|
Note: this->e will have no previous value since you are creating a new object and copying value from a referenced object. You also must dereference a pointer with '*' because you want to change the value the pointer contains, without it you would be changing the pointer itself which is simply a memory address.
this->e could also be a pointer to an integer array, however there is no size member that tells you how big this array could be, so for the example it allocated a int on the help using the new operator.
in your class destructor( dtor ) make sure to free the memory
1 2 3
|
~Grade() {
delete this->e;
}
|
Note: you don't need to check for null before deleting this->e
You should have enough info to code-complete a deep-copy ctor.
Framework example also works, but it only performs a shallow-copy, after the copied object has been created, two objects will point to the same thing for member pointer d and e, this may not be what you want because if one object modifies these value the other object will also be mutated likewise. Thus a deep-copy gives each object it's own copy of all values.
---
Rajinder Yadav <labs@devmentor.org>
DevMentor Labs
http://labs.devmentor.org
Creating Amazing Possibilities