0% found this document useful (0 votes)
20 views104 pages

OOPs With C - CSE 2001 - Unit 1

The document outlines a course on Object Oriented Programming (OOP) with C++, detailing its principles, learning objectives, and key concepts such as classes, objects, inheritance, and polymorphism. It contrasts OOP with procedural programming, highlighting the benefits of OOP like reusability, data hiding, and reduced complexity, while also addressing its limitations. Additionally, it introduces UML for visualizing system designs and provides examples of class diagrams to illustrate OOP concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views104 pages

OOPs With C - CSE 2001 - Unit 1

The document outlines a course on Object Oriented Programming (OOP) with C++, detailing its principles, learning objectives, and key concepts such as classes, objects, inheritance, and polymorphism. It contrasts OOP with procedural programming, highlighting the benefits of OOP like reusability, data hiding, and reduced complexity, while also addressing its limitations. Additionally, it introduces UML for visualizing system designs and provides examples of class diagrams to illustrate OOP concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 104

VIT Bhopal University

Bhopal-Indore Highway, Kothri Kalan, Sehore, Madhya Pradesh – 466114.

Object Oriented Programming with C++


Course Code: CSE 2001

By:
Dr. Ramraj Dangi
● To understand the principles of
Object oriented programming
Learning ● To identify and practice the object
oriented programming concepts
Objectives ●
and techniques
To solve a real world problems
through object oriented approach
● Introduction to object oriented
approach
● Classes and objects
Chapters ● Polymorphism and Inheritance
● Exception handling and Templates
● IOstreams and Files
● Stanley B Lippman, Josee Lajoie,
Barbara E, Moo, “C++ primer”,
Fifth edition, Addison-Wesley, 2012
● Bjarne Stroustrup, The C++
programming Language, Addison
Wesley, 4th edition, 2013
Textbooks ● Harvey M. Deitel and Paul J. Deitel,
C++ How to Program, 7th edition,
Prentice Hall, 2010
● Maureen Sprankle and Jim Hubbard,
Problem solving and Programming
concepts, 9th edition, Pearson
Education, 2014
Introduction to Object Oriented
Approach
Chapter 1: Introduction to Object Oriented Approach

❖ Why object oriented programming?


❖ Characteristics of object oriented language: classes, objects, encapsulation, data
abstraction, inheritance, polymorphism
❖ Merits and Demerits of object oriented programming.
❖ UML: class diagram of OOP
❖ Inline function, default argument function
❖ Exception handling(Standard)
❖ Reference: independent reference – function returning reference – pass by reference
Object means a real word entity such
as pen, chair, table etc.

Why Object Oriented Object-Oriented Programming is a


methodology or paradigm to design a
Programming? program. It simplifies the software
development and maintenance by
providing some concepts:
Why?

OOP language allows to break the program into the bit-sized problems that can be
solved easily (one object at a time). The new technology promises greater programmer
productivity, better quality of software and lesser maintenance cost. OOP systems can
be easily upgraded from small to large systems.
Timeline

Object-oriented programming is such a fundamental part of software development that it’s hard to
remember a time when people used any other approach. However, when objected-oriented
programming, or OOP, first appeared in the 1980s, it was a radical leap forward from the
traditional top-down method.

These days, most major software development is performed using OOP. Thanks to the widespread
use of languages like Java and C++, you can’t develop software for mobile unless you understand
the object-oriented approach. The same goes for web development, given the popularity of OOP
languages like Python, PHP and Ruby. That said, many developers start off with top-down
languages like Visual Basic or JavaScript.
Procedural Programming Approach

The high level languages such as COBOL,


FORTRAN and C are commonly known as
procedure-oriented programming (POP). In the
procedure-oriented approach, the problem is
viewed as a sequence of things and a number
functions are written to accomplish these tasks.
The primary focus is on functions.

Procedural Programming Model : Each problem


is divided into smaller problems and solved
using specified modules that act on data.
Procedural Programming Approach

In a multi-function program, many important


data items are placed as global so that they may
be accessed by all the functions. Each function
may have its own local data . Fig shows the
relationship of data and functions in a
procedure-oriented program.
Procedural Limitations
Programming
– In large program, it is difficult to identify which
data is used for which function.
– To revise an external data structure, all functions
that access the data should also be revised.
– Maintaining and enhancing program code is still
difficult because of global data.
– Focus on functions rather than data.
– It does not model real world problem very well.
Since functions are action oriented and do not really
correspond to the elements of problem.
Why has OOPs become a major programming paradigm?

So far, you’ve built two kinds of C++ programs:

● Procedural: The program moves through a linear series of instructions.


● Functional: The program moves from one function to another.

But there is another very common way to structure C++ code: object-oriented
programming.
Object Oriented Approach

The major motivating factor in the invention of object-oriented approach is to remove


some of the flaws encountered in the procedural approach. OOP treats data as a critical
element in the program development and does not allow it to flow freely around the
system. It ties data more closely to the functions that operate on it, and protects it from
accidental modification from outside functions.
Object Oriented Approach

OOP allows decomposition of a problem into a


number of entities called objects and then
builds data and functions around these objects.
The organization of data and functions in
object-oriented program is shown in figure.

The data of an object can be accessed only by


the functions associated with the object.
However, functions of one object can access the
functions of other objects.
Object Oriented Programming

“Object-oriented programming as an approach that provides a way of modularizing


programs by creating partitioned memory area for both data and functions that can be
used as template for creating copies of such modules on demand” . Memory partitions
are independent; the objects can be used in a variety of different programs without
modifications.
Object oriented programming model: It perceived the entire software system as a
collections of objects which contain attributes and behaviors.
Features of OOPs

– Emphasis is on data rather than procedures.


– Programs are divided into objects.
– Data structures are designed such that they characterize the objects .
– Functions & data are tied together in the data structures so that data abstraction is
introduced in addition to procedural abstraction.
Features of OOPs- Cont.

– Data is hidden & can’t be accessed by external functions.


– Object can communicate with each other through function.
– New data & functions can be easily added.
– Follows Bottom up approach.
Benefits of OOPs

1. Reusability: In OOP's programs functions and modules that are written by a user can be reused
by other users without any modification.
2. Inheritance: Through this we can eliminate redundant code and extend the use of existing
classes.
3. Data Hiding: The programmer can hide the data and functions in a class from other classes. It
helps the programmer to build the secure programs.
4. Reduced complexity of a problem: The given problem can be viewed as a collection of
different objects. Each object is responsible for a specific task. The problem is solved by
interfacing the objects. This technique reduces the complexity of the program design.
Benefits of OOPs

5. Easy to Maintain and Upgrade: OOP makes it easy to maintain and modify existing code as
new objects can be created with small differences to existing ones. Software complexity can be
easily managed.
6. Message Passing: The technique of message communication between objects makes the
interface with external systems easier.
7. Modifiability: it is easy to make minor changes in the data representation or the procedures in
an OO program. Changes inside a class do not affect any other part of a program, since the only
public interface that the external world has to a class is through the use of methods.
Question

Procedure Oriented Programming


vs.
Object Oriented Programming
Object Oriented Languages

Some of the well-known object-oriented languages are Objective Perl, Javascript,


Python, Modula, Ada, Simula, C++, Smalltalk and some Common Lisp Object
Standard.

Here we are discussing OOPs with C++ and its benefits on C++.
Merits of OOPs

● We can build the programs from standard working modules that communicate with one
another, rather than having to start writing the code from scratch which leads to saving of
development time and higher productivity,
● OOP language allows to break the program into the bit-sized problems that can be solved
easily (one object at a time).
● The new technology promises greater programmer productivity, better quality of software
and lesser maintenance cost.
● OOP systems can be easily upgraded from small to large systems.
● It is possible that multiple instances of objects co-exist without any interference.
Merits of OOPs

● It is very easy to partition the work in a project based on objects.


● It is possible to map the objects in problem domain to those in the program.
● The principle of data hiding helps the programmer to build secure programs which cannot
be invaded by the code in other parts of the program.
● By using inheritance, we can eliminate redundant code and extend the use of existing
classes.
● Message passing techniques is used for communication between objects which makes the
interface descriptions with external systems much simpler.
● The data-centered design approach enables us to capture more details of model in an
implementable form.
Demerits of OOPs

● The length of the programmes developed using OOP language is much larger than the
procedural approach. Since the programme becomes larger in size, it requires more time
to be executed that leads to slower execution of the programme.
● Programmers need to have brilliant designing skill and programming skill along with
proper planning because using OOP is little bit tricky.
● OOPs take time to get used to it. The thought process involved in object-oriented
programming may not be natural for some people.
● Everything is treated as object in OOP so before applying it we need to have excellent
thinking in terms of objects.
Characteristics of Object Oriented Language

❖ Classes
❖ Objects
❖ Encapsulation
❖ Data Abstraction
❖ Inheritance
❖ Polymorphism
❖ Dynamic Binding
❖ Message Passing
Objects

Objects are the basic run-time entities in an object-oriented system.


They may represent a person, a place, a bank account, a table of data
or any item that the program must handle.The fundamental idea
behind object oriented approach is to combine both data and
function into a single unit and these units are called objects.
The term objects means a combination of data and program that
represent some real word entity.
When a program executed, the object interact by sending messages
to one another. Each object contain data, and code to manipulate the
data.
Classes

A group of objects that share common properties for data part and some program part
are collectively called as class. In C ++ a class is a new data type that contains member
variables and member functions that operate on the variables.
The entire set of data and code of an object can be made a user-defined data type with
the help of a class. Objects are variable of the type class. Once a class has been defined,
we can create any number of objects belonging to that class.
Classes

Example:
When class is defined, objects are created as:
<classname><objectname>;
If employee has been defined as a class, then the statement
employee manager;
will create an object manager belonging to the class employee.
Encapsulation

Wrapping of data and functions together as a single unit is known as


encapsulation. By default data is not accessible to outside world and they are only
accessible through the functions which are wrapped in a class. Prevention of data from
direct access by the program is called data hiding or information hiding.
Data Abstraction

Abstraction refers to the act of representing essential features without including


the background details or explanation. Classes use the concept of abstraction and are
defined as a list of attributes such as size, weight, cost and functions to operate on these
attributes. They encapsulate all essential properties of the object that are to be created.
The attributes are called as data members as they hold data and the functions which
operate on these data are called as member functions.
Class use the concept of data abstraction so they are called abstract data type (ADT).
Inheritance

Inheritance is the mechanism by which one class can inherit the properties of another. It
allows a hierarchy of classes to be build, moving from the most general to the most
specific. When one class is inherited by another, the class that is inherited is called the
base class. The inheriting class is called the derived class. In general, the process of
inheritance begins with the definition of a base class. The base class defines all
qualities that will be common to any derived class.
In OOPs, the concept of inheritance provides the idea of reusability. In essence, the
base class represent the most general description of a set of traits. The derived class
inherits those general traits and adds properties that are specific to that class.
Example

Employee
Name
Employee ID
Department
Designation

Branch
IFSC Code
Name
Example
People
Name
Age
City BASE Class
Mail ID
Department

Student Faculty
Scholar No Faculty ID
CGPA Derived Designation
Classes
Polymorphism

Polymorphism comes from the Greek words “poly” and “morphism”. “poly” means
many and “morphism” means form i.e.. many forms. Polymorphism means the ability
to take more than one form. For example, an operation have different behavior in
different instances. The behavior depends upon the type of the data used in the
operation.
Different ways to achieving polymorphism in C++ program:
1) Function overloading
2) Operator overloading
Dynamic Binding

Binding refers to the linking of a procedure call to the code to the executed in response
to the call. Dynamic binding means the code associated with a given procedure call is
not known until the time of the call at run-time. It is associated with a polymorphic
reference depends upon the dynamic type of that reference.
Message Passing

An object oriented program consists of a set of objects that communicate with each
other.
A message for an object is a request for execution of a procedure and therefore will
invoke a function (procedure) in the receiving object that generates the desired result.
Message passing involves specifying the name of the object, the name of the function
(message) and information to be sent.
UML: Unified Modeling Language

● Unified Modeling Language (UML) is a general purpose modelling language. The


main aim of UML is to define a standard way to visualize the way a system has been
designed. It is quite similar to blueprints used in other fields of engineering.
● UML is not a programming language, it is rather a visual language.
● UML diagrams portray the behavior and structure of a system.
● UML helps software engineers, businessmen and system architects with modelling,
design and analysis.
UML Diagrams
Class Diagram

● The most widely use UML diagram is the class diagram.


● It is the building block of all object oriented software systems.
● We use class diagrams to depict the static structure of a system by showing system’s
classes,their methods and attributes.
● Class diagrams also help us identify relationship between different classes or objects.
● The class diagram can be used to show the classes, relationships, interface, association, and
collaboration.
● The class diagram has an appropriate structure to represent the classes, inheritance,
relationships, and everything that OOPs have in their context.
Cont.

The main purpose to use class diagrams are:


● This is the only UML that can appropriately depict various aspects of the OOPs concept.
● Proper design and analysis of applications can be faster and efficient.
● It is the base for deployment and component diagram.

There are several software available that can be used online and offline to draw these diagrams
like Edraw max, lucid chart, etc. There are several points to be kept in focus while drawing the
class diagram. These can be said as its syntax:
Example:

Each class is represented by a rectangle having a subdivision of three compartments name,


attributes, and operation.

There are three types of modifiers that are used to decide the visibility of attributes and operations.
● + is used for public visibility(for everyone)
● # is used for protected visibility (for friend and derived)
● – is used for private visibility (for only me)
Class

The UML representation of a class is a rectangle containing three compartments stacked vertically,
as shown in the Figure:
Attributes and Operations

Attribute
The attribute section of a class lists each of the class's attributes on a separate line. The attribute section is
optional, but when used it contains each attribute of the class displayed in a list format. The line uses this
format: name : attribute type (e.g. cardNumber : Integer).

Operation
The operations are documented in the bottom compartment of the class diagram's rectangle, which also is
optional. Like the attributes, the operations of a class are displayed in a list format, with each operation
on its own line. Operations are documented using this notation: name (parameter list) : type of value
returned (e.g. calculateTax (Country, State) : Currency).
Relationship

● Association
Association specifies a "has-a" or
● Multiplicity "whole/part" relationship between two
● Visibility classes. In an association relationship,
an object of the whole class has objects
● Generalization
of part class as instance data.
● Dependency
Association

Unidirectional association - In a unidirectional Bidirectional (standard) association -


association, two classes are related, but only one Associations are always assumed to be
class knows that the relationship exists. A bi-directional; this means that both classes are
unidirectional association is drawn as a solid line aware of each other and their relationship, unless
with an open arrowhead pointing to the known you qualify the association as some other type. A
class. bi-directional association is indicated by a solid
line between the two classes.
A B A B
Multiplicity

Place multiplicity notations near the ends of an association. These symbols indicate the number of
instances of one class linked to one instance of the other class. For example, one company will have one
or more employees, but each employee works for one company only.
Visibility

Visibility is used to signify who can access the information contained within a class denoted with +, -, #
as show in the figure:
Generalisation

A generalization is a relationship between a


general thing (called the superclass) and a more
specific kind of that thing (called the subclass).
Generalization is sometimes called an "is a kind
of" relationship and is established through the
process of inheritance.

In a class diagram, generalization relationship is


rendered as a solid directed line with a large open
arrowhead pointing to the parent class.
Dependency

Dependency indicates a "uses" relationship between two classes. In a class diagram, a dependency
relationship is rendered as a dashed directed line.
If a class A "uses" class B, then one or more of the following statements generally hold true:

1. Class B is used as the type of a local variable in one or more methods of class A.
2. Class B is used as the type of parameter for one or more methods of class A.
3. Class B is used as the return type for one or more methods of class A.
4. One or more methods of class A invoke one or more methods of class B.
Class Diagram for E-Commerce Websites
Class Diagram for E-Commerce Websites
Example of Class Diagram
Class Diagram of an E-mail
1. 2.

Practice Class Diagrams


Functions in C++

• A function is block of code which is used to perform a particular task when it is called.
• Functions are used to perform certain actions, and they are important for reusing code: Define the
code once, and use it many times.
• Depending on whether a function is predefined or created by programmer; there are two types of
function:
• Library Function : Library functions are the built-in function. Programmer can use library function
by invoking function directly; they don't need to write it themselves.
• User-defined Function : The function created by the user according to the need.
Function Elements

Generally, C++ function has three parts:


• Function Prototype: declaring a function before calling a function is called function declaration
or prototype which tells the compiler that at some point of the program we will use the function of
the name specified in the prototype.
• Function Call: means calling the function with a statement. When the program encounters the
function call statement the specific function is invoked.
• Function Definition: is a part where we define the operation of a function. It consists of the
declarator followed by the function body.
Function Elements

• You can pass data, known as parameters, into a function.


• A parameter is a variable in a method definition. When a method is called, the arguments are the
data you pass into the method's parameters. Parameter is variable in the declaration / definition of
function. Argument is the actual value of this variable that gets passed to function.
User Defined Functions
User Defined Function Types :

For better understanding of arguments and return in functions, user


defined functions can be categorised as:
• Function with no argument and no return value
• Example: void add(void);
• Function with argument but no return value
• Example: void add(int,int); Note:
• Function with no argument but return value The particular method is
• Example: int add(void); chosen depending upon
• Function with argument and return value the situation and how you
• Example: int add(int,int); want to solve a problem.
Function with no return value and no argument
Example 1: Function with no argument and no return value

//Program to print square of a number using functions.


#include<iostream>
using namespace std;
void sqr(void); //function prototype
int main()
{
sqr(); //function calling
}

void sqr() //function definition


{//function body starts
int no;
cout<<"Enter a no.::";
cin>>no;
cout<<"Square of "<<no<<" is ::"<<no*no;
}
Example 2: Function with argument but no return value

//Program to add two numbers using functions


#include<iostream>
#include<conio.h>
using namespace std;
void add(int,int);
int main()
{
int a,b;
cout<<"enter values of a and b"<<endl;
cin>>a>>b;
void add(int x,int y)
add(a,b);
{
getch();
int c;
return 0;
c=x+y;
}
cout<<"addition is"<<c;
}
Example 3: Function with no argument but return value

//Program to add two numbers using functions


#include<iostream>
#include<conio.h>
using namespace std;
int add(void);
int main()
{
int z;
z=add(); int add(void)
cout<<"sum of 2 numbers is"<<z; {
getch(); int a,b;
return 0; cout<<"enter 2 numbers::";
} cin>>a>>b;
return(a+b);
}
Example 4: Function with argument and return value

#include<iostream>
#include<conio.h>
using namespace std;
int sqr(int);
int main()
{
int a,ans;
cout<<"enter a number";
cin>>a;
ans=sqr(a); int sqr(int X)
cout<<"square of number is"<<ans; {
getch(); return(X*X);
return 0; }
}
Function

Understand
• One of the major objectives of using functions in a program is to save memory space, which
becomes appreciable when a function is likely to be called many times.
• However, every time a function is called, it takes a lot of extra time in executing tasks such
as jumping to the calling function.
• When a function is small, a substantial percentage of execution time may be spent in such
overheads and sometimes maybe the time taken for jumping to the calling function will be
greater than the time taken to execute that function.
Inline Function

● C++ provides an inline functions to reduce the function call overhead.


● Inline function is a function that is expanded in line when it is called.
● When the inline function is called whole code of the inline function gets inserted or
substituted at the point of inline function call.
● This substitution is performed by the C++ compiler at compile time.
● Inline function may increase efficiency if it is small.
● The syntax for defining the function inline is:
inline <return_type> <function_name>(<parameters>)
{
// function code
}
Functioning of Inline Function
Example: Inline Function

#include <iostream>
using namespace std;

int cube(int); //function prototype

int main()
{
cout << "The cube of 3 is: " << cube(3) << "\n"; //calling
return 0;
}

inline int cube(int s) //definition


{
return s*s*s;
}
Example: Inline Function

#include <iostream>
using namespace std;

inline int cube(int s)


{
return s*s*s;
}

int main()
{
cout << "The cube of 3 is: " << cube(3) << "\n";
return 0;
}
Example: Inline Function

#include <iostream>
using namespace std;
class firstClass //Name of Class
{
int a,b,add,sub,mul;
float div; //attributes or data members
public:
void get(); //member function or operations
void sum();
void difference();
void product();
void division();
};

int main()
{
cout << "Program using inline function\n";
firstClass s;
s.get();
s.sum(); //to call the functions from objects (.)
s.difference(); //s <object name>.<dot operator> difference()<function name>
s.product();
s.division();
return 0;
}
Example: Inline Function

inline void f irstClass :: product()


{
mul = a*b;
inline void firstClass :: get()
cout << "Product of two numbers: " << a*b << "\n";
{
}
cout << "Enter first value:";
cin >> a;
inline void f irstClass ::division()
cout << "Enter second value:";
{
cin >> b;
div=a/b;
}
cout<<"Division of two numbers: "<<a/b<<"\n" ;
}
inline void f irstClass :: sum()
{
add = a+b;
cout << "Addition of two numbers: " << a+b << "\n";
}

inline void f irstClass :: difference()


{
sub = a-b;
cout << "Difference of two numbers: " << a-b << "\n";
}
Points to Remember/ Limitation

Inlining is only a request to the compiler, not a command. Compiler can ignore the request for
inlining. Compiler may not perform inlining in such circumstances like:
1. If a function contains a loop. (for, while, do-while)
2. If a function contains static variables.
3. If a function is recursive.
4. If a function return type is other than void, and the return statement doesn’t exist in function
body.
5. If a function contains switch or goto statement.
Advantages of Inline Function

● Function call overhead doesn’t occur. It saves the overhead of a return call from a function.
● When we use the inline function it may enable the compiler to perform context-specific
optimization on the function body, such optimizations are not possible for normal function calls.
● An inline function may be useful for embedded systems because inline can yield less code than the
function call preamble and return.
Disadvantages of Inline Function

● If you use too many inline functions then the size of the binary executable file will be large,
because of the duplication of same code.
● Too much inlining can also reduce your instruction cache hit rate, thus reducing the speed of
instruction fetch from that of cache memory to that of primary memory.
● Inline function may increase compile time overhead if someone changes the code inside the inline
function then all the calling location has to be recompiled because compiler would require to
replace all the code once again to reflect the changes, otherwise it will continue with old
functionality.
● Inline functions might cause thrashing because inlining might increase size of the binary
executable file. Thrashing in memory causes performance of computer to degrade.
Default Arguments

What are Default Arguments?


• A default argument is a default value provided for a function parameter.
• If the user does not supply an explicit argument for a parameter with a default argument, the
default value will be used.
• If the user does supply an argument for the parameter, the user-supplied argument is used.
Need?
• Because the user can choose whether to supply a specific argument value, or use the default, a
parameter with a default value provided is often called an optional parameter.
Default
Arguments
in C++
Points to Remember

● All default arguments must be for the rightmost parameters.


Ex. void printValue(int x=10, int y); // not allowed
● Cannot mix a default argument in between two arguments.
Ex. void add(int a, int b = 3, int c, int d = 4); //not allowed
● If more than one default argument exists, the leftmost default argument should be the one most
likely to be explicitly set by the user.
● Default arguments can only be declared once
If the function has a forward declaration, put the default argument there. Otherwise, put them in the
function definition.
Exception Handling

Exception handling in C++ is a special condition for developers to handle. In programming, it is


normal to commit mistakes that prompts unusual conditions called errors.

All in all, these errors are of three kinds:

1. Syntax Error
2. Logical Error
3. Runtime Error
Exceptions Handling Cont.

● Exception in programming languages like C++ means run time errors i.e. errors which appear
during execution of a program.

● It might be due to user’s wrong input or any logical fallacy of the program.

● Exception handling is the behavior of a program after an exception occurs.

● But before understanding how to handle exception, first let us understand what C++ does when an
exception occurs.

● By default C++ takes 2 actions whenever an exception occurs -


Exception Handling
How C++ handles it???

● It immediately kills the program on the line where the exception occurs.

● It defines the reason for exception but is highly technical and is not friendly to an user.

Both the above actions are not user friendly because,


1. If exception occurs at least those lines should continue to run which are not related with
the exception.

2. It would be much better if our program displays an easy to understand message regarding
the exception so that the user can become aware about his mistakes.
Keywords of Exception Handling

Exception Handling in C++ falls around these three keywords:

Try: the try block Catch: a program that


Throw: when a program
recognises the code utilises an exception
experiences an issue, it
block for which certain handler to catch an
throws an Exception.
exceptions will be Exception. It is added to
The throw keyword
enacted. It ought to be the part of a program
assists the program by
followed by one/more where you need to deal
performing throw.
catch blocks with the error.
Syntax

try {
// Block of code to try
throw exception; // Throw an exception when a problem arise
}
catch () {
// Block of code to handle errors
}
Example:

#include <iostream>
using namespace std; Enter numerator: 72
int main() { Enter denominator: 0
double numerator, denominator, divide; Error: Cannot divide by 0
cout << "Enter numerator: ";
cin >> numerator;
cout << "Enter denominator: "; Enter numerator: 72
cin >> denominator; Enter denominator: 3
try { 72 / 3 = 24
// throw an exception if denominator is 0
if (denominator == 0)
throw 0;
// not executed if denominator is 0
divide = numerator / denominator;
cout << numerator << " / " << denominator << " = " << divide << endl;
}
catch (int num_exception) {
cout << "Error: Cannot divide by " << num_exception << endl;
}
return 0;}
Functioning of Catch
There is a special catch block called ‘catch all’ #include <iostream>
using namespace std;
catch(…) that can be used to catch all types of int main()
exceptions. {
try {
throw 'a';
For example, in the following program, an int is
}
thrown as an exception, but there is no catch catch (int x) {
cout << "Caught " << x;
block for int, so catch(…) block will be executed.
}
catch (...) {
cout << "Default Exception\n";
}
return 0;
}
Example 1

try {
int age = 15;
if (age >= 18) {
cout << "Access granted - you are old enough.";
} else {
throw (age);
}
}
catch (int myNum) {
cout << "Access denied - You must be at least 18 years old.\n";
cout << "Age is: " << myNum;
}
Exception Handling: Summary

● An exception is a problem that arises during the execution of a program.


● A C++ exception is a response to an exceptional circumstance that arises while a program is
running, such as an attempt to divide by zero.
● Exceptions provide a way to transfer control from one part of a program to another.
● C++ exception handling is built upon three keywords: try, catch, and throw.
● One of the advantages of C++ over C is Exception Handling.
● There are two types of exceptions: a)Synchronous, b)Asynchronous(Ex:which are beyond
the program’s control, Disc failure etc)
Basics to Pointers in C++

Pointers
Special type of variables which hold the address of another variable, i.e no values or datas are
stored but it points to another variable where data is stored.
Ex:
int a; //declaration
100 a
a = 100; //initialization

a 100 Memory Int &ref= a

name value address


Pointer Example
a
Note: a pointer can be used to point to another pointer also i.e it
can store the address of another pointer.
Ex.

int a = 100;
cout << a; //100
int *ptr = &a;
cout << ptr;//ML
int **ptr1 = &ptr;
cout << ptr1; //ML
cout << *ptr; //100 ptr1
cout << **ptr1; //100 address 2
address 3
Reference Variable
When a variable is declared as reference, it becomes an alternative name for an existing variable.
A variable can be declared as reference by putting ‘&’ in the declaration.

int a = 100;

Now we will use a reference variable i.e two names for same memory location.

int &ref=a; //initialization and declaration

Now in program we can use either “a” or an alternative name “ref”

c = a+b; or c = ref+b; //Output?


Example

#include<iostream.h>
#include<conio.h>
int main()
{
int a=100;
int &ref=a;
cout<<“value of a is”<<a; //100
Output:
cout<<“value of ref is”<<ref; //100
cout<<address of a is”<<&a; //ML
cout<<address of a is”<<&ref; //ML (same)
getch();
}
Call by Value and Reference

A function can be invoked in 2 manner


(i) call by value
(ii) call by reference

The call by value method copies the value of actual parameters into formal parameters

i.e the function creates its own copy of arguments and uses them.
In call by reference method in place of calling a value to the function being called , a reference to
the original variable is passed,
i.e the same variable value can be accessed by any of the two names.
Example: Call by Value

/* C++ Program to Swap two numbers using call by value */

#include<iostream>
void swap(int a,int b)
using namespace std;
{
int c;
void swap(int,int);
c=a;
a=b;
int main()
b=c;
{
cout<<"\nInside Function After Swapping”;
int a,b;
cout<<”Value of :: \n\tA = "<<a;
cout<<"Enter Value Of A :: ";
cout<<"\tB = "<<b<<"\n";//20 and 10
cin>>a;
}
cout<<"\nEnter Value of B :: ";
cin>>b;

cout<<"\nBefore Swapping, Value of :: \n\tA = "<<a<<"\tB = "<<b<<"\n"; //10, 20

swap(a,b);

cout<<"\nOutside Function After Swapping, Value of :: \n\tA = "<<a<<"\tB = "<<b<<"\n";


}
10 20 10 20

a b a b

x y

20 10

a b

&x = a, &y = b
Example: Call by Reference

/* C++ program to Swap Values using call by reference */

#include<iostream>
using namespace std; void swap(int &x,int &y)
{
void swap(int &,int &); int temp;
temp=x;
int main() x=y;
{ y=temp;
int a,b; }

cout<<"\nEnter 1st number :: ";


cin>>a;
cout<<"\nEnter 2nd number :: ";
cin>>b;

cout<<"\nBefore Swapping :: \n\ta = "<<a<<"\tb = "<<b<<"\n";//10, 20


swap(a,b);
cout<<"\nAfter Swapping :: \n\ta = "<<a<<"\tb = "<<b<<"\n";// 20, 10

return 0;
}
Basic C++ Programs
Program 1

#include<iostream>
using namespace std;
int main()
{
cout<<"Hello World";
return 0;
}
Program 2

//Addition of two numbers


#include<iostream>
using namespace std;
int main()
{
cout<<"Enter two numbers::"<<endl;
int a;
int b;
cin>>a>>b;
int c = a+b;
cout<<"Addition of two numbers::"<<endl<<c<<endl;
return 0;
}
Program 3

//to print Hello World 10 times


#include<iostream>
using namespace std;
int main()
{
for(int i = 0; i<10 ; i++) //for(initialisation; condition; increment/dec operation)
{
cout<<"\n Hello World"<<endl;
}
}
Program 4

#include<iostream>
using namespace std;
int main()
{
int a,b;
cout<<"Enter two numbers"<<endl;
cin>>a>>b;
if(a>b)
{
cout<<"a is largest";
}
else
{
cout<<"b is largest" ;
}
}
Unit 1_Programming Assignment

1. WAP in C++ to check whether the given number is odd or even.


2. WAP in C++ to check whether the given Character is a Vowel /Consonant /Digit /Special Symbol.
3. WAP in C++ to input basic salary of an employee and calculate gross salary according to given
conditions.
Basic Salary <= 10000 : HRA = 20%, DA = 80%
Basic Salary is between 10001 to 20000 : HRA = 25%, DA = 90%
Basic Salary >= 20001 : HRA = 30%, DA = 95% Using
(Gross Salary=Basic Salary + HRA + DA) Conditional
1. WAP in C++ to find the sum of first 10 natural numbers. and
2. WAP in C++ to find the perfect numbers between 1 and 500. Iterative
3. WAP in C++ to find the factorial of a number. statements
Unit 1_Assignment

1. Write down the difference between Procedure Oriented Programming and Object Oriented
Programming.
2. Explain basic concepts of OOPs?
3. Why OOP is popular? Name some commonly used Object Oriented Languages?
4. Name some major companies/applications that uses the concept of OOPs and how?
5. Explain Functions in C++ and its elements.
6. Explain the functioning of inline functions in C++.
7. What is Class Diagram? How can we justify the relationships between the classes?

You might also like