Constructor overloading in C++
Constructor overloading in C++
(OOP)
Lab
Topic: Constructor overloading in C++
Lab Tasks:
1. Student Class Implementation
2. Product Class with Overloaded Constructors
3. Simple Counter Class with Constructors and Destructor
Objectives:
• Understanding constructor overloading in C++.
Constructor overloading in C++
• Constructor overloading in C++ refers to the ability to define
multiple constructors for a class, each with a different signature/
different parameter.
• The constructors with the same name must differ in one of the
following ways:
▪ Number of parameters.
▪ Type of parameters.
▪ Sequence of parameters.
• This allows objects of the class to be initialized in different ways
depending on the parameters provided during object creation.
Syntax:
• Syntax for constructor overloading in C++:
class ClassName {
public:
// Constructor with no parameters
ClassName() {
// Constructor code
}
int main() {
// Creating objects using different constructors
ClassName object1; // Calls constructor with no parameters
ClassName object2(argument); // Calls constructor with one parameter
ClassName object3(argument1, argument2); // Calls constructor with two parameters
return 0; }
Explanation:
• ClassName is the name of the class.
• Constructors are defined inside the class with the same
name as the class.
• Each constructor has a different parameter list.
• In the main function, objects of ClassName are created
using different constructors.
Here's a very simple example demonstrating constructor overloading
#include <iostream>
using namespace std;
public:
// Default constructor
MyClass() {
num = 0;
}
// Displaying values
obj1.display(); // Output: Value: 0
obj2.display(); // Output: Value: 5
obj3.display(); // Output: Value: 30
return 0;
}
Program Output
Value: 0
Value: 5
Value: 30
Destructor in C++
A destructor in C++ is a special member function of a class that is
automatically called when an object of that class goes out of scope or is
explicitly deleted using the delete keyword. The primary purpose of a
destructor is to release resources that the object may have acquired
during its lifetime, such as dynamic memory allocation or closing file
handles.
Here are some key points about destructors:
1. Syntax: A destructor is identified by its name, which is the tilde
character (~) followed by the class name. For example: ~ClassName().
2. No Return Type or Parameters: Destructors do not have a return
type and do not accept any parameters. They cannot be overloaded
with different parameter lists.
3. Automatic Invocation: Destructors are automatically called when an
object goes out of scope or when delete is explicitly called on a
dynamically allocated object.
4. Order of Destruction: Destructors are called in the reverse order of
construction. That is, the destructor of the most derived class is called
first, followed by destructors of base classes.
5. Implicitly Defined: If a class does not explicitly define a destructor,
the compiler provides a default destructor, which performs no specific
action. However, if a class manages resources that require cleanup, it's
often necessary to define a custom destructor.
6. Resource Cleanup: Destructors are commonly used to release
resources acquired by an object, such as freeing dynamically allocated
memory, closing file handles, releasing network connections, etc.
Syntax for a destructor in C++:
class ClassName {
public:
// Constructor(s), member functions, etc.
~ClassName() {
// Destructor code
}
};
Example 1: Destructor
#include <iostream>
using namespace std;
class SimpleClass {
public:
SimpleClass() {
cout << "Constructor called" << endl;
}
~SimpleClass() {
cout << "Destructor called" << endl;
}
};
int main() {
SimpleClass obj; // Object created
return 0;
}
Program Output
• Constructor called
• Destructor called
Object Creation:
•Creating objects using different constructors:
•Calculator calc1; // Calls default constructor
•Calculator calc2(5); // Calls constructor with one
parameter
•Calculator calc3(10, 2); // Calls constructor with two
parameters
After creating objects using different constructors, you can
perform arithmetic operations and display the results using
the provided member functions.
#include <iostream>
using namespace std;
class Calculator {
private:
double num1;
double num2;
public:
// Default constructor
Calculator() {
num1 = 0;
num2 = 0;
}
}
return 0;
Program Output
Addition: 12
Subtraction: 8
Multiplication: 20
Division: 5
Program 2:- Problem Description:
Create a class called Book to represent books. The class
should have the following features:
• It should have private member variables for the title,
author, and year of publication of the book.
o Data Members: title, author, and yearOfPublication.
Implement constructor overloading:
• Default constructor: Initializes all member variables to
empty strings and 0, respectively.
• Constructor with one parameter: Sets the title and
initializes the author and year of publication to empty
strings and 0, respectively.
• Constructor with three parameters: Sets all member
variables.
Provide member functions to:
• Get the title of the book. Method name: getTitle()
• Get the author of the book. Method name: getAuthor()
• Get the year of publication of the book. Method name:
getYearOfPublication()
• Set the title of the book. Method name: setTitle()
• Set the author of the book. Method name: setAuthor()
• Set the year of publication of the book. Method name:
setYearOfPublication()
• Display the details of the book, including title, author, and
year of publication. Method name: displayDetails()
o Object Creation:
• Creating objects using different constructors:
o Book book1; // Calls default constructor
o Book book2("The Great Gatsby"); // Calls constructor
with one parameter
o Book book3("To Kill a Mockingbird", "Harper Lee",
1960); // Calls constructor with three parameters
After creating objects using different constructors, you can get
and set the title, author, year of publication, and display the
details of each book using the provided member functions.
Program
#include <iostream>
#include <string>
using namespace std;
class Book {
private:
string title;
string author;
int yearOfPublication;
public:
// Default constructor
Book() {
title = "";
author = "";
yearOfPublication = 0;
}
int main() {
// Creating objects using different constructors
Book book1; // Calls
default constructor
Book book2("The Great Gatsby"); // Calls
constructor with one parameter
Book book3("To Kill a Mockingbird", "Harper Lee",
1960); // Calls constructor with three parameters
return 0;
}
Output?
Program 3:- Problem Description:
You are tasked with implementing a simple class called Box to
represent rectangular boxes. The Box class should have the
following features:
1. Private Member Variables:
• length (integer): Represents the length of the box.
• width (integer): Represents the width of the box.
2. Default Constructor:
• Initializes both length and width to 0.
• Displays a message indicating that the default
constructor has been called.
3. Parameterized Constructor:
• Allows initializing length and width with provided
values.
• Displays a message indicating that the parameterized
constructor has been called.
4. Destructor:
• Displays a message indicating that the destructor has
been called when an object of the class is destroyed.
5. Method: void display():
• Displays the length and width of the box.
Your Task:
Implement the Box class according to the provided
specifications.
In the main function:
• Create two Box objects, one using the default constructor
and another using the parameterized constructor with
length 5 and width 3.
• Display the details of both boxes using the display()
method
Program:
#include <iostream>
using namespace std;
class Box {
private:
int length;
int width;
public:
Box() {
length = 0;
width = 0;
cout << "Default constructor called" << endl;
}
Box(int l, int w) {
length = l;
width = w;
cout << "Parameterized constructor called" << endl;
}
~Box() {
cout << "Destructor called" << endl;
}
void display() {
cout << "Length: " << length << ", Width: " << width << endl;
}
};
int main() {
Box box1; // Calls default constructor
Box box2(5, 3); // Calls parameterized constructor
box1.display();
box2.display();
return 0;
}
LAB TASK
Lab Task #1: Student Class Implementation
1. Define a class called Student with the following features:
• Private member variables: name (string), rollNumber (int), and
grade (char).
• Default constructor: Initializes name to "Unknown", rollNumber
to 0, and grade to F.
• Parameterized constructor: Allows initializing name, rollNumber,
and grade with provided values.
• Method: void display() - Displays the name, roll number, and
grade of the student.
2. Implement the Student class according to the above specifications.
3. In the main function:
• Create two Student objects, one using the default constructor and
another using the parameterized constructor with name "Niamat",
roll number 101, and grade 'A'.
• Display the details of both students using the display() method.
4. Compile and run your program to verify its correctness.
Sample Output:
Student 1:
Name: Unknown
Roll Number: 0
Grade: F
Student 2:
Name: Niamat
Roll Number: 101
Grade: A
Lab Task #2:
Implementing a Product Class with Overloaded Constructors
Problem Description:
You are required to create a class called Product to represent products in
a store. The Product class should have the following features:
1. Private Member Variables:
• name (string): Name of the product.
• id (string): Unique identifier of the product.
• price (double): Price of the product.
• quantity (int): Quantity of the product in stock.
• category (string): Category of the product.
2. Default Constructor:
• Initializes name to "Unknown", id to "0000", price to 0.0, quantity
to 0, and category to "Unknown".
3. Parameterized Constructors:
• Constructor 1: Initializes name, id, price, quantity, and category
with provided values.
• Constructor 2: Initializes name, id, price, and category with
provided values, and sets quantity to 0.
• Constructor 3: Initializes name, id, price, and quantity with
provided values, and sets category to "Unknown".
• Constructor 4: Initializes name, price, quantity, and category with
provided values, and sets id to "0000".
• Constructor 5: Initializes id, price, quantity, and category with
provided values, and sets name to "Unknown".
4. Method: void display():
• Displays the details of the product, including name, id, price,
quantity, and category.
Your Task:
1. Implement the Product class according to the above specifications.
2. In the main function:
• Create five Product objects using each of the overloaded
constructors.
• Display the details of each product using the display() method.
3. Compile and run your program to verify its correctness.
Example Output:
Product 1:
Name: Unknown
ID: 0000
Price: $0.00
Quantity: 0
Category: Unknown
Product 2:
Name: Laptop
ID: LAP123
Price: $799.99
Quantity: 10
Category: Electronics
Product 3:
Name: iPhone
ID: IPH456
Price: $999.99
Quantity: 20
Category: Electronics
Product 4:
Name: Unknown
ID: PRO987
Price: $19.99
Quantity: 30
Category: Books
Product 5:
Name: PRO567
ID: Unknown
Price: $5.99
Quantity: 50
Category: Stationery
Lab Task #3: Implementing a Simple Counter Class with
Constructors and Destructor
Problem Description:
You are tasked with creating a simple class called Counter to represent a
counter. The Counter class should have the following features:
1. Private Member Variable:
• count (integer): Represents the count value of the counter.
2. Default Constructor:
• Initializes count to 0.
• Displays a message indicating that the counter has been initialized
with 0.
3. Parameterized Constructor:
• Allows initializing count with a provided initial value.
• Displays a message indicating the initial value with which the
counter has been initialized.
4. Destructor:
• Displays a message indicating that the destructor has been called
along with the final count value when the counter object is
destroyed.
5. Method: void increment():
• Increments the count value by 1.
6. Method: void display():
• Displays the current count value.
Your Task:
Implement the Counter class according to the provided specifications.
In the main function:
• Create two Counter objects, one using the default constructor and
another using the parameterized constructor with an initial count
value of 5.
• Increment the count value of both counters using the increment()
method.
• Display the count value of both counters using the display() method.
Compile and run your program to verify its correctness.