Copy Cons
Copy Cons
Week 5
Lecture 1 & 2
Copy Constructor:
C++ provides a special type of constructor which takes an object as an argument and is used to
copy values of data members of one object into another object. In this case, copy constructors are
used to declaring and initializing an object from another object.
The copy constructor is a constructor which creates an object by initializing it with an object of
the same class, which has been created previously. The copy constructor is used to −
If a copy constructor is not defined in a class, the compiler itself defines one. If the class has
pointer variables and has some dynamic memory allocations, then it is a must to have a copy
constructor.
For example:
Calc C2(C1);
Or
Calc C2 = C1;
The process of initializing through a copy constructor is called the copy initialization.
Page 1 of 5
Object Oriented Programming
Programming Example:
class CopyCon {
int a, b;
public:
CopyCon(int x, int y)
{
a = x;
b = y;
cout << "\nHere is the initialization of Constructor";
}
void Display()
{
cout << "\nValues : \t" << a << "\t" << b;
}
};
void main()
{
CopyCon Object(30, 40);
//Copy Constructor
CopyCon Object2 = Object;
Object.Display();
Object2.Display();
}
Destructor Function:
As the name implies, destructors are used to destroy the objects that have been created by the
constructor within the C++ program. Destructor names are same as the class name but they are
Page 2 of 5
Object Oriented Programming
preceded by a tilde (~). It is a good practice to declare the destructor after the end of using
constructor. Here's the basic declaration procedure of a destructor:
Syntax of Destructor
~class_name()
{
//Some code
}
similar to constructor, the destructor name should exactly match with the class name. A
destructor declaration should always begin with the tilde(~) symbol as shown in the syntax
above.
Destructor rules
1) Name should begin with tilde sign(~) and must match class name.
2) There cannot be more than one destructor in a class.
3) Unlike constructors that can have parameters, destructors do not allow any parameter.
4) They do not have any return type, just like constructors.
5) When you do not specify any destructor in a class, compiler generates a default destructor
and inserts it into your code.
Page 3 of 5
Object Oriented Programming
Programming Example:
#include <iostream>
using namespace std;
class HelloWorld{
public:
//Constructor
HelloWorld(){
cout<<"Constructor is called"<<endl;
}
//Destructor
~HelloWorld(){
cout<<"Destructor is called"<<endl;
}
//Member function
void display(){
cout<<"Hello World!"<<endl;
}
};
int main(){
//Object created
HelloWorld obj;
//Member function called
obj.display();
return 0;
}
Page 4 of 5
Object Oriented Programming
Constructor is called
Hello World!
Destructor is called
Page 5 of 5