OOPs With C - CSE 2001 - Unit 1
OOPs With C - CSE 2001 - Unit 1
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
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
But there is another very common way to structure C++ code: object-oriented
programming.
Object Oriented Approach
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
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
● 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
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
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
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:
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
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
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.
• 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
#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
#include <iostream>
using namespace std;
int main()
{
cout << "The cube of 3 is: " << cube(3) << "\n"; //calling
return 0;
}
#include <iostream>
using namespace std;
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
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
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.
● But before understanding how to handle exception, first let us understand what C++ does when an
exception occurs.
● 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.
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
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
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
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.
#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
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
#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;
swap(a,b);
a b a b
x y
20 10
a b
&x = a, &y = b
Example: 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; }
return 0;
}
Basic C++ Programs
Program 1
#include<iostream>
using namespace std;
int main()
{
cout<<"Hello World";
return 0;
}
Program 2
#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. 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?