Copy Constructor & Destructor
Copy Constructor & Destructor
Unit 2
Copy Constructor
Sample(Sample &t)
{
id=t.id;
}
Copy constructor
• The process of initializing members of an object through a
copy constructor is known as copy initialization.
};
student::student(int no,char n[ ],double f)
{
rno=no;
strcpy(name,n);
fee=f;
}
void student::display()
{
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
}
int main()
{
student s(1001,"Manjeet",10000);
s.display();
return 0;
}
Characteristics of Copy Constructor
class Point {
private:
int x, y;
public:
Point(int x1, int y1)
{
x = x1;
y = y1;
}
// Copy constructor
Point(const Point& p1)
{
x = p1.x;
y = p1.y;
}
int main()
{
class Test {
public:
// User-Defined Constructor
Test() { cout << "\n Constructor executed"; }
// User-Defined Destructor
~Test() { cout << "\nDestructor executed"; }
};
main()
{
Test t;
return 0;
}
Example: Multiple Objects
#include <iostream>
using namespace std;
class Test {
public:
// User-Defined Constructor
Test() { cout << "\n Constructor executed"; }
// User-Defined Destructor
~Test() { cout << "\n Destructor executed"; }
};
main()
{
// Create multiple objects of the Test class
Test t, t1, t2, t3;
return 0;
}
Output
• Constructor executed
• Constructor executed
• Constructor executed
• Constructor executed
• Destructor executed
• Destructor executed
• Destructor executed
• Destructor executed
Properties of Destructor