0% found this document useful (0 votes)
212 views

Lab03: Constructor and Destructor

The document discusses constructors, destructors, and copying in C++ classes. It defines: 1. Constructors initialize objects and are called automatically upon object creation. They have the same name as the class but no return type. 2. Destructors clean up objects and are called when objects are destroyed. They are prefixed with a tilde (~). 3. Shallow copying just copies member values but can cause problems if members point to dynamic memory. Deep copying allocates new memory for copied members.

Uploaded by

dfgsdf sfd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
212 views

Lab03: Constructor and Destructor

The document discusses constructors, destructors, and copying in C++ classes. It defines: 1. Constructors initialize objects and are called automatically upon object creation. They have the same name as the class but no return type. 2. Destructors clean up objects and are called when objects are destroyed. They are prefixed with a tilde (~). 3. Shallow copying just copies member values but can cause problems if members point to dynamic memory. Deep copying allocates new memory for copied members.

Uploaded by

dfgsdf sfd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

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;

• A class contains at least one constructor.


• A class may contain more than one constructor (overloaded constructor).
• C++ requires a constructor call for each object that’s created, which helps ensure that each object is
initialized properly before it’s used in a program. The constructor call occurs implicitly when the object
is created.This ensures that objects will always have valid data to work on.
• Normally, constructors are declared public.

<constructor name> ( <parameters> )


{
<constructor body>
}

• The constructor name: a constructor has the name of the class.


• The parameter represent values that will be passed to the constructor for initialization of the object
state.
• Constructor declarations look like method declarations except that they use the name of the class
and have no return type.
DIFFERENCE BETWEEN CONSTRUCTORS AND OTHER FUNCTIONS
• A constructor must be defined with the same name as the class.
• Constructors do not possess a return type (not even void).

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

public: //Public interface:


string name; // Account holder
long accountNumber; // Account number
Account()
{ Default/
O
cout<<endl<<"Dafault constructor has been called"<<endl;
No Argument V
name="Inshrah";
setDetails(85000);
Constructor E
}
R
Account(double balance) L
{ O
cout<<endl<<"One argument constructor has been called"<<endl; One Argument
name = "Javeria"; Constructor A
setDetails(balance);
} D
I
Account(string accHolder, double balance)
{ N
cout<<endl<<"Two arguments constructor has been called"<<endl;
name = accHolder;
Two G
Arguments
setDetails(balance);

}
~ Account()
{
cout<<endl<<"Object Destroyed"; Destructor
}

void setDetails(double bal)


{
balance = bal;
}
double getDetails()
{
return balance;
}
void displayDetails()
{
cout<<"Account Holder: "<<name<<endl;
cout<<"Account Balance: "<<balance<<endl;
}};

int main()
{
cout<<"First statement in main"<<endl;

Account currentAccount; //calls default constructor


cout<<"Details for currentAccount: "<<endl;
currentAccount.displayDetails();

Account savingAccount(25000); //calls one argument constructor


cout<<"Details for savingAccount: "<<endl;
savingAccount.displayDetails();

Account fixedAccount("Zainab",95000); //calls two arguments constructor


cout<<"Details for fixedAccount: "<<endl;
fixedAccount.displayDetails();
cout<<endl<<"Last statement in main"<<endl;
return 0;
}

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.

4. SHALLOW COPYING OR MEMBER WISE COPYING


The default copy constructor and the assignment operators use the copying method known as member
wise copy or shallow copy. Shallow copy means copying the data member by member using the
assignment operator. The assignment operator just copies the address of the pointer but it would not
allocate any memory or copy the contents being pointed to. This will work fine when the class is not
dealing with the dynamically allocated memory.
EXAMPLE CODE (SHALLOW 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';
}
void DeleteNamePtr()
{
delete name;
}
void Display()
{
cout<<endl<<"Name: "<<name<<endl;
}
};

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)

PROBLEMS WITH SHALLOW COPYING


Deleting the object “student1” causes the second object “student2” to point to a deallocated memory
location(i.e. dangled).
Updating the object “student1” also updates the second object “student2”.

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;
}

Output: EXAMPLE CODE (DEEP COPYING)


TASKS
Q1): Demonstrate a class Sale that calculate the sale on an overall items, where sales is of 6% on overall
item. You must call a constructor that takes the sale rate as an argument, and two member function one
which calculate the sales and and another function getTotal which returns the total sale. Your Program
should print the TotalSale in main function.

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

Q4): INVENTORY OF BOOK USING CONSTRUCTOR AND DESTRUCTOR


Aim
To write a C++ program for booking using constructor and destructor.
Algorithm
Step 1: Create an object for the class book.
Step 2: Declare the pointer variable for author, title, and publisher and the Variable for price and
stock position.
Step 3: Read the number of records.
Step 4:Display a menu with the following choice create ,buybook, transaction and display.
Step 5:Using switch case execute the statements corresponding to the choice.
Step 6:If the choice is create, read the title, author, publishes, price and stock position and pass
it to the constructor of the book class.
Step 7;Find the string length of each of the pointer variables dynamically.
Step 8:If the choice is buy books, read the title, author, stock from the user and check these with
the array already created.
Step 9:If the author name and title matches then display the message”:Available” and read the number
of copies.
Step 10:Decrement the stock position by 1 and display the mount to be paid. Increment successful
transaction by 1. Else display “NOT success” and increment the unsuccessful transaction by 1.
Step 11:If the transaction; display the variables, successful transaction and unsuccessful transaction.
Step 12:If the choice is display, then display all the details such as title, author, price, publishes
and stock position.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy