Lab03: Constructor and Destructor
Lab03: Constructor and Destructor
Introduction to :
1. Constructor
2. Destructor
3. Copy Constructor
4. Shallow Copying or Member Wise Copying
5. Deep Copying
1. CONSTRUCTOR
• A constructor is a special method that has the same name as the class.
• It is not a void method nor value returning method.
• Constructors define the initial states of objects when they are created.
ClassName x;
DEFAULT CONSTRUCTOR
• A default constructor is used to set initial or default values to the attributes of the object.
• A default constructor does not have parameters.
• If no constructors are defined in the class, the default constructor is added by the compiler at compile
time.
• If a class does not contain a constructor definition, the compiler will create a minimal version of the
default constructor as a public member. However, this constructor will not perform initialization.An
uninitialized variable typically contains a “garbage” value.
• By contrast, if a class contains at least one constructor, a default constructor must be defined
explicitly.
CONSTRUCTOR OVERLOADING
When two or more functions share the same name, the function name is said to be overloaded.Any class
member function may be overloaded, including the constructor. One constructor might take an integer
argument, for example, while another constructor takes a double.
2. DESTRUCTOR
Objects that were created by a constructor must also be cleaned up in an orderly manner.The tasks
involved in cleaning up include releasing memory and closing files.
Objects are cleaned up by a special method called a destructor, whose name is made up of the class
name preceded by ~(tilde).
Syntax: ~class_name();
EXAMPLE CODE (No, One, Two Arguments Constructors and Destructor)
#include<iostream>
#include<string>
using namespace std;
class Account
{
private:
double balance; // Account balance
}
~ Account()
{
cout<<endl<<"Object Destroyed"; Destructor
}
int main()
{
cout<<"First statement in main"<<endl;
3. COPY CONSTRUCTOR
The copy constructor initializes an object with another object of the same type. It is called
automatically when a second, already existing object is used to initialize an object.
The copy constructor is used to:
• Initialize one object from another of the same type.
• Copy an object to pass it as an argument to a function.
• Copy an object to return it from a function.
#include<iostream>
#include<stdlib.h>
#include<cstring>
using namespace std;
class Student
{
public:
char *name;
Student(char *nam="")
{
int m_nLength = strlen(nam) + 1;
int main()
{
Student student1("Ali");
Student student2 = student1; // uses default copy constructor i.e. shallow copy
student1.Display();
student2.Display();
student1.DeleteNamePtr();
cout<<endl<<"student1 object destroyed";
student1.Display();
student2.Display();
cin.get();
return 0;
}
Output: EXAMPLE CODE (SHALLOW COPYING)
5. DEEP COPYING
This duplicates the member variables that are pointed to the destination. Therefore, there will be the
copy of another member is created which is local to the destination object. So to implement the deep
copy we need to write explicitly our copy constructor and the assignment operator functions.
EXAMPLE CODE (DEEP COPYING)
#include<iostream>
#include<stdlib.h>
#include<cstring>
using namespace std;
class Student
{ public:
char *name;
Student(char *nam="")
{
int m_nLength = strlen(nam) + 1;
// Allocate a buffer equal to this length
name= new char[m_nLength];
// Copy the parameter into our internal buffer
strncpy(name, nam, m_nLength);
// Make sure the string is terminated
name[m_nLength-1] = '\0';
}
Student(const Student &obj ) //COPY constructor
{
name = new char[strlen(obj.name)+1];
strcpy(name,obj.name);
}
void DeleteNamePtr()
{
delete name;
}
void Display()
{
cout<<endl<<"Name: "<<name<<endl;
}
};
int main()
{
Student student1("Ali");
Student student2 = student1; // usesuser defined copy constructor i.e. deep copying
student1.Display();
student2.Display();
student1.DeleteNamePtr();
cout<<endl<<"student1 object destroyed";
student1.Display();
student2.Display();
cin.get();
return 0;
}
Q2): Consider the code provided above for shallow and deep copy.
Create a class ‘Employee’ having two data members ‘EmployeeName’(character pointer) and
‘EmployeeId’ (integer).Keep both data members private. Create an object ‘Employee1’ of type
‘Employee’. Copy the contents of ‘Employee1’ to ‘Employee2’ in such a manner that if ‘Employee1’
gets deallocated, ‘Employee2’ still holds the assigned data.
Analyze the benefits of deep copying over shallow copying.
Q3): Demostrate a class that print the combination of strings. Your program should use two constructor.
The first constructor should be an empty constructor that will allow to declare an array of string. The
second constructor will initializes the length of the string , allocate the necessary space for the string to
be stored and creates the string itself using strcpy. Your program should consist of one member function
join() that concatenates two strings. It should estimates the length of the string to be joined, allocates
the memory for the combined string and then uses strcpy() to copy the string and strcat() to concatenate
the strings. Your main() function program should concatenate three strings into one string such as
Mirza Jameel Baig