R
rKrishna
I was trying to understand the real need for copy constructors. From
literature, the main reason for redfinition of copy constructor in a
program is to allow deep copying; meaning ability to make copies of
classes with members with static or dynamic memory allocation. However
to do this it requires the programmer to override the default copy
constructor, the destructor & operator=.
I wrote a small program to test if i can doa deep copy with the default
copy constructor. I was expecting the code to crash but it worked. any
thoughts?
src code:
-----------------------------------------------
#include <iostream>
using namespace std;
#include <math.h>
#include <stdio.h>
class Point{
private :
int x;
int y;
int* pZ; //class with a pointer to int
public :
Point();
Point(int a,int b,int c);
friend float Get2Norm(Point p1, Point p2);
};
Point:oint(){
}
Point:oint(int a,int b, int c){
x = a;
y = b;
pZ = new int; //dynamic memory allocated
*pZ = c;
}
float Get2Norm(Point p1,Point p2){
return sqrt(pow((p1.x -p2.x),2)+pow((p1.y -
p2.y),2)+pow((*(p1.pZ) - *(p2.pZ)),2));
}
int main(){
Point p1(1,2,3);
Point p2(4,5,6);
Point p4;
p4 = p1; //using the default copy constructor
cout <<"2nd norm p1,p2 "<<Get2Norm(p1,p2)<<endl;
cout <<"2nd norm p4,p2 "<<Get2Norm(p4,p2)<<endl;
}
output:
-------------------
2nd norm p4,p2 5.19615
literature, the main reason for redfinition of copy constructor in a
program is to allow deep copying; meaning ability to make copies of
classes with members with static or dynamic memory allocation. However
to do this it requires the programmer to override the default copy
constructor, the destructor & operator=.
I wrote a small program to test if i can doa deep copy with the default
copy constructor. I was expecting the code to crash but it worked. any
thoughts?
src code:
-----------------------------------------------
#include <iostream>
using namespace std;
#include <math.h>
#include <stdio.h>
class Point{
private :
int x;
int y;
int* pZ; //class with a pointer to int
public :
Point();
Point(int a,int b,int c);
friend float Get2Norm(Point p1, Point p2);
};
Point:oint(){
}
Point:oint(int a,int b, int c){
x = a;
y = b;
pZ = new int; //dynamic memory allocated
*pZ = c;
}
float Get2Norm(Point p1,Point p2){
return sqrt(pow((p1.x -p2.x),2)+pow((p1.y -
p2.y),2)+pow((*(p1.pZ) - *(p2.pZ)),2));
}
int main(){
Point p1(1,2,3);
Point p2(4,5,6);
Point p4;
p4 = p1; //using the default copy constructor
cout <<"2nd norm p1,p2 "<<Get2Norm(p1,p2)<<endl;
cout <<"2nd norm p4,p2 "<<Get2Norm(p4,p2)<<endl;
}
output:
-------------------
2nd norm p1,p2 5.19615a.out
2nd norm p4,p2 5.19615