UNIT-1
OBJECT
ORIENTED
PROGRAMMING
Syllabus (Unit-1)
Introduction to C++, C++ Standard Library,
Illustrative Simple C++ Programs. Header
Files, Namespaces, Application of object
oriented programming.
Object Oriented Concepts, Introduction to
Objects and Object Oriented Programming,
Encapsulation, Polymorphism, Overloading,
Inheritance, Abstract Classes, Accessifier
(public/ protected/ private), Class Scope and
Accessing Class Members, Controlling Access
Function, Constant, Class Member, Structure
2
and Class
Introduction to C++
C++ is an Object Oriented Language.
It was developed by Bjarne Stroustrup at
AT&T’s Bell Laboratories.
Earlier it was called ‘C with Classes’ but
later the name was changed to ‘C++’.
C++ is a superset of C, so that most C
programs are also C++ programs.
3
Header Files in C++
A header file in C/C++ contains:
Function definitions
Data type definitions
Macros
Header files offer these features by
importing them into your program
with the help of a preprocessor
directive called #include.
These preprocessor directives are
4 responsible for instructing the C/C+
…contd
Basically, header files are of 2
types:
Standard library header files
These are the pre-existing header files
already available in the C/C++ compiler.
User-defined header files:
Header files can be designed by the user by
saving the file name as .h extension.
There are a total of 49 header files in
5 the Standard C++ Library
Header files in C/C++
#include<stdio.h>
Standard input-output header
Used to perform input and output operations in
C like scanf() and printf().
#include<string.h>
String header
Perform string manipulation operations like
strlen and strcpy.
#include<conio.h>
Console input-output header
Perform console input and console output
operations like clrscr() to clear the screen and
getch() to get the character from the keyboard.
6
Header files in C/C++
#include<stdlib.h>
Standard library header
Perform standard utility functions like dynamic memory
allocation, using functions such as malloc() and calloc().
#include<math.h>
Math header
Perform mathematical operations like sqrt() and pow().
To obtain the square root and the power of a number
respectively.
#include<ctype.h>
Character type header
Perform character type functions like isaplha() and isdigit().
To find whether the given character is an alphabet or a digit
respectively.
#include<time.h>
Time header
Perform functions related to date and time like setdate() and
getdate().
7 To modify the system date and get the CPU time respectively.
Header files in C/C++
#include<assert.h>
Assertion header
It is used in program assertion functions like assert().
To get an integer data type in C/C++ as a parameter
which prints stderr only if the parameter passed is 0.
#include<locale.h>
Localization header
Perform localization functions like setlocale() and
localeconv().
To set locale and get locale conventions respectively.
#include<signal.h>
Signal header
Perform signal handling functions like signal() and
raise().
To install signal handler and to raise the signal in the
8 program respectively
Header files in C/C++
#include<setjmp.h>
Jump header
Perform jump functions.
#include<stdarg.h>
Standard argument header
Perform standard argument functions like va_start and
va_arg().
To indicate start of the variable-length argument list
and to fetch the arguments from the variable-length
argument list in the program respectively.
#include<errno.h>
Error handling header
Used to perform error handling operations like errno().
To indicate errors in the program by initially assigning
the value of this function to 0 and then later changing
9 it to indicate errors.
Header Files in C++
Following are some C++ header
files which are not supported in C-
#inlcude<iostream>
Input Output Stream
Used as a stream of Input and Output.
#include<iomanip.h>
Input-Output Manipulation
Used to access set() and setprecision().
#include<fstream.h>
File stream
Used to control the data to read from a
1
file as an input and data to write into
0
the file as an output.
General form of a C++
program
// Program description
#include directives
int main()
{
constant declarations
variable declarations
executable statements
return 0;
}
1
1
C++ Character Set
A C++ program is a collection of number of
instructions written in a meaningful order.
Further, instructions are made up of
keywords, variables, functions, objects etc.
All these uses C++ character set as shown
below:
1
2
Tokens in C++
Smallest individual unit in a program is
called Token.
C++ defined 6 types of tokens
1
3
C++ Keywords
Each keyword has a predefined purpose in the
language.
Keywords cannot be used as variable and constant
names.
There are 63 keywords in C++ as follows:
1
4
C++ identifiers
An identifier is a name for a variable, constant,
function, etc.
It consists of a letter followed by any sequence of
letters, digits, and underscores.
Rules for writing identifiers:
First letter must be an alphabet or underscore.
From second character onwards, any combination of
digits, alphabets or underscores are allowed.
No other symbol except digits, alphabets or underscores
is allowed.
Keywords cannot be used as identifiers.
Maximum length of identifier depends upon the compiler
used.
Examples:
1
5
Variables
It is a named location in memory that is
used to hold a value that can be modified
in the program by the instruction.
All the variables must be declared before
they can be used.
General form:
datatype variable_name [list];
Unlike C, C++ allows to declare variable
anywhere in the program before its use.
1
6
Data Types in C++
1
7
C++ comments
Comments are explanatory notes which are
ignored by the compiler.
There are two ways to include comments in a
program:
// A double slash marks the start of
a //single line comment.
/* A slash followed by an asterisk marks
the start of a multiple line comment. It
ends with an asterisk followed by a
slash. */
1
8
Programming Style
C++ is a free-format language, which
means that:
Extra blanks (spaces) or tabs before or after
identifiers/operators are ignored.
Blank lines are ignored by the compiler just
like comments.
Code can be indented in any way.
There can be more than one statement on a
single line.
A single statement can continue over
several lines.
1
9
A simple C++ program
2
0
Output Operator
cout represents the standard output
stream.
The operator << is called insertion
operator or put to operator.
2
1
Example
2
2
Input Operator
cin represents the standard input stream.
The operator >> is called extraction
operator or get from operator.
2
3
Example Program
2
4
Program to add two numbers
2
5
Structure & Union
Structure and Union both are a collection of
heterogeneous data elements.
struct book
{
char title[25];
char author[25];
int pages;
float price;
} book1, book2,book3;
union result
{
int marks;
char grade;
2 float percent;
6
};
2
7
Difference between Structure & Union
Structure Union
A structure is defined with A union is defined with union
struct keyword. keyword.
The members of a union can be
All members of structure can
be manipulated manipulated one at a time.
The size of a union object is
simultaneously.
equal to the size of largest
Size of structure object is
member object.
equal to the sum of individual
sizes of member objects.
Union members share common
Structure members are
memory space for their exclusive
allocated distinct memory usage.
locations. Unions are considered memory
Structures are not memory efficient where members are not
efficient as compared to required to be accessed
unions. simultaneously.
2
8
using Structure
2
9
3
0
3
1
Enumerated data type
User defined data type which provide a way of attaching
names to numbers.
enum automatically enumerates a list of words by assigning
them values 0,1,2,….
enum shape{circle, square, triangle};
enum color{red, blue, green, yellow};
enum position{on, off};
We can use these as typenames also like:
shape ellipse;
color background;
The integers values assigned to enumerators can also be
over-ride. For example:
3
enum color{red,blue=4,green=8};
2 enum color{red=5,blue,green};
Output
2
3
3
3
4
3
5
Derived data types
Arrays
Functions
Pointers
Reference
3
6
Pointers
int *ip; //int pointer
ip=&x; //address of x assigned to ip
*ip=10; //10 assigned to x through indirection
char * const ptr1=‘Good’; //constant pointer
Address of ptr1 cannot be modified.
3
7
Reference variables
Reference variable provides as alias name for a
previously defined variable.
Syntax:
Data-type & reference-name = variable-name
eg.
float total=100;
float & sum = total;
• sum is the alternative name declared to represent
total.
• Any modification or assignment applied to either
variable will effect both.
• Reference variable must be initialized at the time of
declaration.
3
8
Memory Management
Operators
New
To allocate memory dynamically.
Delete
To deallocate memory as and when required.
An object created using new will remain in
existence until it is explicitly destroyed by
delete.
3
9
Using NEW operator
General form of using new operator:
Pointer-variable = new data-type;
Eg.
P = new int; //p is a pointer of type int
Q = new float; //q is a pointer of type float
Here, p and q must be already declared.
Alternatively,
int *p = new int;
float *q = new float;
*p = 25;
*q = 7.5;
Assigns 25 to newly created int object and 7.5 to float object.
OR
Pointer-variable = new data-type(value);
int *P = new int(25);
4 float *q = new float(7.5);
0
Using DELETE operator
delete pointer-variable;
delete p;
delete q;
4
1
Manipulators
Endl
causes a linefeed to be inserted as new line
character (“\n”)
Setw
Specifies a field width for printing the value of a
variable and make it right justified.
4
2
4
3
using namespace std
“using namespace std”
means
we use the namespace named
std.
“std” is an abbreviation for
standard which means
we use all the things with in
“std” namespace.
4
4
Features of Object
Oriented Programming in
C++
Procedure Oriented
Programming
Conventional programming such as
FORTRAN, COBOL, C use procedure oriented
programming.
The number of functions are written to
accomplish various tasks.
Employs top down approach.
Large programs are divided in small
programs known as functions.
Most functions share global data & data
moves freely from one function to another.
4
6
Structure of Procedure Oriented
Programs
4
7
Relationship of Data and
Functions in Procedural
Programming
4
8
OBJECT ORIENTED PROGRAMMING
The object oriented approach is used to remove
the flaws encountered in procedure oriented
approach.
OOP treats data as a critical element & doesn’t
allow it to flow freely around the system.
It ties data more closely to the functions that
operate on it.
OOP allows decomposition of a problem into a
number of entities known as objects and then
builds data and functions around these objects.
The data of an object can be accessed only by
the functions associated with that object,
however, functions of one object can access the
4
9
functions of other objects.
Features of OOP
Emphasis is on data rather than procedure.
Programs are decomposed into various entities
known as objects.
Functions that operate on data of an object are
tied together.
Data is hidden and cannot be accessed by
external functions.
Objects may communicate with each other
through functions.
New data and functions may be added easily
as per necessity.
Follows bottom up approach in program
5
0 design.
Organization of data and functions
in OOP
5
1
Applications of OOP
Real Time Systems.
Simulation and Modeling.
Object oriented databases.
AI and Expert System.
Neural Networks and parallel
programming.
Decision support and office
automation systems etc.
5
2
FEATURES OF OOP
Various features of object oriented
programming are:
Objects
Classes
Data Abstraction and Encapsulation
Inheritance
Polymorphism
Dynamic Binding
Message Passing
5
3
OBJECTS
Objects are the basic run time entities in
an object oriented system.
They may represent a person, a place, a
bank account or any other item that the
program has to handle.
An object takes space in memory and
have an associated address like a
structure in C.
During execution, objects interacts by
sending messages to each other.
Each object contains data and the code
5
4
to manipulate the data.
REPRESENTING AN OBJECT
Object: STUDENT
DATA
Name
DOB
Marks
………
FUNCTIONS
Total
Average
Display
………..
5
5
CLASSES
A class is a collection of objects of similar types
e.g. mango, apple are objects of class
Fruit
Classes are user defined data types and
behaves like built-in types.
Any number of objects can be created after
defining a class.
Syntax:
fruit mango;
5
6 Syntax for creating an object is similar to
ENCAPSULATION
The wrapping up of data and functions
into a single unit is called
Encapsulation.
Data is not accessible to the outside
world.
Only the functions that are wrapped in
the class can access it.
5 It is called Data Hiding or Information
7
DATA ABSTRACTION
Representing essential details without
including background details is called
Abstraction.
Classes are also known as Abstract
Data Types (ADT).
The variables or attributes are called
Data Members because they hold
information.
5
8
The functions that operate on these
INHERITANCE
The property by which objects of one
class acquire the properties of objects of
another class.
It supports Reusability.
A new class can be derived from the
existing class by adding additional
features to the existing class without
modifying it.
5
9 The new class will have combined
BIRD
Attributes
Feathers
Lays eggs
FLYING BIRD NON FLYING BIRD
Attributes Attributes
………….. …………..
………….. …………..
ROBIN SWALLOW PENGUIN KIWI
Attributes Attributes Attributes Attributes
………….. ………….. ………….. …………..
………….. ………….. ………….. …………..
6
0
TYPES OF INHERITANCE
Single Inheritance
Multiple Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Hybrid Inheritance
6
1
POLYMORPHISM
Ability to take more than one form.
An operation may exhibit different
behavior in different instances.
The behavior depends upon the types of
data used in the operation.
Types of Polymorphism:
OPERATOR OVERLOADING
FUNCTION OVERLOADING
6
2
OPERATOR OVERLOADING
Process of making an operator to exhibit
different behavior in different instances
is called Operator Overloading.
E.g. Consider the addition operation:
for 2 numbers, the operation will generate a
sum
If the operands are strings, the operation will
produce a third string by concatenation.
6
3
Function Overloading
Using a single function name to perform
different types of tasks is called
Function Overloading.
Known as Function Polymorphism.
All the functions having same name
contains different argument lists.
Correct function to be invoked depends
upon the number and type of
6 arguments.
4
Shape
Draw()
Triangle Square
Circle Object Object Object
Draw (circle) Draw Draw
(triangle) (square)
6
5
6
6
DYNAMIC BINDING
Also called Late Binding.
It means that the code associated with a
given procedure call is not known until
the time of call at run time.
Associated with Polymorphism and
Inheritance
6
7
MESSAGE PASSING
Objects in Object Oriented Programming
communicate with each other by
sending and receiving information to
and from other objects.
A message for an object is a request for
the execution of a procedure.
Message passing involves specifying the
name of the object, name of the function
6
8
and information to be sent.
numbers
6
9
Scope Resolution Operator
The operator :: is called scope resolution operator.
It is used for two purposes.
For accessing global variables
Identifying class members to which class they belong
The scope of a variable extends from the point of its
declaration till the end of the block containing the
declaration.
The variable is local to that block.
If a global variable also exists with same name as
the local variable, then local variable will be called
by default within that block.
Scope resolution operator helps to access the global
variable inside the block.
7 Syntax: :: variable-name
0
Scope Resolution Operator
7
1
7
2
Functions in C++
A function is a block of code that performs a specific
task.
There are two types of functions:
Standard library functions (Predefined in C++)
User-defined function ( Created by users)
Basic Syntax:
return-type: suggests what function will return
function-name: name of the function
Parameters: variables to hold values of arguments
passed while function is called. A function may or may not
contain parameters.
Function body: part where the code statements are
7
3 written
Declaring, Defining and Calling
a function
A function declaration tells the compiler about a
function's name, return type, and parameters.
Syntax:
A function definition provides the actual body of the
function.
Syntax:
To use a function, we have to call or invoke that
function.
When a program calls a function, program control is
transferred to the called function.
A called function performs defined task and when it’s
return statement is executed or when its function-ending
7 closing brace is reached, it returns program control back
4 to the calling program.
7
5
Inline Functions
When a function is called it performs a
series of instructions:
Jumping to the function
Saving registers
Pushing arguments into stack
Returning to calling function
This might be an overhead if function is
small.
Inline functions can to be used as a
solution for this.
7
6
Inline Functions
It is a function that is expanded in line when it is invoked.
The compiler replaces the function call with corresponding function
code.
Syntax:
inline function-header
{
function body
}
Eg.
inline double cube(double a)
{
return (a*a*a);
}
It can by invoked by the statement like:
c=cube(3.0);
7
7
All inline functions must be defined before
they are called.
There are certain situations where inline
expansion may not work:
For function returning values, if a loop,
switch or goto exists.
For function not returning values, if a
return statement exists.
If function contain static variables.
If inline functions are recursive.
7
8
Program: Inline Function
7
9
Default Arguments
C++ allows to call a function without
specifying all its arguments.
The function assigns a default value to the
parameter which does not have a matching
argument in the function call.
Default values are specified when the
function is declared.
8
0
8
1
Classes
A class is a way to bind the data and its
associated functions together.
General form of class declaration:
class class_name
{ private:
variable declarations;
function declarations;
public:
variable declarations;
function declarations;
8
2
};
Visibility Labels
Private
Can be accessed from within the class.
Use of keyword is optional.
Class members are by default private.
Public
Can be accessed from outside the class also.
If both labels are missing, by default, all the
members of the class are private.
8
3
Data hiding in classes
8
4
Accessing class members
General form:
[Link]-name (actual-arguments);
Eg.
[Link](100,75.5);
[Link]();
8
5
Defining member functions
Member functions can be defined in two
places:
Outside the class definition
Inside the class definition
8
6
8
7
Nesting of Member Functions
8
8
Private Member Functions
A private member function can only be
called by another function that is a member
of its class.
An object of the class cannot call the
private member function.
8
9
Memory allocation for objects
Memory space to members of class is
allocated as:
Member functions
When they are defined as a part of class
specification.
All the objects of that class use the same member
functions.
Data members
When the objects of the class are created.
Separate space is allocated to each data member
for each object.
9
0
9
1
Static Data Members
A static data member has following
characteristics:
Initialized to zero when first object of the
class is created.
Cannot be initialized in any other way.
Only one copy of the static member is
created and shared by all objects of the class.
Its lifetime is the entire program.
9
2
9
3
9
4
Output
9
5
9
6
Static Member Functions
A static member function can have access
to only static data members declared in the
same class.
Static member function can be called using
the class name as:
class-name :: function-name;
9
7
9
8
9
9
Array of Objects
Array of variables of type class can also be
declared.
These variables are called array of objects.
1
0
1
0
1
0
1
0
Objects as function arguments
1
0
1
0
Accessing members of objects
within a called function
1
0
End of
Unit-I