Programming with C++ (Open Elective-II)
Course Objectives:
1.To explore the principles of Object-Oriented
Programming (OOP).
2. To use the concept of inheritance and
polymorphism.
3. To understand the use of exception handling in
C++ programs.
4.To provide a foundation for advanced programming
using File handling and STL.
5.To provide lifelong learning attitude towards
problem solving
Course Outcomes: After learning the course, students will
be able to:
1. Identify the need of object-oriented programming to
solve computational problems.
2. Demonstrate the use of inheritance in object-oriented
programming.
3. Apply the concept of overloading and virtualization.
4. Illustrate exception handling in object-oriented
programming.
5. Discuss the use of input and output stream in C++.
6. Analyze the usage of template classes and the STL library
in C++.
Introduction of OOPs Concepts
Overview of procedural programming and
object-oriented programming,
Syntax of variables declaration,
Classes and objects,
Member functions,
memory management.
Case Study: Write a program in c++ to create an
employee class with appropriate features.
Introduction
A programming language is a set of rules that provides a way
of telling a computer what operations to perform
Programmers write instructions in various programming
languages to perform their computation tasks such as:
(i) Machine level Language
(ii) Assembly level Language
(iii) High level Language
Levels of Programming Languages
Machine Language:
● Uses binary code
● Machine-dependent
● Not portable
Assembly Language:
● Uses mnemonics
● Machine-dependent
● Not usually portable
High-Level Language (HLL):
● Uses English-like language
● Machine independent
● Portable (but must be compiled for different platforms)
● Examples: Pascal, C, C++, Java, Fortran, . . .
Characteristics of a programming Language
● A programming language must be simple, easy to learn and use,
have good readability, and be human recognizable.
● Programming language’s efficiency must be high so that it can be
easily converted into a machine code and its execution consumes
little space in memory.
● A programming language should be well structured and
documented so that it is suitable for application development.
● A programming language must be consistent in terms of syntax
and semantics.
Procedural programming paradigm
● This paradigm emphasizes on procedure in terms of underlying
machine model.
● Conventional programming, using 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 to be done such as reading, calculating and
printing.
● A number of functions are written to accomplish these tasks. The
primary focus is on functions.
Procedural programming paradigm
GLOBAL DATA GLOBAL DATA
FUNCTION-1 FUNCTION-2 FUNCTION-3
LOCAL DATA LOCAL DATA LOCAL DATA
Relationship of data and function in procedure oriented
programming
Object oriented programming
● The program is written as a collection of classes and object which are
meant for communication.
● The smallest and basic entity is object and all kind of computation is
performed on the object only.
● More emphasis is on data rather procedure. It can handle almost all
kind of real life problems which are today in scenario.
● 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 programming
HISTRY OF C++
Author of C++ is
Bjarne stroustrup
He invented this language in 1980's at
AT&T Bell Laboratories
All the C programs can be run
successfully using C++ compiler
POCEDURE OREINTED PROGRAMMING
• Emphasis is on doing things (algorithm).
• Large programs are divided into smaller programs known as
functions.
• Most of function shared global data.
• Data move openly around the system from function to
function.
• Employs top-down approach in program design.
Features of the Object Oriented programming
Emphasis is on data rather than procedure.
1.
Programs are divided into what are known as objects.
2.
Data structures are designed such that they characterize the objects.
3.
Functions that operate on the data of an object are tied together in the
4.
data structure.
Data is hidden and can’t be accessed by external functions.
5.
Objects may communicate with each other through functions.
6.
New data and functions can be easily added.
7.
Follows bottom-up approach in program design.
8.
Need of Object-Oriented Programming (OOP)
•Object oriented programming provides object, class, inheritance encapsulation, data
hiding, abstraction, etc.
•It is very easy to develop the software using the above object oriented concept.
•With the help of inheritance concept, we are able to remove the repeat code in the program.
•With the help of classes and objects we can easily divide the code in different components.
•We can develop the code which hides the data from other users or from other program.
•We can easily scale the software for more requirements.
•Software code reusability is possible with object oriented programming.
•They develop the software which focuses mainly on data which result more secure
software.
•Very easy to map the real world problem into programming.
BASIC CONCEPT OF OBJECT ORIENTED PROGRAMMING
•Object.
•Class.
•Data Abstraction.
•Data Encapsulation.
•Inheritance.
•Polymorphism.
All around us in the real
world are objects.
Each object has certain
characteristics and exhibits
certain behaviour
OBJECT
Data
Color : Black
Year : 2008
Actions
Start
Stop
Accelerate
Polygon objects Polygon class
Properties
Vertices
Border Color
Abstract Fill Color
into Methods
Draw
Erase
Move
Inheritance
It is the process of creating a new
class from an existing class
EXAMPLE OF INHERITANCE
BIRD
ATTRIBUTES
FEATHERS
LAY EGGS
FLYING BIRD NONFLYING BIRD
ATTRIBUTES ATTRIBUTES
………… …………
………… …...........
ROBIN EAGLE PENGUIN KIWI
ATTRIBUTES ATTRIBUTES ATTRIBUTES ATTRIBUTES
Benefits of Inheritance
POLYMORPHISM
POLYMORPHISM
COMPILE TIME RUN TIME
FUNCTION OPERATOR VIRTUAL
OVERLOADING OVERLOADING FUNCTION
POLYMORPHISM
Shape
Shape()
Circle Box Triangle
Draw (circle) Draw (box) Draw (triangle)
Encapsulation
Class
Private
Not accessible from outside
class
Accessible from outside class Public
Data Abstraction
Data abstraction is a process of identifying
Class
properties and methods related much to a
particular entity as relevant to the application
Methods
Why OOP’s Concept are Used?
The drawbacks of Traditional Programming approach are
✔ Unmanageable Programs
✔ Code Reusability not Optimum
✔ Problems in Modification of Data
✔ Difficulty in Implementation
Benefits of Object Oriented Programming approach
are -
• OOP offers better implementation
• OOP offers better data security
• OOP offers better code reusability
• OOP offers more flexibility
• OOP offers better manageable programs
• Large complexity in the software development
can be easily managed
• User defined datatypes can be easily constructed
• Data acquisition Systems
• Client/Server Computing
• Object –Oriented Database applications
• Artificial Intelligence and expert systems
• systems such as process control, temperature control etc.
• GUI based system such as Windows Applications
• Computer Aided Design and manufacturing Systems
Syntax variables
You can declare variables using the syntax −
datatype variable_name;
For example,
int my_var; float my_float;
The general rules for naming variables are:
•Names can contain letters, digits and underscores
•Names must begin with a letter or an underscore (_)
•Names are case-sensitive (myVar and myvar are different
variables)
•Names cannot contain whitespaces or special characters like !, #,
%, etc.
•Reserved words (like C++ keywords, such as int) cannot be used
as names
he example of declaring variable is given below:
1.int x;
2.float y;
3.char z;
35
C++ keywords
Cannot be used as identifiers or variable names
STRUCTURE OF C++ PROGRAM
Include Files
Class Declaration
Member Function Definition
Main Function Program
HEADER FILES
A lot of library functions are subdivided into number of
groups. This groups are called Header files.
Syntax : #include<headerfilename.h>
Examples: #include<iostream.h>
#include<process.h>
iostream -> Input/Output Stream Conio -> Console
Input/Output
# preprocessor directive
Class
Class: The building block of C++ that leads to Object-Oriented programming is a Class. It is
a user-defined data type, which holds its own data members and member functions, which
can be accessed and used by creating an instance of that class. A class is like a blueprint for
an object.
Members of class
Data members / attributes Member functions / method
In C++, there are three access specifiers:
•public - members are accessible from outside the class
•private - members cannot be accessed (or viewed) from
outside the class
•protected - members cannot be accessed from outside the
class, however, they can be accessed in inherited classes.
• class C {
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
};
int main() {
C O;
O.x = 25; // Allowed (public)
O.y = 50; // Not allowed (private)
return 0;
}
TO CREATE A NEW CLASS
SYNTAX :
class<classname>
{
private :
datatype var1;
datatype var2;
public :
<retu_type> func_name1(arguments);
<retu_type> func_name2(arguments);
};
create a object from the main()functions
Syntax:
classname<objectname1, objectname2,..>;
For Example :
class emp
{
private:
char name[25]; //Member Data
int empno;
float salary;
public:
void get_data() // Member Function
{
---------
}
void show_details()
{
-------------
------------
};
DEFINING MEMBER FUNCTION
• Member Function can be defined in two places:
1. Outside the class definition
2. Inside the class definition
Syntax of Outside the class definition
Return type class name :: function_name (arg list)
{
Function body
}
Syntax of Inside the class definition :-
Return type function_ name (arg list)
{
function body
}
How to call the function from main()
objectname.func_name(arguments);
Write a Program to calculate the area of a circle using class & Object
#include<iostream.h>
#include<conio.h>
class area
{
private:
int radius;
float area;
public:
void getdata()
{
cout<<"Enter the radius"<<endl;
cin>>radius;
}
void calculate()
{
area=3.14*radius*radius;
}
void showdata()
{
cout<<"The area of the circle is "<<area<<endl;
}
};
void main()
{
area r;
r.getdata();
r.calculate();
r.showdata();
getch();
Enter the Radius : 2
} The area of the circle is
SCOPE RESOLUTION OPERATOR
SCOPE RESOLUTION
OPERATOR ::
Used to define the member function
defined outside of the class
• // C++ program for Outside
the Class Definition // function defining using scope resolution
• class rectangle { operator "::"
int rectangle::area() { return (length *
• private: breadth); }
• int length;
int rectangle::perimeter()
• int breadth; {
return 2 * (length + breadth);
• public: }
• rectangle(int l, int b)
int main()
• { {
• length = l; // Creating object
rectangle r(2, 3);
• breadth = b; cout << "perimeter: " << r.perimeter()
• } << endl;
cout << "area: " << r.area() << endl;
• int area(); return 0;
}
• int perimeter();
• };
WITH ARGUMENT NO RETURN VALUES
#include<iostream.h>
void main()
{
int b,h;
void area(int,int);
cout<<endl<<"Enter Base and Height Values";
cin>>b>>h;
area(b,h);
cout<<endl<<"end";
}
void area(int x,int y)
{
float at;
at=0.5*x*y;
cout<<"area is :"<<at;
}
A function is a set of instruction used to perform
some kind of special task
cin
cout A series of Instructions that are to
getc() be executed more than once
putc()
USER DEFINED FUNCTION :
SYNTAX :
retu_datatype func_name(arguments)
{
Body of the function
statements;
return;
}
call the function from main() :
SYNTAX :
func_name(arguments );
C++ User-defined Function Types
For better understanding of arguments and return
values in functions, user-defined functions can be in
various forms like:
•Function with no argument and no return value
•Function with no argument but return value
•Function with argument but no return value
•Function with argument and return value
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
Line 1: #include <iostream> is a header file library that lets us work with
input and output objects, such as cout (used in line 5). Header files add
functionality to C++ programs.
Line 2: using namespace std means that we can use names for objects and
variables from the standard library.
NO ARGUMENT NO RETURN VALUES
#include<iostream.h>
#include<conio.h>
void main()
{
void message();
clrscr();
cout<<endl;"Welcome to C++";
message();
cout<<endl<<"end";
getch();
}
void message()
{
cout<<endl<<"Welcome to the Function";
}
Memory Management
Memory management is a process of managing
computer memory, assigning the memory space to
the programs to improve the overall system
performance.
Why is memory management required?
As we know that arrays store the homogeneous data,
so most of the time, memory is allocated to the array at
the declaration time. Sometimes the situation arises
when the exact memory is not determined until
runtime. To avoid such a situation, we declare an array
with a maximum size, but some memory will be
unused. To avoid the wastage of memory, we use the
new operator to allocate the memory dynamically at
the run time.
Memory Management Operators
In C language, we use the malloc() or calloc() functions to
allocate the memory dynamically at run time, and free()
function is used to deallocate the dynamically allocated
memory.
C++ also supports these functions, but C++ also defines
unary operators such as new and delete to perform the
same tasks, i.e., allocating and freeing the memory.
New operator
A new operator is used to create the object
while a delete operator is used to delete the
object.
When the object is created by using the new
operator, then the object will exist until we
explicitly use the delete operator to delete the
object. Therefore, we can say that the lifetime
of the object is not related to the block structure
of the program.
Syntax
pointer_variable = new data-type
The above syntax is used to create the object using the new
operator. In the above syntax, 'pointer_variable' is the name
of the pointer variable, 'new' is the operator, and 'data-type'
defines the type of the data.
Example 1:
int *p;
p = new int;
In the above example, 'p' is a pointer of type int.
Delete operator
When memory is no longer required, then it needs to be deallocated so that the memory can
be used for another purpose. This can be achieved by using the delete operator, as shown
below:
1.delete pointer_variable;
In the above statement, 'delete' is the operator used
to delete the existing object,
and 'pointer_variable' is the name of the pointer
variable.
In the previous case, we have created two pointers
'p' and 'q' by using the new operator, and can be
deleted by using the following statements:
1.delete p;
Advantages of OOPs
There are various advantages of object-oriented
programming.
❑OOPs provide reusability to the code and extend the use of
existing classes.
❑In OOPs, it is easy to maintain code as there are classes and
objects, which helps in making it easy to maintain rather
than restructuring.
❑It also helps in data hiding, keeping the data and
information safe from leaking or getting exposed.
❑Object-oriented programming is easy to implement.