explain the relationship between a deep copy and its pointer.
explain the relationship between a shallow copy and its pointer.
how many bytes are incremented if a pointer such as *p is incremented using pointer arithmetic such as (depending upon which primitive type it point to; int, double, char etc).
write a copy constructor to copy a class object containing a dynamic array. use a member by member copy techniques shown in the textbook.
using correct c++ syntax, write the function defination to overload the operator test for equality: == operator to determine if two objects that have identical components of their dynamic arrays used in above question .
Deep copy and its pointer :
Shallow copy and its pointer :
When we increment pointer by using pointer Arithmetic it uses formula internally how many bytes to increment.
int x=10;
int *p=&x;
p++; // p=p+1*(sizeof(premitive_datatype)); --> suppose x address is 100 so p contains 100. 100+1*sizeof(int) i.e 4 so p=104 ( 4 bytes are incremented).
Copy Constructur to check identical items in object using overloading of == :
#include<iostream>
using namespace std;
class Demo
{
private:
int * arr;
int size;
public:
Demo(int size) // Parameterized
Constructor
{
this->size = size;
arr = new int[size];
}
Demo(const Demo& obj) // User defined Copy
constructor
{
size = obj.size;
arr = new int[obj.size];
for (int i = 0; i<obj.size;
i++)
arr[i] =
obj.arr[i];
}
void InsertValues() { // Insert elements
into dynamic arrays
for (int i = 0; i <
this->size; i++)
{
cin >>
arr[i];
}
cout << "\n";
}
void PrintValues() // Display dynamic
array elements.
{
for (int i = 0; i <
this->size; i++)
{
cout
<<"\t"<<arr[i];
}
cout << "\n";
}
bool operator ==(Demo obj) // == Operator
overloading to check objects elements.
{
for (int i = 0; i < size;
i++)
{
if
(this->arr[i] != obj.arr[i])
return false;
}
return true;
}
};
int main()
{
Demo
obj1(3);
// Object 1
obj1.InsertValues();
obj1.PrintValues();
Demo obj2 =
obj; // Object
2 --> Here call goes to Copy Constructor
obj2.PrintValues();
obj1.InsertValues(); // Insert new
elements in Obj1
if (obj1 == obj2) //
Compare Objects
cout << "\nBoth are
same";
else
cout << "\nBoth are
different";
return 0;
}
Get Answers For Free
Most questions answered within 1 hours.