Oop-Lab-3 Alishba

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 17

AIR UNIVERSITY

DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING

EXPERIMENT NO 3

Lab Title: Destructor, Constructor, and its types


Student Name:JAWAD MIR Reg. No:231509
Objective: : The purpose of this report is to offer a comprehensive explanation of
structures in C++. It will clarify what a structure is, how it is defined, and how it can
be utilized to organize and handle various types of data within a single entity

LAB ASSESSMENT:
Attributes Excellent Good Average Satisfact Unsatisfact
(5) (4) (3) ory (2) ory (1)
Ability to Conduct
Experiment
Ability to assimilate
the results
Effective use of lab
equipment and
follows the lab safety
rules

Total Marks: Obtained Marks:

LAB REPORT ASSESSMENT:


Attributes Excellent Good Average Satisfact Unsatisfact
(5) (4) (3) ory (2) ory (1)
Data presentation

Experimental results

Conclusion
Total Marks: Obtained Marks: :

Date: Signature:
EXPERIMENT NO 3

Destructor, Constructor, and its types

Objectives
In this lab students will learn,
➢ Default Constructors
➢ Passing parameters to constructors (Parametrized
constructors) ➢ Constructor overloading
➢ Copy constructor
➢ Destructor

Equipment required
➢ Visual Studio/ Dev C++/Eclipse installed in Windows/PC

Constructor
1. • Special member function -- same name as the class name
2. • Initialization of data members
3. • Acquisition of resources
4. • Opening files
5. • Does NOT return a value
6. • Implicitly invoked when objects are created
7. • Can have arguments
8. • Cannot be explicitly called
9. • Multiple constructors are allowed
10. • If no constructor is defined in a program, default
constructor is called • no arguments
11. • constructors can be overloaded (two constructors with same
name but having different signatures)

Types of Constructors
Constructors are of three types:
• Default Constructor
• Parametrized Constructor
• Copy Constructor

Default Constructor
Default constructor is the constructor that doesn't take any argument. It has no parameter.
Example
• #include <iostream>
• using namespace std;

• class DemoDC {
• private:
• int num1, num2;
• public:
• DemoDC() {
• num1 = 10;
• num2 = 20;
• }
• void display() {
• cout<<"num1 = "<< num1 <<endl;
• cout<<"num2 = "<< num2 <<endl;
• }
• };
• int main() {
• DemoDC obj;
• obj.display();
• return 0;
• }
LAB TASKS
Q1. Define a class Customer that holds private fields for a customer's ID, first name,
last name, address, and credit limit.
• Define functions that set the fields of customer. For example
setCustomerID(). • Define functions that shows the fields of customer. For
example
getCustomerID().
• Use constructor to set the default values to each of the field.
• Overload at least two constructors of the customer class.
• Define a function that takes input from user and set all fields of customer
data. • Using copy constructor, copy the data to another object.
• Create Destructors for each Constructor.
CODE :
• #include <iostream>
• #include <string>
• #include <cmath>
• using namespace std;

• class Customer {
• private:
• int customer_id;
• string first_name;
• string last_name;
• string address;
• int credit_limit;
• public:
• Customer() { // default constructor
• customer_id = 0;
• first_name = "unknown";
• last_name = "unknown";
• address = "unknown";
• credit_limit = 0;
• cout << "Default constructor called." << endl;
• }

• Customer(int id, string fn, string ln, string add, int cl) { // parameterized
constructor
• customer_id = id;
• first_name = fn;
• last_name = ln;
• address = add;
• credit_limit = cl;
• cout << "Parameterized constructor called." << endl;
• }

• Customer(const Customer& obj) { // copy constructor
• customer_id = obj.customer_id;
• first_name = obj.first_name;
• last_name = obj.last_name;
• address = obj.address;
• credit_limit = obj.credit_limit;
• cout << "Copy constructor called." << endl;
• }

• ~Customer() { // destructor
• cout << "Destructor called." << endl;
• }

• void set_id() {
• cout << "Enter customer first name: ";
• getline(cin, first_name);
• cout << "Enter customer last name: ";
• getline(cin, last_name);
• cout << "Enter customer address: ";
• getline(cin, address);
• cout << "Enter customer ID: ";
• cin >> customer_id;
• cout << "Enter customer credit limit: ";
• cin >> credit_limit;
• }

• void get_id() {
• cout << "Customer ID: " << customer_id << endl;
• cout << "First Name: " << first_name << endl;
• cout << "Last Name: " << last_name << endl;
• cout << "Address: " << address << endl;
• cout << "Credit Limit: " << credit_limit << endl;
• }
• };

• int main() {
• Customer obj;
• obj.get_id();
• Customer obj2(231532, "izhar", "ul haq", "rawalpindi", 231547);
• obj2.get_id();
• obj.set_id();
• obj.get_id();
• Customer obj3 = obj2; // copy constructor
• obj3.get_id();

• return 0;
• }
OUTPUT OF THIS CODE:

Credit Limit: 0
Parameterized constructor called.
Customer ID: 231532
First Name: izhar
Last Name: ul haq
Address: rawalpindi
Credit Limit: 231547
Enter customer first name: Alishba
Enter customer last name: Kanwal
Enter customer address: street 25 house no 31
Enter customer ID: 231474
Enter customer credit limit: 10000
Customer ID: 231474
First Name: Alishba
Last Name: Kanwal
Address: street 25 house no 31
Credit Limit: 10000
Copy constructor called.
Customer ID: 231532
First Name: izhar
Last Name: ul haq
Address: rawalpindi
Credit Limit: 231547
Destructor called.
Destructor called.
Destructor called.

DEV C++ CODE :

COMPILER OF THIS CODE IS

Parameterized constructor

When an object is instantiated using default constructor its attributes are not initialized to any
value. Values are set later by calling setters.
But what if attributes are not assigned to any meaningful value using setters? It will result in
incorrect results throughout. In order to avoid that, a class can include a special function called
its parameterized constructor, which is automatically called whenever a new object of this class
is created, allowing the class to initialize member variables or allocate storage. This constructor
function is declared just like a regular member function, but with a name that matches the class
name and without any return type; not even void but takes a list of arguments to initialize the
attributes to some meaningful value.
Instantiating Objects using default and parameterized constructors

MyClass MyClass ()
{ {
Private: val=0;
int val; }
Public: };
MyClass(int i) void main()
{ {
val=i; MyClass c; // call to default constructor
}; MyClass c2(2); // call to
parameterizedconstructor }

When a constructor is used to initialize other members, these other members can be
initialized directly, without resorting to statements in its body. This is done by inserting,
before the constructor's body, a colon (:) and a list of initializations for class members.
For example, consider a class with the following declaration:
initialization using member
initialize
MyClass
{
Private:
int val;

Public:
MyClass(int i):val(i)
{
};

};

Lab task 2

Q2. Write a class Travel that has the attributes of kilometres and hours. A constructor
with noparameters initializes both data members to 0. A member function set() inputs the
values and function show() displays the values. It has a member function add() that
takes an object of type Travel, adds the kilometres and hours of calling object and the
parameter and return an object with added values.

• #include <iostream>
• #include <string>
• #include <cmath>
• using namespace std;
• class Travel {
• private:
• int kilometres;
• int hours;

• public:
• Travel() {
• kilometres = 0;
• hours = 0;
• }
• void set() {
• cout << "Enter kilometres: ";
• cin >> kilometres;
• cout << "Enter hours: ";
• cin >> hours;
• }
• void show() const {
• cout << "Kilometres: " << kilometres << ", Hours: " << hours << endl;
• }
• void add(const Travel& t) {
• kilometres += t.kilometres;
• hours += t.hours;
• }
• };

• int main() {
• Travel t1, t2;
• cout << "Set values for first travel:\n";
• t1.set();
• cout << "Set values for second travel:\n";
• t2.set();
• t1.add(t2);
• cout<<"\n";
• cout<<"__________________________________________";
• cout<<"\n\n";
• cout << "Combined travel: ";
• t1.show();
• return 0;
• }
OUTPUT OF THIS CODE:

Set values for first travel:


Enter kilometres: 12
Enter hours: 24
Set values for second travel:
Enter kilometres: 24
Enter hours: 48
Combined travel: Kilometres: 36, Hours: 72

DEV C++ CODE

Copy Constructor
A copy constructor is a member function that initializes an object using another object of
the same class.
Syntax:

Example

• #include <iostream>
• #include <string>
• using namespace std;
• class Cars{
• string name;
• string model;
• double price;
• public:
• void setvalues(string nam,string
mod,double pri) {
• name=nam;
• model=mod;
• price=pri;
• }

• void display()
• {
• cout<<"Name:"<<name<<endl;
• cout<<"Model:"<<model<<endl;
• cout<<"Price:"<<price<<endl;}

• //default constructor
• Cars()
• {
• cout<<"Constructor initialized"<<endl;
• name="Audi";
• model="R8";
• price=2000;}
• // Copy constructor
• Cars(const Cars &c1)
• {
• cout<<"Copy Constructor
Initialized"<<endl; name=
c1.name;
• model=c1.model;
• price= c1.price;
• }

• ~Cars()
• {}
• };

• int main()
• {

• Cars c1;
• //c1.setvalues("BMW","X5",2000);
• Cars c2=c1; //Copying object
• c1.display();
• c2.display();
}
When is copy constructor called?
In C++, a Copy Constructor may be called in the following cases:
• When an object of the class is returned by value.
• When an object of the class is passed (to a function) by value as an
argument. • When an object is constructed based on another object of the
same class. • When the compiler generates a temporary object.

When is a user-defined copy constructor needed?


If we don’t define our own copy constructor, the C++ compiler creates a default copy
constructor for each class which does a member-wise copy between objects. The
compiler created copy constructor works fine in general. We need to define our own
copy constructor only if an object has pointers or any runtime allocation of the resource
like file handle, a network connection. Etc.
The default constructor does only a shallow copy.
Deep copy is possible only with user defined copy constructor. In user defined copy
constructor, we make sure that pointers (or references) of copied object point to new
memory locations.
Destructor
A member function that is called automatically when an object is destroyed used to
clean up memory in case of dynamically allocated memory. Destructors have same
name as the class, preceded by tilde ~ having no return value and no arguments
Class Destructor Syntax
class Foo {
private:
int data; // Private data member
public:
Foo(): data(0) {} // constructor
~Foo()
{
} // destructor

voidsetData(int val)
{
data=val
} // public member functions

Int getData()
{
return data;
}
};

Destructors are called in reverse order of the constructor. Automatic Objects destructor
call is always preceded by Global Objects destructor call

HOME TASK :
Q1. Create a class Country. Country is identified by its name, location on earth (which
means the longitude & latitude values) area, population & capital.
• All the data members should be private. User should be able to set the value of
all its parameters either at the time of instance creation or later be able to
individually change the values of all these identifiers whenever user want to.
• Calling member function DisplayAll_Info() should display all the information
pertaining to a country instance. User should also be able to individually call
functions such asDisplayName(), DisplayCapital etc.

To test: Ask the user to enter 3 countries and all the related info. Display the info
once Entered

CODE

• #include <iostream>

• #include <string>

• using namespace std;


• class Country {

• private:

• string name;

• float latitude;

• float longitude;

• float area;

• long population;

• string capital;

• public:

• Country() ///constructor

• {}

• void get_data()

• {

• cout << "Enter Country Name: ";

• getline(cin, name);

• cout << "Enter Latitude: ";

• cin >> latitude;

• cout << "Enter Longitude: ";

• cin >> longitude;

• cout << "Enter Area (in sq.km): ";

• cin >> area;

• cout << "Enter Population: ";

• cin >> population;


• cout << "Enter Capital: ";

• getline(cin, capital);

• }

• void display() const

• {

• cout << "Country Name: " << name << endl;

• cout << "Location (Lat, Lon): " << latitude << " , " << longitude <<
endl;

• cout << "Area: " << area << " square kilometers" << endl;

• cout << "Population: " << population << endl;

• cout << "Capital: " << capital << endl;

• }};

• int main()

• {

• const int a = 3;

• Country obj[a];

• for (int i = 0; i < a; ++i)

• {

• cout << "\nEnter details for country " << (i + 1) << ":\n";

• obj[i].get_data();

• }

• cout << "\nCountries Information:\n";

• for (int i = 0; i < a; ++i) {

• cout << "\nCountry " << (i + 1) << " Information:\n";


• obj[i].display();

• }

• return 0;

• }

OUTPUT OF THIS CODE

• Enter Longitude: 16

• Enter Area (in sq.km): 26

• Enter Population: 3000000

• Enter Capital:Islamabad

• Countries Information:

• Country 1 Information:

• Country Name: Pakistan

• Location (Lat, Lon): 10 12

• Area: 22 square kilometers

• Population: 1000000

• Capital:

• Country 2 Information:

• Country Name: Turkey

• Location (Lat, Lon): 12, 14 Area: 24 square kilometers

• Population: 2000000

• Capital:Istanbol
• Country 3 Information:

• Country Name: Qatar

• Location (Lat, Lon): 14 16

• Area: 26 square kilometers

• Population: 3000000

• Capital:Doha

DEV C++ CODE

COMPILER OF THIS CODE

Q2. Create a class SavingAccountthat helps to maintain the accounts of different customers
each customer having its own savingsBalance and also stores an
annualInterestRateProvide a member function to calculate Monthlyinterestthat calculate the
monthly interest by (balance*annualInterestRate)/12. This interest should be added to
savingBalance.

TEST PLAN
Commands Output
SavingAccount y;
y.getBalance();
y.getMonthlyInterest();
SavingAccount v(90);
v=y;
v.getMonthlyInterest();
SavingAccount j=v;
j.getBalance();
j.getMonthlyInterest();
v.getBalance();
v.getMonthlyInterest();

CODE

• #include <iostream>
• using namespace std;

• class SavingAccount
• {
• private:
• double s_balance;
• double interest;
• public:
• SavingAccount(double d, double i)
• {
• s_balance = d;
• interest = i / 100.0;
• }
• void c_interest()
• {
• double m_Interest = (s_balance * interest) / 12.0;
• s_balance += m_Interest;
• }
• void get_info() const
• {
• cout << "Savings Balance: $" << s_balance << endl;
• cout << "Annual Interest Rate: " << (interest * 100) << "%" << endl;
• }
• };
• int main() {
• double initialBalance, interestRate;
• cout << "Enter initial savings balance: $";
• cin >> initialBalance;
• cout << "Enter annual interest rate (in percentage): ";
• cin >> interestRate;
• SavingAccount obj(initialBalance, interestRate);
• obj.c_interest();
• cout << "\nAccount Information after adding monthly interest:\n";
• obj.get_info();
• return 0;
• }
OUTPUT OF THIS CODE

• Enter initial savings balance: $120


• Enter annual interest rate (in percentage): 15
• Account Information after adding monthly interest:
• Savings Balance: $121.5
• Annual Interest Rate: 15%

DEV C++CODE

COMPILER OF THIS CODE:

You might also like