0% found this document useful (0 votes)
18 views41 pages

Constructor overloading in C++

The document discusses constructor overloading and destructors in C++, detailing their syntax, usage, and examples. It includes lab tasks for implementing classes such as Student, Product, and Calculator, showcasing how to utilize overloaded constructors and destructors effectively. The document aims to enhance understanding of object-oriented programming concepts in C++.

Uploaded by

pcpc4289
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)
18 views41 pages

Constructor overloading in C++

The document discusses constructor overloading and destructors in C++, detailing their syntax, usage, and examples. It includes lab tasks for implementing classes such as Student, Product, and Calculator, showcasing how to utilize overloaded constructors and destructors effectively. The document aims to enhance understanding of object-oriented programming concepts in C++.

Uploaded by

pcpc4289
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/ 41

Object Oriented Programming

(OOP)
Lab
Topic: Constructor overloading in C++

Mr. Niamat Ullah Junior lecturer


Department of CS & IT,
Sarhad University, Peshawar.
Topic Agenda:
• Constructor Overloading
• Destructor 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
}

// Constructor with one parameter


ClassName(datatype parameter1) {
// Constructor code
}

// Constructor with two parameters


ClassName(datatype parameter1, datatype parameter2) {
// 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;

// Declaration of the class MyClass


class MyClass {
private:
int num; // Private member variable

public:
// Default constructor
MyClass() {
num = 0;
}

// Constructor with one parameter


MyClass(int val) {
num = val;
}

// Constructor with two parameters


MyClass(int val1, int val2) {
num = val1 + val2;
}

// Function to display the value


void display() {
cout << "Value: " << num << endl;
}
};
// Main function
int main() {
// Creating objects using different constructors
MyClass obj1; // Calls default constructor (no parameters)
MyClass obj2(5); // Calls constructor with one parameter
MyClass obj3(10, 20); // Calls constructor with two parameters

// 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

// Object goes out of scope at the end of the block


// Destructor automatically called to release resources

return 0;
}
Program Output
• Constructor called
• Destructor called

• In this example, the SimpleClass has a constructor that


prints a message when an object is created and a
destructor that prints a message when an object is
destroyed.
• When the obj object goes out of scope at the end of
the main() function, its destructor is automatically
called.
Illustrated with Additional Examples
Program 1:- Problem Description:
Create a class called Calculator to perform simple arithmetic
operations.
The class should have the following features:
• It should have private member variables for two numbers
on which arithmetic operations will be performed.
• Data Members: num1 and num2.

Implement constructor overloading:


•Default constructor: Initializes both numbers to 0.
•Constructor with one parameter: Sets the first number
and initializes the second number to 0.
•Constructor with two parameters: Sets both numbers.
Provide member functions to:
• Perform addition: Method name: add()
• Perform subtraction: Method name: subtract()
• Perform multiplication: Method name: multiply()
• Perform division: Method name: divide()
• Display the result of each operation.

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

// Constructor with one parameter


Calculator(double n) {
num1 = n;
num2 = 0;
}

// Constructor with two parameters


Calculator(double n1, double n2) {
num1 = n1;
num2 = n2;
}
// Function to perform addition
double add() {
return num1 + num2;
}

// Function to perform subtraction


double subtract() {
return num1 - num2;
}

// Function to perform multiplication


double multiply() {
return num1 * num2;
}

// Function to perform division


double divide() {
if (num2 == 0) {
cout << "Error: Division by zero!" << endl;
return 0;
}
return num1 / num2;
}
};
int main() {
// 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

// Displaying results of arithmetic operations


cout << "Addition: " << calc3.add() << endl;
cout << "Subtraction: " << calc3.subtract() << endl;
cout << "Multiplication: " << calc3.multiply() << endl;
cout << "Division: " << calc3.divide() << endl;

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

// Constructor with one parameter


Book(string t) {
title = t;
author = "";
yearOfPublication = 0;
}
// Constructor with three parameters
Book(string t, string a, int year) {
title = t;
author = a;
yearOfPublication = year;
}

// Getter for title


string getTitle() {
return title;
}

// Getter for author


string getAuthor() {
return author;
}

// Getter for year of publication


int getYearOfPublication() {
return yearOfPublication;
}

// Setter for title


void setTitle(string t) {
title = t;
}

// Setter for author


void setAuthor(string a) {
author = a;
}

// Setter for year of publication


void setYearOfPublication(int year) {
yearOfPublication = year;
}

// Display the details of the book


void displayDetails() {
cout << "Title: " << title << endl;
cout << "Author: " << author << endl;
cout << "Year of Publication: " <<
yearOfPublication << endl;
}
};

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

// Displaying details of each book


cout << "Book 1 Details:" << endl;
book1.displayDetails();
cout << "\nBook 2 Details:" << endl;
book2.displayDetails();

cout << "\nBook 3 Details:" << endl;


book3.displayDetails();

// Setting title, author, and year of publication for


book1
book1.setTitle("1984");
book1.setAuthor("George Orwell");
book1.setYearOfPublication(1949);

// Displaying updated details of book1


cout << "\nUpdated Book 1 Details:" << endl;
book1.displayDetails();

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.

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