Oop-Lab-3 Alishba
Oop-Lab-3 Alishba
Oop-Lab-3 Alishba
EXPERIMENT NO 3
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
Experimental results
Conclusion
Total Marks: Obtained Marks: :
Date: Signature:
EXPERIMENT NO 3
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.
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:
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.
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>
• private:
• string name;
• float latitude;
• float longitude;
• float area;
• long population;
• string capital;
• public:
• Country() ///constructor
• {}
• void get_data()
• {
• getline(cin, name);
• getline(cin, capital);
• }
• {
• cout << "Location (Lat, Lon): " << latitude << " , " << longitude <<
endl;
• cout << "Area: " << area << " square kilometers" << endl;
• }};
• int main()
• {
• const int a = 3;
• Country obj[a];
• {
• cout << "\nEnter details for country " << (i + 1) << ":\n";
• obj[i].get_data();
• }
• }
• return 0;
• }
• Enter Longitude: 16
• Enter Capital:Islamabad
• Countries Information:
• Country 1 Information:
• Population: 1000000
• Capital:
• Country 2 Information:
• Population: 2000000
• Capital:Istanbol
• Country 3 Information:
• Population: 3000000
• Capital:Doha
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
DEV C++CODE