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

oops lab 2

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

oops lab 2

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

LAB NO.

2
DD/MM/YYYY

CONSTRUCTORS AND DESTRUCTORS

Lab outcomes:
After completing this lab, students will be able to;
 Understand how constructors initialize objects and destructors handle
cleanup.
 Implement default, parameterized, and copy constructors.
 Apply constructor overloading and memory management in C++
classes.

Corresponding CLO and PLO:


 CLO-1, PLO-1 (Engineering Knowledge)

Theory:

Role of Constructors and Destructors in C++

In C++, constructors and destructors are special member functions of a class that are used to
initialize and clean up objects when they are created and destroyed, respectively.

1. Constructors:
o Purpose: Initialize an object when it is created.
o A constructor has the same name as the class.
o It does not have a return type, not even void.
o It can be overloaded to provide different ways to initialize objects.

The primary role of a constructor is to ensure that an object is in a valid state when it is
first created. For example, in a class Person, the constructor may initialize the name, age,
and address fields of a person.

2. Destructors:
o Purpose: Clean up any resources an object holds before it is destroyed.
o A destructor has the same name as the class but is preceded by a tilde ( ~).
o Like constructors, destructors do not have a return type, and they cannot be
overloaded.
o Destructors are primarily used to release memory or resources like file handles,
network connections, etc.

Types of Constructors in C++


In C++, constructors can be classified into three main types:

1. Default Constructor:
o A constructor that takes no parameters or has default values for all its parameters.
o If no constructor is defined by the user, the compiler automatically provides a
default constructor.
o A default constructor is useful when you want to create objects without providing
any arguments at the time of creation.
2. Parameterized Constructor:
o A constructor that takes parameters to initialize an object with specific values.
o It allows an object to be initialized with custom values when it is created.
3. Copy Constructor:
o A constructor that initializes a new object as a copy of an existing object.
o It takes a reference to an object of the same class as a parameter.
o The copy constructor is used when objects are passed by value or returned by
value from functions.

Implementing Constructors and Destructors in C++ Classes

1. Default Constructor

The default constructor does not take any parameters and initializes an object with default values

#include<iostream>
using namespace std;

class Person {
string name;
int age;
public:
// Default Constructor
Person() {
name = "Unknown";
age = 0;
cout << "Default Constructor called!" << endl;
}

void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};

int main() {
Person p1; // Default constructor is called
p1.display();
return 0;
}

Output:
Default Constructor called!
Name: Unknown, Age: 0

2. Parameterized Constructor
A parameterized constructor takes parameters and uses them to initialize
the object.
#include<iostream>
using namespace std;

class Person {
string name;
int age;
public:
// Parameterized Constructor
Person(string n, int a) {
name = n;
age = a;
cout << "Parameterized Constructor called!" << endl;
}

void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};

int main() {
Person p1("John", 25); // Parameterized constructor is called
p1.display();
return 0;
}

Output
Parameterized Constructor called!
Name: John, Age: 25

3. Copy Constructor
The copy constructor is invoked when an object is copied to initialize another
object of the same class.
#include<iostream>
using namespace std;

class Person {
string name;
int age;
public:
// Parameterized Constructor
Person(string n, int a) {
name = n;
age = a;
cout << "Parameterized Constructor called!" << endl;
}

// Copy Constructor
Person(const Person &p) {
name = p.name;
age = p.age;
cout << "Copy Constructor called!" << endl;
}

void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};

int main() {
Person p1("Alice", 30); // Parameterized constructor is called
Person p2 = p1; // Copy constructor is called
p2.display();
return 0;
}

Output
Parameterized Constructor called!
Copy Constructor called!
Name: Alice, Age: 30

4. Destructor
The destructor is automatically called when an object goes out of scope or is
explicitly deleted. Its role is to release any resources allocated during the
lifetime of the object.
#include<iostream>
using namespace std;

class Person {
string name;
int age;
public:
// Parameterized Constructor
Person(string n, int a) {
name = n;
age = a;
cout << "Constructor called!" << endl;
}
// Destructor
~Person() {
cout << "Destructor called for " << name << endl;
}

void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};

int main() {
Person p1("Charlie", 40); // Constructor is called
p1.display();
return 0;
}
Output
Constructor called!
Name: Charlie, Age: 40
Destructor called for Charlie

Task 1: Create a Class with a Default Constructor


1. Create a class named `Book`with the following private data members:
- `string title`
- `string author`
- `int pages`
2. Implement a default constructor for the `Book` class that:
- Sets `title` to `"Unknown"`
- Sets `author` to `"Unknown"`
- Sets `pages` to `0`
3. Add a member function `void display()`to print the details of the book.
4. In the `main()` function:
- Create an object of the `Book` class using the default constructor.
- Call the `display()` function to print the book details.
CODE:
Img 1: Lab Task 1(Code)
OUTPUT:
Img 2: Lab Task 1

Task 2: Implement a Parameterized Constructor


1. Modify the `Book` class** to include a parameterized constructor** that:
- Accepts `string title`, `string author`, and `int pages` as parameters.
- Initializes the respective data members with the provided values.
2. In the `main()` function:
- Create another object of the `Book` class using the parameterized constructor.
- Call the `display()` function for this object to print the details.
CODE:
Img 3: Lab Task 2(CODE)

OUTPUT:
Img 4: Lab Task 2

Task 3: Implement a Copy Constructor


1. Add a copy constructor** to the `Book` class that:
- Takes a reference to another `Book` object as a parameter.
- Copies the values of the `title`, `author`, and `pages` from the passed object to the new object.

2. In the `main()` function:


- Create a third `Book` object by copying the second `Book` object using the copy constructor.
- Call the `display()` function to print the details of the copied object.
CODE:
Img 5: Lab Task 3

OUTPUT:
Img 6: Lab Task 3

Task 4: Implement a Destructor


1. mplement a destructor** for the `Book` class that:
- Prints a message indicating that the book object is being destroyed, including the title of the
book.
2. In the `main()` function:
- At the end of the function, observe when the destructors are called.
- Explain the order of destruction based on the output.
OUTPUT:
Img 7: Lab Task 4

OUTPUT:
Img 8: Lab Task 4

Task 5: Dynamic Memory Management (Bonus Task)


1. Modify the `Book` class to dynamically allocate memory for the `title` and `author` (using
`new` and `delete`).
2. Ensure that:
- The copy constructor correctly handles deep copying of the dynamic memory.
- The destructor correctly frees the allocated memory.
Rubrics
Report not Content that The The Appropri Conclusion
submitted has been requirement observati ate drawn
plagiarized s are ons, as measure correctly
or that has described,
well as ments or with exact
Laborato been as well as
submitted the the numeric results and
ry
incompletel experiment complete al a complete
Reports
y al process. technique analysis report in
, are are every way
document carried
ed. out.
Category Ungrade Very Poor Poor Fair Good Excellent
d
Marks 0 1 2 3 4 5

Date Total Instructor’s Signature


Marks

Absent The The student The The student The student


student understands student has created successfully
is unable the followed a functional developed a
to presented instructio or working functional
adequat laboratory ns to build schematic, model,
ely instructions the core model, logic, circuit,
follow and is schematic block block
the familiar with , block diagram, or diagram, or
instructi the lab diagram, code and code and
ons environment code, or has completed
provided but Cannot model. successfull the lab
. The setup With y run the objective in
student simulation some program or real-time or
can according to assistance circuit on a in a
Demonst
name design but , the software simulation
ration
the knows how student platform. environment
hardwar to perform can set up With , achieving
e or simulation and run minimum the expected
simulatio the assistance, results. They
n simulation they can can set up,
platform, . On the set up and operate, and
but protoboar run the run the
Cannot d/trainer/s simulation. simulation
setup or imulation on their own.
perform software
the
simulatio
n
Category Ungrad Very Poor Fair Good Excellent
ed Poor
Marks 0 1 2 3 4 5

Date Total Instructor’s


Marks Signature

You might also like