When copies of objects are made

A copy constructor is called whenever a new variable is created from an object. This happens in the following cases (but not in assignment).

C++ calls a copy constructor to make a copy of an object in each of the above cases. If there is no copy constructor defined for the class, C++ uses the default copy constructor which copies each field, ie, makes a shallow copy.

Copy constructors are required for classed having POINTERS , FILEHANDLES and OTHER RESOURCES

class Person {
private:
  int age;
  char * name;
public:   // the following three member functions must be defined by the class implementer 
  Person (const char * name, int age);
  Person (const Person& other);
};
 
int a = 10;
int b = 5;
int * pa = &a;
int * pb = &b;

cout << "pa = " << pa << "\n";
cout << "pb = " << pb << "\n";

cout << "a = " << *pa << "\n";
cout << "b = " << *pb << "\n";

pb = pa;
cout << "After pb = pa \n\n";

cout << "pa = " << pa << "\n";
cout << "pb = " << pb << "\n";

cout << "a = " << *pa << "\n";
cout << "b = " << *pb << "\n";
 

char a[] = "a\0";
char b[] = "b\0";
char * pa = a;
char * pb = b;

cout << "pa = " << &pa << "\n";
cout << "pb = " << &pb << "\n";

cout << "a = " << pa << "\n";
cout << "b = " << pb << "\n";

//strcpy(pb,pa);
pb = pa;
cout << "After pb = pa \n\n";

cout << "pa = " << &pa << "\n";
cout << "pb = " << &pb << "\n";

cout << "a = " << pa << "\n";
cout << "b = " << pb << "\n";
 

Hosted by www.Geocities.ws

1