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

LAB MANUAL

COURSE TITLE: Object Oriented Programming


COURSE CODE: CE-113L

STUDENT NAME:
REG. NO:
SECTION:

DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING


AIR UNIVERSITY ISLAMABAD
Lab Objectives

Lab # Lab Experiments

1 Introduction to Structures

2 Introduction to Classes

3 Constructors, Parameterized Constructors and Destructors

4 Friend classes and functions

5 Operator Overloading

6 Inheritance

7 Multiple Inheritance

8 Polymorphism

9 STL in C++

10 Smart Pointers and Exception Handling

11 Introduction to UML and Visio

12 UML State Diagrams

UML design of Project


13

14 Open-ended lab
AIR UNIVERSITY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING

EXPERIMENT NO 1

Lab Title: Introduction to Structures


Student Name: Reg. No:

Objective:

LAB ASSESSMENT:

Excellent Good Average Satisfactory Unsatisfactory


Attributes
(5) (4) (3) (2) (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:


Excellent Good Average Satisfactory Unsatisfactory
Attributes
(5) (4) (3) (2) (1)

Data presentation

Experimental results

Conclusion

Total Marks: Obtained Marks:

Date: Signature:
EXPERIMENT NO 1
Introduction to Structures

Objectives:
 Familiarization with Structures in C++.
 Learning Difference between structural and functional programming

Equipment required:
 Desktop PCs
 Visual Studio/ Dev C++ on Windows

We often come around situations where we need to store a group of data whether of
similar data types or non-similar data types. We have seen Arrays in C++ which are used to
store set of data of similar data types at contiguous memory locations.
Unlike Arrays, Structures in C++ are user defined data types which are used to store group
of items of non-similar data types.

What is a structure?

A structure is a user-defined data type in C/C++. A structure creates a data type that can be
used to group items of possibly different types into a single type.

How to create a structure?

The ‘struct’ keyword is used to create a structure. The general syntax to create a structure is
as shown below:

struct structureName{
member1;
member2;
member3;
.
.
.
memberN;
};
Structures in C++ can contain two types of members:
 Data Memeber: These members are normal C++ variables. We can create a structure
with variables of different data types in C++.
 Member Functions: These members are normal C++ functions. Along with variables, we
can also include functions inside a structure declaration.

How to access structure elements?

struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here
};

Structure members are accessed using dot (.) operator.

#include <iostream>
using namespace std;

struct Point {
int x, y;
};

int main()
{
struct Point p1 = { 0, 1 };

// Accesing members of point p1


p1.x = 20;
cout << "x = " << p1.x << ", y = " << p1.y;

return 0;
}

LAB TASKS

Q1. Create a struct Rectangle where a rectangle is defined by Length & Width. Each
Rectangle has an
area and perimeter. You can also compare two rectangles with respect to the area.
Q2. Create a struct Student where attributes associated with each student are his name,
registration
number, father name, degree and department. One can view the details of any student and
can also
overwrite the details.

Q3. Create a struct complexNumber choose the attributes accordingly. Provide Following
functions
A function to take input for the attributes of complex number.
A function isZero to check if the complex number is 0? Function should return 1 if the
complex
number if zero and return 0 otherwise.
A function isGreaterThan (compare two complexNumber and return 1 if first complex
number is
greater than second)
A function Add that adds two complex numbers and return their sum as another complex
number.

Q4. Make a struct “Cylinder”. Choose appropriate attributes. The struct should include input
methods.
Class should be able to calculate:
Surface Area of Cylinder (formulaA = 2πr2 + 2πrh = 2πr(r + h))
Volume of cylinder (formula V = πr2h )
AIR UNIVERSITY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING

EXPERIMENT NO 2

Lab Title Introduction to Classes in C++


Student Name: Reg. No:

Objective:

LAB ASSESSMENT:

Excellent Good Average Satisfactory Unsatisfactory


Attributes
(5) (4) (3) (2) (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:


Excellent Good Average Satisfactory Unsatisfactory
Attributes
(5) (4) (3) (2) (1)

Data presentation

Experimental results

Conclusion

Total Marks: Obtained Marks:

Date: Signature:
EXPERIMENT NO 2

Introduction to Classes in C++

Objectives:
 To learn difference between structures and classes
 Implementing classes and understand data encapsulation in C++

Equipment required:

 Visual Studio/ Dev C++

Theory
The main purpose of C++ programming is to add object orientation to the C programming
language and classes are the central feature of C++ that supports object-oriented
programming and are often called user-defined types. A class is a user defined type that has
data and functions

Defining a Class

A class definition begins with the keyword class. The body of the class is contained
within a set of braces, { }; A class consists of its members. These members can be
either attributes or functions.

Figure 1: Class Body

Access specifiers

Visibility of attributes and functions in class are set within the body using access specifiers.
The keywords private: and public: specify the access level of the members of the class.
 Private: class members are only visible within a class body i.e. within public, private
member functions. These are not accessible outside the class body.
 Public: class members are visible both within and outside the class body.

Default access specifier is private. It is important to note that private members cannot be
accessed directly using direct member access operator (.). We will learn how private
members can be accessed.

Declaring objects of a class

A class provides the blueprints for objects, so basically an object is created from a class. We
declare objects of a class with exactly the same sort of declaration that we declare variables
of basic types. This is also called instantiation. You can have many variables of the same type
(class) but different names in same scope. Once an object of a certain class is instantiated, a
new memory location (separate for all objects) is created for it to store its data members
and code.
You can instantiate many objects from a class type. For example

 Foo c; // creating an object or declaring a variable of user defined data type


 Foo *a;// creating pointer to an object
 Foo b[100]; // creating array of objects

The public data members of objects of a class can be accessed using the direct member
access operator (.).Let us try the following example to make the things clear:

Calling member functions


int main()
{
Foo s1, s2; //instances
s1.setData(1066); s2.setData(1776); //calling public member functions using (.)
operator
s1.getData(); s2.getData(); return 0;
}

Private data members of class are not visible outside the class but they are visible within the
class. Thus to access private data members of class, public member functions are used due
to the reason of their visibility outside the class. Making the attributes private and hiding
them from the entire outer world helps in attaining one of the main objectives of Object
Oriented programming i.e. Encapsulation. Member functions that are used to access private
data members to set some value are called setters and member functions used to retrieve
value of private data members are called getters.
LAB TASKS

I. Create a class Rectangle keeping in mind that rectangle have length and width. One
should be able to calculate the perimeter () and the area() of the rectangle, can set a
value to length and width and retrieve the value of Length & width. Where

0 < length < 21


0 < width < 21
Area of Rectangle=length*width;
Perimeter of Rectangle=(length+width)*2;
TEST PLANS
Commands Output
Rectangle r;
r.set(2);
r.getLength();
r.set(50);
r.getLength();
Rectangle f=r;
f.set(-20);
f.getLength();

II. Create a class called account that might use to represent customers’ bank accounts.
Bank account should keep the record of customer’s account balance. Your class
should provide a constructor that receives an initial balance and uses it to initialize
data member. Account balance should be greater than or equal to zero. The class
should provide the feature credit to insert any amount to customers’ account. Debit
functionality should enable the user to withdraw the money from account (The
function should keep the check of the amount withdraw should not exceed the
current balance if it does generate an error message to the user indicating the
operation is not possible). Function getBlanceenables the user to check the amount
present in his account.

TEST PLANS
Commands Output
Account a;
a.Debit(90);
a.credit(150);
Account y(-50);
y.Debit(90);
y.credit(150);
y=a;
y.Debit(1000);
Account j=y;
j.Debit(-1000);
j.credit(24);
j=a;
a.credit(900);
j.debit(50);

III. Create a class called Rational for performing arithmetic with fractions. Write a
program to test your class. Use integer variables to represent the private data of the
class— the numerator and the denominator. Provide a constructor that enables an
object of this class to be initialized when it’s declared. The constructor should
contain default values in case no initializers are provided and should store the
fraction in reduced form. For example, the fraction would be stored in the object as
1 in the numerator and 2 in the denominator. Provide public member functions that
perform each of the following tasks:
 Adding two Rational numbers. The result should be stored in reduced form.
 Subtracting two Rational numbers. The result should be stored in reduced form.
 Multiplying two Rational numbers. The result should be stored in reduced form.
 Dividing two Rational numbers. The result should be stored in reduced form.
 Printing Rational numbers in the form a/b, where ‘a’is the numerator and b is
the denominator.
 Printing Rational numbers in floating-point format.

Commands Output
Rational a;
Rational b;
a.setvalue(7,8);
b.setvalue(6,5);
a.add(b);
Rational c;
c.setvalue(-5,7);
c.multiply(b);
c=a;
c.print();
Rational j=b;
a=b.divide(c);
Rational d;
d.setvalue(-5,0);
c.multiply(d);
THINK

i.Why is it appropriate to set the attributes always private and member functions public?
ii.Why default constructors are needed to over write.
iii.Why is it good to make attribute private and access them using setters?
iv.Can we make member functions private?
v.Can we set constructors private?

AIR UNIVERSITY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING

EXPERIMENT NO 3

Lab Title: Destructors, Parameterized Constructors and Copy Constructors


Student Name: Reg. No:

Objective:

LAB ASSESSMENT:

Excellent Good Average Satisfactory Unsatisfactory


Attributes
(5) (4) (3) (2) (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:


Excellent Good Average Satisfactory Unsatisfactory
Attributes
(5) (4) (3) (2) (1)

Data presentation

Experimental results

Conclusion

Total Marks: Obtained Marks:

Date: Signature:

EXPERIMENT NO 3
Destructors, Parameterized Constructors and Copy Constructors

Objectives:
 To learn types of constructors in classes their use and syntax
 Understand difference between Shallow and Deep Copy

Equipment required:

 Visual Studio/Dev C++

Introduction of dynamic memory in the attributes of class results in the use of destructors
and copy constructors to avoid crashing programs and run time errors.
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(intval) {data=val} // public member functions

intgetData() {return data;}


};

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

When an object is instantiated using default constructor its attributes are not initialized to
some desired value. This is done later by calling setters. 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{ void main()
Private: {
intval; MyClass c; // call to default constructor
Public: MyClass c2(2); // call to
MyClass(int i){val=i;}; parameterizedconstructor
MyClass(){val=0;}}; }

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:
intval;
Public:
MyClass(int i):val(i){};
};

Copy Constructor

The copy constructor is called whenever an object is initialized from another object of the
same type, which includes

 Initialization, T a = b; or T a(b);, where b is of type T


 Function argument passing: f(a);, where a is of type T and f is void f(T t)
 Function return: return a; inside a function such as T f(), where a is of type T, which
has no move constructor.

Like default constructor C++ also provides a default copy constructor which can be
overwritten as a public member function of class by the class designer if required. In many
cases, default copy constructor is sufficient. However, there are certain circumstances
where the member-wise copy version is not good enough. By far, the most common reason
the default copy constructor is not sufficient is because the object contains pointers and you
need to take a "deep" copy of the pointer. That is, you don't want to copy the pointer itself;
rather you want to copy what the pointer points to. Why do you need to take "deep"
copies? This is typically because the instance owns the pointer; that is, the instance is
responsible for calling delete on the pointer at some point (probably the destructor). If two
objects end up calling delete on the same non-NULL pointer, heap corruption results. Copy
constructor has the following signature
MyClass(constMyClass& other );
Myclass indicates class name, an argument of the same user defined data type is passed
which is to be copied. Argument is passed by reference to avoid the recursive call to copy
constructor. Key word const saves the argument from being changed anywhere within the
copy constructor accidently. When we write
MyClass g;
MyClassobj=g; // call is generated by compiler to the copy constructor
obj.MyClass(g)

LAB TASKS

I. Create a class POINT to represent a point in Cartesian coordinate system Choose


appropriate data members. Provide member functions:
 Default constructor
 Parameterized constructor
 Input
 Output
 Distance( returns the distance between two POINT objects,
the function takes one object as an input)
 isZero(determines if a point is the center)
 Midlepoint(returns the middle point , takes one object as an
input and returns the answer in a POINT object)
 isEqualTo (compare two POINTs)
 isGreaterThan (compares two POINT in terms of the distance from the center )
o Above two function takes one POINT object as an argument and returns true
if the condition is satisfied and false otherwise

TEST PLAN

Commands Output
Point g;
g.setx(-2);
g.isZero();
g.gety();
g.MiddlePoint();
g.isEqualTo(g);
Point r(9,8.5);
r.isGeaterThan(g);
Point j=g;
g.isEqualTo(r);
g.isEqualTo(j);
Point f(-6.7,-9.5);
f.setx(5.5)
f.Distance(r);
g.Distance(f);
g.Distance(r);

II. 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();

III. Create a class called Invoice that a hardware store might use to represent an invoice
for an item sold at the store. An Invoice should include four data members—a part
number (type string), a part description (type string), a quantity of the item being
purchased (type int) and a price per item (type int). Your class should have a
constructor that initializes the four data members. A constructor that receives
multiple arguments is defined with the form:

ClassName( TypeName1 parameterName1, TypeName2 parameterName2, ... )

Provide a set and a get function for each data member. In addition, provide a
member function named getInvoiceAmount that calculates the invoice amount (i.e.,
multiplies the quantity by the price per item), then returns the amount as an int
value. If the quantity is not positive, it should be set to 0. If the price per item is not
positive, it should be set to 0. Write a test program that demonstrates class Invoice’s
capabilities.

IV. Create a class name copy_concatenate that take char* as data member and
concatenate the given string with existing one. Provide following functions:
 copy_concatenate(const char *str)
 copy_concatenate(const copy_concatenate &)
 void concatenate(const char *)
 ~copy_concatenate()
 Void display()

TEST PLAN

Commands Output
Invoice y;
y.setpartnumber(“hw5678”);
v.setpartname(“Wire cripper”);
y.setQuantity(10);
v.priceperitem(70);
v.getInvoiceAmount();
Invoice f(“hw7890”,”screw driver”,2,100);
Invoice t=r;
r.getInvoiceAmount();
Invoice m;
m.getInvoiceAmount();

THINK
i. Why do we need to overwrite destructors in our class?
ii. Why is copy constructor needed?
iii. SavingAccount g=v; results in call of which constructor? Write the implicit calls
needed.
iv. Why copy constructor receives a constant object of same class as an argument.
AIR UNIVERSITY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING

EXPERIMENT NO 4

Lab Title: Friend Classes and Friend Functions

Student Name: Reg. No:

Objective:

LAB ASSESSMENT:

Excellent Good Average Satisfactory Unsatisfactory


Attributes
(5) (4) (3) (2) (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:


Excellent Good Average Satisfactory Unsatisfactory
Attributes
(5) (4) (3) (2) (1)

Data presentation

Experimental results

Conclusion

Total Marks: Obtained Marks:

Date: Signature:
EXPERIMENT NO 4

Friend Classes and Friend Functions

Objectives:
 To understand the concept of making classes and functions friend to other classes
for data sharing

Equipment required:
 Visual Studio/Dev C++

Description:

Friendship helps in accessing the private data members of class. Thus it enables a class to
grant the access to any other class without inheriting that class. If two classes do not fulfill
“is-a” relationship and are required to access the private member function of any class it is
declared as friend class of that class. Friend functions are also meant for the same purpose.
Friend classes

All member functions of a class become friends of the friendship-granting class. Friendship-
granting class allows the other class to access all the private, protected, public members
directly using (.) operator with Friendship-granting class object.

Friend Class Example


class alpha {
int data;
public:
alpha(): data(99){}
friend class beta; // granting
friendship
};
class beta {
public:
void func1(alpha a) {cout<<a.data;}
void func2(alpha a) {cout<<a.data;}
};

Friendship-grant is not commutative. It is not dual side relationship until or unless declared
in both the classes separately
LAB TASK

I. Define a TV class representing a television and a Remote class representing a remote


control. You can represent a television with a set of state members—that is,
variables that describe various aspects of the television. Here are some of the
possible states:

• On/off
•Channel setting
•Volume setting
•Cable or antenna tuning mode
• TV input (TV or AV)
The input selection chooses between TV,
which could be either cable or
broadcast TV, and a VCR. Some sets may
offer more choices, such as multiple
VCR/DVD inputs, but this list is enough for the purposes of this example. Also, a
television has some parameters that aren’t state variables. For example, televisions
vary in the number of channels they can receive, and you can include a member to
track that value. i.e. Max Channels and Max volume. Viewer can also be able to see
the following settings if TV is on
“Volume setting = “
“Channel setting = “
“Mode = “
“Input = “
Next, you must provide the class with methods for altering the settings. Many
televisions these days hide their controls behind panels, but it’s still possible with
most televisions to change channels, and so on, without a remote control. However,
often you can go up or down one channel at a time but can’t select a channel at
random. Similarly, there’s usually a button for increasing the volume and one for
decreasing the volume.
A remote control should duplicate the controls built in to the television. A single
remote of a company control can control several televisions of the same company.
Many of its methods can be implemented by using TV methods. In addition, a
remote control typically provides random access channel selection. That is, you can
go directly from channel 2 to channel 20 without going through all the intervening
channels. Also, many remotes can work in two modes—as a television controller
and as a VCR controller.

TEST PLAN

Commands Output
Television t;
Remote r;
r.setChannel(t,25);
r.VolumeUp();
r.VolumeDown();
r.viewSettings(t);
r.setMode(t);
Television g=t;
r.setChannel(g,1);
r.channelDown();
r.channelDown();
r.viewSettings(g);

II. Write a program to find Maximum out of two numbers using friend function. Here
one member is of one class and second belongs to another class.

III. Write a program to swap the values of private data members of classes names
class_1 and class_2 using friend keyword

IV. Create two classes DM and DB which stores the value in distances. DM stores
distance in meters and centimeters and DB in feet and inches. Write a program that
can read values for the class objects and add one object of DM with another object
of DB. Use a friend function to carry out the addition operation. The object that
stores the results may be a DM object or DB object, depending on the units in which
the results are required. The display should be in the format of feet and inches or
meters and centimeters depending on the object on display.

THINK

i. Why friendship is needed?


ii. Inheritance vs. friends, what do you prefer? Justify?
iii. Why do we make friend functions?
iv. Are friend functions parts of a class?
v. Does friendship effects the privacy of class?
AIR UNIVERSITY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING

EXPERIMENT NO 5

Lab Title: Operator Overloading

Student Name: Reg. No:

Objective:

LAB ASSESSMENT:

Excellent Good Average Satisfactory Unsatisfactory


Attributes
(5) (4) (3) (2) (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:


Excellent Good Average Satisfactory Unsatisfactory
Attributes
(5) (4) (3) (2) (1)

Data presentation

Experimental results

Conclusion

Total Marks: Obtained Marks:


Date: Signature:

EXPERIMENT NO 5

Operator Overloading

Objectives
 To understand concept of operator overloading
 Implement operator overloading to use operators for user defined data types

Equipment required

 Visual Studio/ Dev C++

Description:

In C++ the overloading principle applies not only to functions, but to operators too. That is,
of operators can be extended to work not just with built-in types but also classes. A
programmer can provide his or her own operator to a class by overloading the built-in
operator to perform some specific computation when the operator is used on objects of
that class. The following set of operators is commonly overloaded for user-defined classes:

 = (assignment operator)
 + - * (binary arithmetic operators)
 += -= *= (compound assignment operators)
 == != (comparison operators)

Operator overloading is a clear representation of operations performed, and is used


because it allows the developer to program using notation closer to the target domain and
allows user-defined types a similar level of syntactic support as types built into the
language, for example, consider variables a, b, c of some user-defined type, such as
matrices:
a+b*c
In a language that supports operator overloading, and with the usual assumption that the '*'
operator has higher precedence than '+' operator, this is a concise way of writing:
add (a, multiply (b,c))
You cannot create new operators like *& and try to overload them; only existing operators
can be overloaded. The precedence of an operator cannot be changed by overloading. The
associativity (i.e. left-to-right or right-to-left) of an operator cannot be changed. The arity
(i.e. no. of operands) of an operator cannot be changed. The meaning of how an operator
works on built-in types cannot be changed. Operator overloading works only on objects of
user defined types or with a mixture of user-defined and built-in types.

Operator Overloading example


class complex { void main() {
int real, imag; complex c1, c2(1,2), c3, c4;
public: c1.setdata();
complex(): real(0), imag(0) {} c3=c1+c2; //same as c1.operator + (c2)
complex(int re, intim): real(re), imag(im) { } c4 = c1+c2+ c3; //note cascading
complex operator + (complex c) { c4. showdata();
int re2=real + c.real; }
//note: we aim not to change the operands
int im2=imag+c.imag;
return complex(re2, im2);}
};

LAB TASK

1. Write a C++ program to overload unary operators that is increment and decrement.

2. Write a C++ program to overload binary operator '+' to add two complex numbers.

3. Create a class Time which contains:

- Hours
- Minutes
- Seconds
Write a C++ program using operator overloading for the following:
1. = = : To check whether two Time are same or not.
2. >> : To accept the time.
3. << : To display the time.
4. Develop class Polynomial. The internal representation of a Polynomial is an array of
terms. Each term contains a coefficient and an exponent. The term 2x 4 has the
coefficient 2 and the exponent 4. The index number of an array represents the
exponent.

· Develop a complete class containing proper constructor and destructor functions as


well as set and get functions.
· The class should also provide the following overloaded operator capabilities:

o Overload the addition operator (+) to add two Polynomials.

o Overload the subtraction operator (-) to subtract two Polynomials.

o Overload the equal operator (==) to compare two Polynomials.

o Overload the assignment operator to assign one Polynomial to another.

o Overload the multiplication operator (*) to multiply two Polynomials.

o Overload the addition assignment operator (+=), subtraction assignment operator (-=),
and multiplication assignment operator (*=).

5. Make a Class Named Vector3D that represents a vector in 3D and it contains


following Private data members I, J and K (of type double), with default values of 0.

Make a three argument constructor


Make get_value() and set_value() and print() function
Make Operator Overloading of + operator to add two 3D vectors
Make Operator Overloading of - operator to subtract two 3D vectors.
Make Operator Overloading of * operator to take dot product of two 3D vectors.
Make Operator Overloading of ^ operator to take cross product of two 3D vectors.
Make Operator Overloading of +=, -=, *= and ^= operators
Make a get_leng() to return length of a 3D Vector
AIR UNIVERSITY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING

EXPERIMENT NO 6

Lab Title: Inheritance

Student Name: Reg. No:

Objective:

LAB ASSESSMENT:

Excellent Good Average Satisfactory Unsatisfactory


Attributes
(5) (4) (3) (2) (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:


Excellent Good Average Satisfactory Unsatisfactory
Attributes
(5) (4) (3) (2) (1)

Data presentation

Experimental results

Conclusion

Total Marks: Obtained Marks:


Date: Signature:

EXPERIMENT NO 6

Inheritance

Objective:

 To understand oop concept of inheritance between classes

Equipment Required:

 Visual Studio/ Dev C++

Description:

Inheritance enables reusability and helps in enhancing the functionality of any class.
Inheritance is one of the major pillars of Object Oriented programming and aids in code
maintainability and avoids redundancy.
Inheritance

Inheritance is a form of software reuse in which you create a class that absorbs an existing
class’s data and behavior and enhances them with new capabilities.Ininheritance, a class
derives the behavior and structure of another (existing) class.

 Advantages
o Saves time
o Reuse of proven, debugged, high quality software
Figure 1: Derived & Base class relationship
Data members in the base class are part of the derived class. Behaviors defined in the base
class are part of the derived class. Note that private aspects of the base class are part of the
child, but are not (directly) accessible within the derived class.
classDerivedClass : kind BaseClass
Where kind is one of public, private or protected.

1. Order of Constructors & Destructors

When a program creates a derived-class object, the derived-class constructor immediately


calls the base-class constructor; the base-class constructor’s body executes, then the
derived-class’s member initializers execute and finally the derived-class constructor’s body
executes. This process cascades up the hierarchy if it contains more than two levels.
When a derived-class object is destroyed, the program calls that object’s destructor. This
begins a chain (cascade) of destructor calls in which the derived-class destructor and the
base destructors execute in reverse of the order in which the constructors executed.

LAB TASK
i. Create an inheritance hierarchy that a bank might use to represent customers'
bank accounts. All customers each having an account no. at this bank can deposit
(i.e., credit) money into their accounts and withdraw (i.e., debit) money from
their accounts. More specific types of accounts also exist. CreditCardAccount, for
instance, provide the user the facility to make money transactions using ATM the
money they hold. Checking accounts, on the other hand, charge a fee per
transaction (i.e., credit or debit).
Create an inheritance hierarchy containing base class Account and derived
classes CreditCardAccount and CheckingAccount that inherit from class Account.
Base class Account should include one data member of type double to represent
the account balance. Customer’s name and account no.

The account no. should be unique and assigned in the order in which instances are
created The class should provide a constructor that receives an initial balance and
uses it to initialize the data member. The constructor should validate the initial
balance to ensure that it is greater than or equal to 0.0. If not, the balance should be
set to 0.0 and the constructor should display an error message, indicating that the
initial balance was invalid.The class should provide following member functions.

 Member function credit should add an amount to the current balance.

 Member function debit should withdraw money from the Account and
ensure that the debit amount does not exceed the Account's balance. If it
does, the balance should be left unchanged and the function should print the
message "Debit amount exceeded account balance.

 Member function getBalance should return the current balance.

 Member function getAccountNo.

• Derived class CreditCardAccount should inherit the functionality of an Account, but


also include a data memberpinnumberset by the customer.

 Constructor should receive the initial balance, as well as pin number.

 It should provide a public member function resetpin

• Derived class CheckingAccount should inherit from base class Account and include
an additional data member of type double that represents the fee charged per
transaction to all the customers.

 CheckingAccount's constructor should receive the initial balance, as well as a


parameter indicating a fee amount.

 Class CheckingAccount should redefine member functions credit and debit so


that they subtract the fee from the account balance whenever either
transaction is performed successfully. CheckingAccount's versions of these
functions should invoke the base-class Account version to perform the
updates to an account balance. CheckingAccount's debit function should
charge a fee only if money is actually withdrawn (i.e., the debit amount does
not exceed the account balance). After defining the classes in this hierarchy,
write a program that creates objects of each class and tests their member
functions.

Note: In all the classes make the member functions & data members const ,static
where required.

ii. Create two classes named Mammals and MarineAnimals. Create another class
named BlueWhale which inherits both the above classes. Now, create a function
in each of these classes which prints "I am mammal", "I am a marine animal" and
"I belong to both the categories: Mammals as well as Marine Animals"
respectively. Now, create an object for each of the above class and try calling
1 - function of Mammals by the object of Mammal
2 - function of MarineAnimal by the object of MarineAnimal
3 - function of BlueWhale by the object of BlueWhale
4 - function of each of its parent by the object of BlueWhale
AIR UNIVERSITY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING

EXPERIMENT NO 07

Lab Title: Multiple Inheritance

Student Name: Reg. No:

Objective:

LAB ASSESSMENT:

Excellent Good Average Satisfactory Unsatisfactory


Attributes
(5) (4) (3) (2) (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:


Excellent Good Average Satisfactory Unsatisfactory
Attributes
(5) (4) (3) (2) (1)

Data presentation

Experimental results

Conclusion

Total Marks: Obtained Marks:

Date: Signature:
EXPERIMENT NO 7

Multiple Inheritance

Objectives
 To learn what is Multiple Inheritance
 Understand and solve the diamond problem due to Multiple Inheritance

Equipment required:
 Visual Studio/ Dev C++

Description

Inheritance is the process of inheriting properties of objects of one class by objects of


another class. The class which inherits the properties of another class is called Derived or
Child or Sub class and the class whose properties are inherited is called Base or Parent or
Super class. When a class is derived from two or more base classes, such inheritance is
called Multiple Inheritance. It allow us to combine the features of several existing classes
into a single class.

For example,
 Petrol is derived from both liquid and fuel.

 A child has character of both his/her father and mother, etc

Syntax of Multiple Inheritance

class base_class1

properties;
methods;

};

class base_class2

properties;

methods;

};

... ... ...

... ... ...

class base_classN

properties;

methods;

};

class derived_classname : visibility_mode base_class1, visibility_mode base_class2,...


,visibility_mode base_classN

{
properties;

methods;

};

The diamond problem

The diamond problem occurs when two superclasses of a class have a common base class.
For example, in the following diagram, the TA class gets two copies of all attributes of
Person class, this causes ambiguities.
LAB TASK

1. Implement the Example of TA class shown above in figure using multiple


inheritance with and without diamond problem and notice the difference among
two.
AIR UNIVERSITY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING

EXPERIMENT NO 8

Lab Title: Polymorphism

Student Name: Reg. No:

Objective:

LAB ASSESSMENT:

Excellent Good Average Satisfactory Unsatisfactory


Attributes
(5) (4) (3) (2) (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:


Excellent Good Average Satisfactory Unsatisfactory
Attributes
(5) (4) (3) (2) (1)

Data presentation

Experimental results

Conclusion

Total Marks: Obtained Marks:


Date: Signature:

EXPERIMENT NO 8

Polymorphism

Objectives
 To understand and implement the core concept of Polymorphism in OOP classes
Equipment required

 Visual Studio/Dev C++

Description

To make a program more dynamic polymorphism is used. It helps in dynamic binding and
helps in achieving real time decisions based on user selection. Polymorphism if often used
as it also support inheritance and makes a code to follow a proper hierarchy thus helps in
code portability and maintainability.

1. Static binding

Function choice is based on type of variable making the call

2. Dynamic binding

Function choice is based on the type of the data in the variable making the call.
Person *p = new Student();
p->print();
Here static binding will choose Person::print() because the pointer variable is of type
PersonBut dynamic binding will choose Student::print() because p is actually pointing to a
Student type object.Suppose we have the following inheritance hierarchy

class Shape { class Circle: public Shape{ class Rectangle:public Shape{

}; void draw() const; void draw() const;

}; };

Suppose we declared an array of shapes like this

Static binding
Shape* shapeList[3];
shapeList[0] = new Circle(...); // Upcast to Shape*
shapeList[1] = new Square(...);// Upcast to Shape*
shapeList[2] = new Rectangle(...); // Upcast to
Shape*
for(int i=0; i<numShapes; i++)
shapeList[i]->draw();

Even though we created a Circle object, a Rectangle object, and a Square object,
drawShapes only sees them as generic Shape (base class) objects so Shape::draw() keeps
getting called throughout the loop because default behavior of C++ is static binding If we
want dynamic binding, we must use virtual functions.
If you had declared draw() function to be virtual throughout in the example above, we
would have got dynamic behavior. When you call a virtual function, the system will check
the dynamic type of the object before choosing which function to call to declare a function
to be a virtual function, you simply use the virtual keyword when declaring the function in
the class. For example, we could declare our Shape, Circle, and Rectangle classes as follows

class Shape { class Circle:public Shape{ class Rectangle:public Shape{

... ... ...

virtual void draw() const; virtual void draw() const; virtual void draw() const;

... ... ...

}; }; };

Now we get the dynamic behavior we want; this is called polymorphism

Polymorphism Example 1: Polymorphism Example 2:


Shape* shapeList[maxShapes]; Shape * sptr;
shapeList[0] = new Circle(...); // Upcast to Shape* sptr= new Rectangle();
shapeList[1] = new Square(...); // Upcast to sptr->Size(); //Rectangle’s
Shape* Size
shapeList[2] = new Rectangle(...); // Upcast to sptr=new Circle();
Shape* sptr->Size(); //Circle’s Size
shapeList[0]->draw(); // Calls Circle::draw() // Notice the same call being used for
shapeList[1]->draw(); // Calls Square::draw() different functionalities
shapeList[2]->draw(); // Calls Rectangle::draw() // Important: the function Size() has
to be virtual in the base class
Figure: Polymorphism
In the base class, create a virtual function Size(). In the derived classes also, create
appropriate definitions of Size(), Create a base class pointer (e.g. Shape * sptr). During
execution, if sptr points to a Rectangle type object, then call to Size() will execute
Rectangle’s version of Size() and if sptr points to a Circle type object, then call to Size() will
execute Circle()’s version of Size().

LAB TASK

I. All the shapes share some features for example each have some area and perimeter.
Every shape has dimensions. Shapes can be further divided into 2D and 3D shapes.
Area is the property of 2D Shapes and volume is the additional property of 3D
Shapes. Square and circle are two derived classes of 2D Shapes. Cube and sphere are
the 3D shapes. Let us assume that only 2D shapes can be painted and the paint cost
depends on area and can be calculated if cost/unit area is provided. Provide a design
in OOP of the scenario discussed above and exercise polymorphism in main by
creating 10 pointers to object array. Make virtual functions where required

2D Shapes Area Perimeter/


Circumference

a2 4a

r2 2r

3D Shapes Surface Area Volume

6a2 a3
4r2 4/3 r3

TEST PLAN

Commands Output
Shape * s[100];
s[0]=new Shape();
S[0]=new circle();
S[0].calcPaintCost();
S[0].getArea();
S[1]=new Sphere();
S[1].getVolume();
S[1]=new twoD();
S[2]=new cube();
S[2].getArea();
S[3]=new shape();
S[3].getVolume();
S[4]=new threeD();
S[4].getVolume();
S[4]=new Square();

AIR UNIVERSITY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING

EXPERIMENT NO 9

Lab Title: STL in C++


Student Name: Reg. No:

Objective:
LAB ASSESSMENT:

Excellent Good Average Satisfactory Unsatisfactory


Attributes
(5) (4) (3) (2) (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:


Excellent Good Average Satisfactory Unsatisfactory
Attributes
(5) (4) (3) (2) (1)

Data presentation

Experimental results

Conclusion

Total Marks: Obtained Marks:


Date: Signature:

EXPERIMENT NO 9

STL in C++

Objectives:
 To learn what are template classes and implement templates in C++
Equipment required:
 Visual Studio/ Dev C++

Description:

STLs are a Software reuse. Data structures and algorithms commonly used by C++
programmers and are Part of C++ Standard Library.
1. Key Components of STL
 Iterators i.e. Generalization of the pointer concept
 Point to elements in a container
 Connect algorithm with container

Figure: Key Components of STL


1. Basic Sequence Containers
 Ordinary C++ array (not part of STL) Fixed size, Quick random access (by index
number), Slow to insert/delete in the middle, Size cannot be changed at runtime
 Vector expandable array, Quick random access (by index number), Slow to
insert/delete in the middle, Quick to insert/delete at end
 ListDoubly linked list,Quick to insert/delete at any location, Quick access to both
ends, Slow random access
 DequeLike vector, but can be accessed at either end, Quick random access (by index
number), Slow to insert/delete in the middleQuick insert/delete at either the
beginning or the end.

Instantiating (i.e. Creating) an STL Container


// include appropriate header Then use the template format with the kind of
// objects to be stored as the parameter
vector <int>aVect; //create a vector of int
list <airtime>departure_list; //create a list of airtime objectsno need to specify
size of containers

Lab Tasks

I. Create template function display that displays all the items of the list.
II. Use STL to implement stack and queue

Some basic functions associated with Map:

begin() – Returns an iterator to the first element in the map


end() – Returns an iterator to the theoretical element that follows last element in the map
size() – Returns the number of elements in the map
max_size() – Returns the maximum number of elements that the map can hold
empty() – Returns whether the map is empty
pair insert(keyvalue, mapvalue) – Adds a new element to the map
erase(iterator position) – Removes the element at the position pointed by the iterator
erase(const g)– Removes the key value ‘g’ from the map
clear() – Removes all the elements from the map

Functions used with List:

 front() – Returns the value of the first element in the list.


 back() – Returns the value of the last element in the list .
 push_front(g) – Adds a new element ‘g’ at the beginning of the list .
 push_back(g) – Adds a new element ‘g’ at the end of the list.
 pop_front() – Removes the first element of the list, and reduces size of the list by 1.
 pop_back() – Removes the last element of the list, and reduces size of the list by 1
 list::begin() and list::end() in C++ STL– begin() function returns an iterator pointing to
the first element of the list
 end()– end() function returns an iterator pointing to the theoretical last element which
follows the last element.
 list rbegin() and rend() function in C++ STL– rbegin() returns a reverse iterator which
points to the last element of the list. rend() returns a reverse iterator which points to
the position before the beginning of the list.
 list cbegin() and cend() function in C++ STL– cbegin() returns a constant random access
iterator which points to the beginning of the list. cend() returns a constant random
access iterator which points to the end of the list.
 list crbegin() and crend() function in C++ STL– crbegin() returns a constant reverse
iterator which points to the last element of the list i.e reversed beginning of
container. crend() returns a constant reverse iterator which points to the theoretical
element preceding the first element in the list i.e. the reverse end of the list.
 empty() – Returns whether the list is empty(1) or not(0).
 insert() – Inserts new elements in the list before the element at a specified position.
 erase() – Removes a single element or a range of elements from the list.
 assign() – Assigns new elements to list by replacing current elements and resizes the
list.
 remove() – Removes all the elements from the list, which are equal to given element.
 list::remove_if() in C++ STL– Used to remove all the values from the list that
correspond true to the predicate or condition given as parameter to the function.
 reverse() – Reverses the list.
 size() – Returns the number of elements in the list.
 list resize()function in C++ STL– Used to resize a list container.
 sort() – Sorts the list in increasing order.
 list max_size() function in C++ STL– Returns the maximum number of elements a list
container can hold.
 list unique() in C++ STL– Removes all duplicate consecutive elements from the list.
 list::emplace_front() and list::emplace_back() in C++ STL– emplace_front() function is
used to insert a new element into the list container, the new element is added to the
beginning of the list. emplace_back() function is used to insert a new element into the
list container, the new element is added to the end of the list.
 list::clear() in C++ STL– clear() function is used to remove all the elements of the list
container, thus making it size 0.
 list::operator= in C++ STL– This operator is used to assign new contents to the
container by replacing the existing contents.
 list::swap() in C++ STL– This function is used to swap the contents of one list with
another list of same type and size.
 list splice() function in C++ STL– Used to transfer elements from one list to another.
 list merge() function in C++ STL– Merges two sorted lists into one
 list emplace() function in C++ STL– Extends list by inserting new element at a given
position.
The functions supported by queue are :
1. empty() – Returns whether the queue is empty.
2. size() – Returns the size of the queue.
3. queue::swap() in C++ STL: Exchange the contents of two queues but the queues must
be of same type, although sizes may differ.
4. queue::emplace() in C++ STL: Insert a new element into the queue container, the new
element is added to the end of the queue.
5. queue::front() and queue::back() in C++ STL– front() function returns a reference to
the first element of the queue. back() function returns a reference to the last element
of the queue.
6. push(g) and pop() – push() function adds the element ‘g’ at the end of the
queue. pop() function deletes the first element of the queue.

The functions associated with stack are:

empty() – Returns whether the stack is empty – Time Complexity : O(1)


size() – Returns the size of the stack – Time Complexity : O(1)
top() – Returns a reference to the top most element of the stack – Time Complexity : O(1)
push(g) – Adds the element ‘g’ at the top of the stack – Time Complexity : O(1)
pop() – Deletes the top most element of the stack – Time Complexity : O(1)

AIR UNIVERSITY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING

EXPERIMENT NO 10
Lab Title: Smart Pointers and Exceptions in C++
Student Name: Reg. No:

Objective:

LAB ASSESSMENT:

Excellent Good Average Satisfactory Unsatisfactory


Attributes
(5) (4) (3) (2) (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:


Excellent Good Average Satisfactory Unsatisfactory
Attributes
(5) (4) (3) (2) (1)

Data presentation

Experimental results

Conclusion

Total Marks: Obtained Marks:


Date: Signature:

EXPERIMENT NO 10

Smart Pointers and Exceptions in C++

Objective:
 To learn what are smart pointers and handling of exceptions in C++

Equipment Required
 Visual Studio/Dev C++

Smart Pointers:
Consider the following simple C++ code with normal pointers.
MyClass *ptr = new MyClass();
ptr->doSomething();
// We must do delete(ptr) to avoid memory leak

Using smart pointers, we can make pointers to work in way that we don’t need to explicitly
call delete. Smart pointer is a wrapper class over a pointer with operator like * and ->
overloaded. The objects of smart pointer class look like pointer, but can do many things that
a normal pointer can’t like automatic destruction (yes, we don’t have to explicitly use
delete), reference counting and more.
The idea is to make a class with a pointer, destructor and overloaded operators like * and ->.
Since destructor is automatically called when an object goes out of scope, the dynamically
allocated memory would automatically deleted (or reference count can be decremented).
Consider the following simple smartPtr class.

Example:

class SmartPtr
{
int *ptr; // Actual pointer
public:

SmartPtr(int *p = NULL) { ptr = p; }

// Destructor
~SmartPtr() { delete(ptr); }

// Overloading dereferencing operator


int &operator *() { return *ptr; }
};

int main()
{
SmartPtr ptr(new int());
*ptr = 20;
cout << *ptr;

// We don't need to call delete ptr: when the object


// ptr goes out of scope, destructor for it is automatically
// called and destructor does delete ptr.

return 0;
}

Exception Handling:

Errors can be broadly categorized into two types. We will discuss them one by one.

1. Compile Time Errors


2. Run Time Errors

Compile Time Errors – Errors caught during compiled time is called Compile time errors.
Compile time errors include library reference, syntax error or incorrect class import.
Run Time Errors - They are also known as exceptions. An exception caught during run time
creates serious issues.
Errors hinder normal execution of program. Exception handling is the process of handling
errors and exceptions in such a way that they do not hinder normal execution of the system.
For example, User divides a number by zero, this will compile successfully but an exception
or run time error will occur due to which our applications will be crashed. In order to avoid
this we'll introduce exception handling technics in our code.
In C++, Error handling is done using three keywords:

 try
 catch
 throw
Syntax:
try
{
//code
throw parameter;
}
catch(exceptionname ex)
{
//code to handle exception
}

try block

The code which can throw any exception is kept inside(or enclosed in) atry block. Then,
when the code will lead to any error, that error/exception will get caught inside
the catch block.

catch block

catch block is intended to catch the error and handle the exception condition. We can have
multiple catch blocks to handle different types of exception and perform different actions
when the exceptions occur. For example, we can display descriptive messages to explain
why any particular excpetion occured.

throw statement

It is used to throw exceptions to exception handler i.e. it is used to communicate


information about error. A throw expression accepts one parameter and that parameter is
passed to handler.
throw statement is used when we explicitly want an exception to occur, then we can
use throw statement to throw or generate that exception.
set_terminate( )

#include <exception>
#include <iostream>
#include <cstdlib>
using namespace std;

void terminator() {
cout << "I'll be back!" << endl;
exit(0);
}

void (*old_terminate)()
= set_terminate(terminator);

class Botch {
public:
class Fruit {};
void f() {
cout << "Botch::f()" << endl;
throw Fruit();
}
~Botch() { throw 'c'; }
};

int main() {
try{
Botch b;
b.f();
} catch(...) {
cout << "inside catch(...)" << endl;
}
} ///:~

You can install your own terminate( ) function using the standard set_terminate( ) function,
which returns a pointer to the terminate( ) function you are replacing, so you can restore it
later if you want. Your custom terminate( ) must take no arguments and have a void return
value. In addition, any terminate( ) handler you install must not return or throw an
exception, but instead must call some sort of program-termination function.
If terminate( ) is called, it means the problem is unrecoverable.

Like unexpected( ), the terminate( ) function pointer should never be null.

old_terminate looks a bit confusing at first: It not only creates a pointer to a function, but it
initializes that pointer to the return value of set_terminate( ). Even though you may be
familiar with seeing a semicolon right after a pointer-to-function definition, it’s just another
kind of variable and may be initialized when it is defined.
The class Botch not only throws an exception inside f( ), but also in its destructor. This is one
of the situations that causes a call to terminate( ), as you can see in main( ). Even though
the exception handler says catch(...), which would seem to catch everything and leave no
cause for terminate( ) to be called, terminate( ) is called anyway, because in the process of
cleaning up the objects on the stack to handle one exception, the Botch destructor is called,
and that generates a second exception, forcing a call to terminate( ). Thus, a destructor that
throws an exception or causes one to be thrown is a design error.

LAB TASKS:

1. Implement the example of Smart Pointer done in class with * and -> operator
overloading included into the ptr class.

2. Write a C++ code and use exception handling to handle a division by zero.

3. Write a C++ code in which if a value in array is greater than 2 int exception is thrown
else char exception is thrown

4. Implement and run the set_terminate() example above and see how it works?

5. . Prove to yourself that if you create an exception object on the heap and throw the
pointer to that object, it will not be cleaned up.
AIR UNIVERSITY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING

EXPERIMENT NO 11

Lab Title: Unified Modelling Language


Student Name: Reg. No:

Objective:

LAB ASSESSMENT:

Excellent Good Average Satisfactory Unsatisfactory


Attributes
(5) (4) (3) (2) (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:


Excellent Good Average Satisfactory Unsatisfactory
Attributes
(5) (4) (3) (2) (1)

Data presentation

Experimental results

Conclusion

Total Marks: Obtained Marks:


Date: Signature:

EXPERIMENT NO 11

Unified Modelling Language

Objectives:
 To learn converting C++ code into UML diagrams and vice versa

Equipment’s required:
 Visio 2010

Use Case Diagram:


In the Unified Modeling Language (UML), a use case diagram can summarize the details of your
system's users (also known as actors) and their interactions with the system. To build one, you'll use
a set of specialized symbols and connectors. An effective use case diagram can help your team
discuss and represent:

Scenarios in which your system or application interacts with people, organizations, or external
systems

Goals that your system or application helps those entities (known as actors) achieve

The scope of your system

Association:

Generalization:
Class Diagram:

In software engineering, a class diagram in the Unified Modeling Language is a type of static
structure diagram that describes the structure of a system by showing the system's classes,
their attributes, operations, and the relationships among objects.

LAB TASKS:

1. A vending machine sells small, packaged, ready to eat items (chocolate bars, cookies,
candies, etc.). Each item has a price and a name. A customer can buy an item, using a smart
card (issued by the vending machine company) to pay for it. No other payment forms (i.e.
cash, credit card) are allowed. The smart card records on it the amount of money available.
The functions supported by the system are: Sell an item (choose from a list of items, pay
item, distribute item) Recharge the machine Set up the machine (define items sold and
price of items) Monitor the machine (number of items sold, number of items sold per type,
total revenue)

The system can be used by a customer, a maintenance employee (who recharges items in the
machines), an administrator (who sets up the machine).

2. Draw a use case diagram using the above cases and determine the relation between them?

3. A company consists of departments. Departments are located in one or more offices. One
office acts as a headquarter. Each department has a manager who is recruited from the set
of employees. Your task is to model the system for the company. Draw a class diagram
which consists of all the classes in your system their attributes and operations, relationships
between the classes, multiplicity specifications, and other model elements that you find
appropriate

4. Draw a sequence diagram for withdrawing money from an ATM machine


AIR UNIVERSITY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING

EXPERIMENT NO 12

Lab Title: UML State Diagrams

Student Name: Reg. No:

Objective:

LAB ASSESSMENT:

Excellent Good Average Satisfactory Unsatisfactory


Attributes
(5) (4) (3) (2) (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:


Excellent Good Average Satisfactory Unsatisfactory
Attributes
(5) (4) (3) (2) (1)

Data presentation

Experimental results

Conclusion

Total Marks: Obtained Marks:


Date: Signature:

EXPERIMENT NO 12

UML State Diagrams

Objectives:
 Learn to draw State Diagrams for C++ code design

Equipment’s required:
 Visio 2010

Description:

A state diagram is used to represent the condition of the system or part of the system at
finite instances of time. It’s a behavioral diagram and it represents the behavior using finite
state transitions. State diagrams are also referred to as State machines and State-chart
Diagrams. These terms are often used interchangeably. So simply, a state diagram is used to
model the dynamic behavior of a class in response to time and changing external stimuli.
We can say that each and every class has a state but we don’t model every class using State
diagrams. We prefer to model the states with three or more states.
Uses of state chart diagram –
 We use it to state the events responsible for change in state (we do not show what
processes cause those events).
 We use it to model the dynamic behavior of the system.
 To understand the reaction of objects/classes to internal or external stimuli.

Basic components of a statechart diagram –

1. Initial state – We use a black filled circle represent the initial state of a System or a
class.

Figure – initial state notation


2. Transition – We use a solid arrow to represent the transition or change of control from
one state to another. The arrow is labelled with the event which causes the change in
state.
Figure – transition

3. State – We use a rounded rectangle to represent a state. A state represents the


conditions or circumstances of an object of a class at an instant of time.

Figure – state notation


4. Fork – We use a rounded solid rectangular bar to represent a Fork notation with
incoming arrow from the parent state and outgoing arrows towards the newly created
states. We use the fork notation to represent a state splitting into two or more
concurrent states.
Figure – a diagram using the fork notation
5. Join – We use a rounded solid rectangular bar to represent a Join notation with
incoming arrows from the joining states and outgoing arrow towards the common goal
state. We use the join notation when two or more states concurrently converge into
one on the occurrence of an event or events.

Figure – a diagram using join notation


6. Self transition – We use a solid arrow pointing back to the state itself to represent a
self transition. There might be scenarios when the state of the object does not change
upon the occurrence of an event. We use self transitions to represent such cases.

Figure – self transition notation


7. Composite state – We use a rounded rectangle to represent a composite state
also.We represent a state with internal activities using a composite state.
Figure – a state with internal activities

8. Final state – We use a filled circle within a circle notation to represent the final state in
a state machine diagram.

Figure – final state notation

LAB TASKS:

1. Draw a State Diagram for placing an online order.


2. Draw Airport check in state diagram in Visio.
AIR UNIVERSITY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING

EXPERIMENT NO 13

Lab Title: UML for Project


Student Name: Reg. No:

Objective:

LAB ASSESSMENT:

Excellent Good Average Satisfactory Unsatisfactory


Attributes
(5) (4) (3) (2) (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:


Excellent Good Average Satisfactory Unsatisfactory
Attributes
(5) (4) (3) (2) (1)

Data presentation

Experimental results

Conclusion

Total Marks: Obtained Marks:


Date: Signature:

EXPERIMENT NO 13

UML for Project

Objectives:
 To design UML for the project

Equipment required:

 Visio 2010
Description:

On the day The Imitation Game hits cinemas, a look at how Allied
codebreakers untangled the Enigma

Like all the best cryptography, the Enigma machine is simple to describe, but infuriating to
break.

Straddling the border between mechanical and electrical, Enigma looked from the outside
like an oversize typewriter. Enter the first letter of your message on the keyboard and a
letter lights up showing what it has replaced within the encrypted message. At the other
end, the process is the same: type in the “ciphertext” and the letters which light are the
decoded missive.

Inside the box, the system is built around three physical rotors. Each takes in a letter and
outputs it as a different one. That letter passes through all three rotors, bounces off a
“reflector” at the end, and passes back through all three rotors in the other direction.

The board lights up to show the encrypted output, and the first of the three rotors clicks
round one position – changing the output even if the second letter input is the same as the
first one.

When the first rotor has turned through all 26 positions, the second rotor clicks round, and
when that’s made it round all the way, the third does the same, leading to more than 17,000
different combinations before the encryption process repeats itself. Adding to the
scrambling was a plugboard, sitting between the main rotors and the input and output,
which swapped pairs of letters. In the earliest machines, up to six pairs could be swapped in
that way; later models pushed it to 10, and added a fourth rotor.
Working of Enigma:

LAB TASK:

1. Design UML diagrams for the Enigma Machine given as project to you. (Use Case
Diagram, Class Diagram, Sequence Diagrams etc)

You might also like