OOP Manual
OOP Manual
OOP Manual
STUDENT NAME:
REG. NO:
SECTION:
1 Introduction to Structures
2 Introduction to Classes
5 Operator Overloading
6 Inheritance
7 Multiple Inheritance
8 Polymorphism
9 STL in C++
14 Open-ended lab
AIR UNIVERSITY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
EXPERIMENT NO 1
Objective:
LAB ASSESSMENT:
Data presentation
Experimental results
Conclusion
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.
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.
struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here
};
#include <iostream>
using namespace std;
struct Point {
int x, y;
};
int main()
{
struct Point p1 = { 0, 1 };
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
Objective:
LAB ASSESSMENT:
Data presentation
Experimental results
Conclusion
Date: Signature:
EXPERIMENT NO 2
Objectives:
To learn difference between structures and classes
Implementing classes and understand data encapsulation in C++
Equipment required:
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.
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.
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
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:
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
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
Objective:
LAB ASSESSMENT:
Data presentation
Experimental results
Conclusion
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:
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
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.
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:
Copy Constructor
The copy constructor is called whenever an object is initialized from another object of the
same type, which includes
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
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);
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:
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
Objective:
LAB ASSESSMENT:
Data presentation
Experimental results
Conclusion
Date: Signature:
EXPERIMENT NO 4
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.
Friendship-grant is not commutative. It is not dual side relationship until or unless declared
in both the classes separately
LAB TASK
• 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
EXPERIMENT NO 5
Objective:
LAB ASSESSMENT:
Data presentation
Experimental results
Conclusion
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
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)
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.
- 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.
o Overload the addition assignment operator (+=), subtraction assignment operator (-=),
and multiplication assignment operator (*=).
EXPERIMENT NO 6
Objective:
LAB ASSESSMENT:
Data presentation
Experimental results
Conclusion
EXPERIMENT NO 6
Inheritance
Objective:
Equipment Required:
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.
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 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.
• 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.
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
Objective:
LAB ASSESSMENT:
Data presentation
Experimental results
Conclusion
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
For example,
Petrol is derived from both liquid and fuel.
class base_class1
properties;
methods;
};
class base_class2
properties;
methods;
};
class base_classN
properties;
methods;
};
{
properties;
methods;
};
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
EXPERIMENT NO 8
Objective:
LAB ASSESSMENT:
Data presentation
Experimental results
Conclusion
EXPERIMENT NO 8
Polymorphism
Objectives
To understand and implement the core concept of Polymorphism in OOP classes
Equipment required
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
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
}; };
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
virtual void draw() const; virtual void draw() const; virtual void draw() const;
}; }; };
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
a2 4a
r2 2r
6a2 a3
4r2 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
Objective:
LAB ASSESSMENT:
Data presentation
Experimental results
Conclusion
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
Lab Tasks
I. Create template function display that displays all the items of the list.
II. Use STL to implement stack and queue
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:
Data presentation
Experimental results
Conclusion
EXPERIMENT NO 10
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:
// Destructor
~SmartPtr() { delete(ptr); }
int main()
{
SmartPtr ptr(new int());
*ptr = 20;
cout << *ptr;
return 0;
}
Exception Handling:
Errors can be broadly categorized into two types. We will discuss them one by one.
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
#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.
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
Objective:
LAB ASSESSMENT:
Data presentation
Experimental results
Conclusion
EXPERIMENT NO 11
Objectives:
To learn converting C++ code into UML diagrams and vice versa
Equipment’s required:
Visio 2010
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
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
EXPERIMENT NO 12
Objective:
LAB ASSESSMENT:
Data presentation
Experimental results
Conclusion
EXPERIMENT NO 12
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.
1. Initial state – We use a black filled circle represent the initial state of a System or a
class.
8. Final state – We use a filled circle within a circle notation to represent the final state in
a state machine diagram.
LAB TASKS:
EXPERIMENT NO 13
Objective:
LAB ASSESSMENT:
Data presentation
Experimental results
Conclusion
EXPERIMENT NO 13
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)