You are on page 1of 7

Copy Constructor

Week-5 (Part-1)
Shallow Copy Constructor
• Used to copy direct values

private:
Shallow Copy Constructor - Issues
• A shallow copy of an object is a new object
whose instance variables are identical to the old
object.
Deep Copy Constructor
• Used to copy indirect values
• In case of static fields, it performs bit by bit copy
• If a field is a reference type, a new copy of the referred object is
performed
• A deep copy of an object is a new object with entirely new instance
variables, it does not share objects with the old
Example
class test{ void show(){
private: cout<<"The value is :"<<*a<<endl;
int *a; }
public: };
main()
test(int q){
{
a= new int; test q1(8);
*a=q; test q2= q1;
} q2.show();
test(test &obj){ q1.mod(5);
a= new int; q2.show();
getch();
*a= *obj.a;
}
}
void mod(int e){ Output
*a=e; The value is: 8
} The value is: 8
“this.” Operator
• Every object in C++ has access to its own
address through an important pointer
called this pointer
• The this pointer is an implicit parameter to all
member functions
▫ Therefore, inside a member function, this may be
used to refer to the invoking object
▫ ‘this’ pointer is a constant pointer that holds the
memory address of the current object
▫ ‘this’ pointer is not available in static member
functions
Example
class Test{ int x;
public:
Test (int a ) // Constructor
{ x = a;}
void print () const
{
cout << " x is equal to " << x ;
cout << "this-> is equal to "<<this->x;
cout << "(*this).x is equal to "<< (*this).x;}
};
int main ()
{
Test testobject(12);
testobject.print();
return 0;
}

You might also like