Copy constructor is
- a constructor function (Function with the same name as the class)
- used to make deep copy of objects.
There are 3 important places where a copy constructor is called.
- When an object is created from another object of the same type
- When an object is passed by value as a parameter to a function
- When an object is returned from a function
If a copy constructor is not defined in a class, the compiler itself defines one. This will ensure a shallow copy. If the class does not have pointer variables with dynamically allocated memory, then one need not worry about defining a copy constructor. It can be left to the compiler's discretion.
But if the class has pointer variables and has some dynamic memory allocations, then it is a must to have a copy constructor. (Find its example in BLUE colour)
For ex:
class A //Without copy constructor
{ private:
int x;
public:
A() {A = 10;}
~A() { }
};
class B //************** With copy constructor ************
{
private:
int month;
public:
B( int y) //********* Parameterized constructor ***********
{
month = y;
}
~B( )
{
cout << "destructor function invoked"; }
B( B &b) //*************** Copy constructor *************
{
month = b.month;
}
};
class B //With copy constructor
{
private:
char *name;
public:
B()
{
name = new char[20];
}
~B()
{
delete name[];
}
//Copy constructor
B(B &b)
{
name = new char[20];
strcpy(name, b.name);
}
};
Example : When an object is created from another object of the same type
class A
{ int a;
public:
A(int x )
{ cout <<"Constructor invoked ..."; a=x; } }Obj1(23); A Obj2=Obj1; }
1. When an object is passed by value as a parameter to a function
2.When an object is returned from a function
class time
{ int hr;
int min;
public:
time ( ) // ******** constructor function ********
{ hr = min = 0;}
void gettime(int x,int y) {hr=x;min=y;}
void showtime( ) { cout <<" : " <
time addtime( time T1, time T2)
{ time T3;
T3.hr =
if (T3.min >= 60)
{ T3.min =T3.min - 60;
T3.hr = T3.hr+1;
}
return T3;
}
void main( )
{ time X1 (5,45); // Parameterized constructor Invoked
time X2 (7,40); // Parameterized constructor Invoked
time X3=addtime(X1,X2); // Copy Constructor invoked
X3.showtime( ); // This will show the time as 13 : 25
}
1 comment:
class B //************** With copy constructor ************
{
private:
int month;
public:
B( int y) //********* Parameterized constructor ***********
{
month = y;
}
~B( )
{
cout << "destructor function invoked"; }
B( B &b) //*************** Copy constructor *************
MAM above LINE is not clear
{
month = b.month;
}
};
class B //With copy constructor
{
private:
char *name;
public:
B()
{
name = new char[20];
}
~B()
{
delete name[];
}
//Copy constructor
B(const B &b)
/*USE of constant not clear*/
{
name = new char[20];
strcpy(name, b.name);
}
};
Post a Comment