Unit-1 Concepts of OOPS
What is object oriented programming? How it is differ
from procedure oriented programming?
Object oriented programming treats data as 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.
OOP allows decomposition of a problem into a number of entities called objects and
then builds data and function around these objects.
The organization of data and function in object oriented programs is shown in
following figure.
The data of an object can be accessed only by the functions associated with that
object. However, functions of one object can access the function of other objects.
Characteristics
1. Emphasis is on data rather than procedure.
2. Programs are divided into what are known as objects.
3. Data structures are designed such that they characterize the objects.
4. Functions that operate on the data of an object are tied together in the data
structure.
5. Data is hidden and cannot be accesses by external functions.
6. Object may communicate with each other through functions.
7. New data and functions can be easily added whenever necessary.
8. Follows bottom-up approach in program design.
Object Oriented Programming and Data Structure Page 1
Unit-1 Concepts of OOPS
Procedure Oriented Programming V/S Object Oriented
Programming
Procedure Oriented Object Oriented Programming
Programming
Divided In, POP, program is divided into In OOP, Program is divided into
into small parts called functions. parts called objects.
Importance In POP importance is not given to In OOP, importance is given to the
data but to functions as well as data rather than procedures or
sequence of action to be done. function because it works as a real
world
Approach POP follows Top Down approach. OOP follows Bottom Up approach.
Access POP does not have any access OOP has access specifier named
Specifiers specifier. public, private, protected etc.
Data In POP, Data can move freely from In OOP, Objects can move and
Moving function to function in the system. communicate with each other
through member function.
Expansion To add new data and function in OOP provides an easy way to add
POP is not so easy. new data and function.
Data Access In POP, most function uses Global In OOP, data can not move easily
data sharing that can be accessed from function to function. It can be
freely from function to function in kept public or private so we can
the system. control the access of data.
Data Hiding POP does not have any proper way OOP provides Data hiding so
for hiding data so it is less secure. provide more security.
Overloading In POP, Overloading is not In OOP, overloading is possible in
possible. the form of function overloading
and Operator Overloading.
Inheritance POP does not support inheritance. OOP support inheritance
Examples C, VB, FORTRAN, Pascal C++, JAVA, VB.NET, C#.NET
Object Oriented Programming and Data Structure Page 2
Unit-1 Concepts of OOPS
List out features of object oriented programming.
Explain any two of them.
Following are some features of Object Oriented Programming.
1. Objects
2. Classes
3. Data abstraction & Encapsulation
4. Inheritance
5. Polymorphism
6. Dynamic binding
7. Message passing
Object:
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 has to handle. They may also represent used defined data such as vectors,
time etc.
When program is executed, the objects interact by sending messages to one
another. For example, if “customer” and “account” are two objects in a program
then the customer object may send a message to the account object requesting for
the bank balance.
Each object contains data and code to manipulate the data. Following figure shows
two notations that are popularly used in object oriented programming.
The entire set of data and code of an object can be made a user-defined data type
with the help of a class.
Class:
Class is a user defined data type and objects are variable of type class. Once a class
has been defined we can create any number of objects belonging to that class.
Object Oriented Programming and Data Structure Page 3
Unit-1 Concepts of OOPS
Class wrapped data member and member functions.
The attributes of class called as data member and the functions that operate on
these data are called as member functions.
for example, mango, apple and orange are members of the class fruit.
Data Abstraction and Encapsulation:
The wrapping up of data and functions into a single unit (called class) is known as
encapsulation.
The data is not accessible to the outside world, and only those functions which are
wrapped in the class can access it.
The function provides the interface between the object’s data and the program. This
insulation of the data from direct access by the program is called data hiding or
information hiding.
Abstraction refers to the act of representing essential features without including the
background details or explanations.
Inheritance:
Inheritance is the process by which objects of one class acquire the properties of
objects of another class.
The concept of inheritance provides the idea of reusability. This means that we can
add additional features to an existing class without modifying it. This is possible by
deriving a new class from the existing one. The new class will have the combined
features of both the classes.
For example, the bird ‘robin’ is a part of the class ‘flying bird’ which is again a part
of the class ‘bird’. The principle behind this sort of division is that each derived class
shares common characteristics with the class from which it is derived as shown in
following figure.
Object Oriented Programming and Data Structure Page 4
Unit-1 Concepts of OOPS
Polymorphism:
Polymorphism is another important OOP concept. Polymorphism, a Greek term,
means the 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.
Operator Overloading: The process of making an operator to exhibit different
behaviors in different instances is known as operator overloading.
For example, the operation of addition. For two numbers, the operation will
generate a sum. If the operands are strings then the operation would produce a
third string by concatenation.
Method Overloading: A single function name can be used to handle different
number and different types of arguments. This is something similar to a particular
word having several different meaning depending on the context.
Using a single function name to perform different types of tasks is known as
function overloading.
Dynamic Binding
Binding refers to the linking of a procedure call to the code to be executed in
response to the call. Dynamic binding also known as late binding means that the
code associated with a given procedure call is not known until the time of the call at
run time.
Message Passing:
Objects communicate with one another by sending and receiving information to
each other. A message for an object is a request for execution of a procedure and
therefore will invoke a function in the receiving object that generates the desired
Object Oriented Programming and Data Structure Page 5
Unit-1 Concepts of OOPS
results. Message passing involves specifying the name of the object, the name of the
function and the information to be sent.
Benefits of OOPS
Through inheritance, we can eliminate redundant code and extend the use of
existing classes which is not possible in procedure oriented approach.
We can build programs from the standard working modules that communicate with
one another, rather than having to start writing the code from scratch which
happens procedure oriented approach. This leads to saving of development time
and higher productivity.
The principle of data hiding helps the programmer to build secure programs that
cannot be invaded by code in other parts of the program.
It is possible to have multiple instances of object to co-exist without any
interference.
It is possible to map objects in the problem domain to those in the program.
It is easy to partition the work in a project based on objects .
The data-centered design approach enables us to capture more details of a model in
implementable from.
Object oriented systems can be easily upgraded from small to large systems.
Message passing techniques for communication between objects makes the
interface descriptions with external systems much simpler.
Software complexity can be easily managed.
Input and Output Operator in C++
In C++, input and output (I/O) operators are used to take input and display output.
Output Operator: The operator used for displaying the output is known as
the insertion or put to operator (<<).
The statement,
cout<<”C++ is better than C”;
cause the string in quotation marks to be displayed on the screen.
The operator << is called the insertion or put to operator. It inserts the contents of
the variable on its right to the object its left.
Object Oriented Programming and Data Structure Page 6
Unit-1 Concepts of OOPS
Screen
cout << “C++”
Object Insertion Variable
t Operator
Input Operator: The operator used for taking the input is known as
the extraction or get from operator (>>).
The input operator, commonly known as the extraction operator (>>), is used with
the standard input stream, cin.
It extracts or takes the values from the keyboard and assigns it to the variable on its
right as shown in following diagram.
The statement cin >>number1 is an input statement and causes the program to wait
for the user to type in a number.
Extraction
Object Operator Variable
cin >> 45.5
Keyboard
Cascading of I/O Operators
The cascading of the input and output operators refers to the consecutive
occurrence of input or output operators in a single statement.
E.g. , cout<<”Sum = ”<<sum << “\n”;
In above example insertion operator used two time to print the sum. That is
cascading of output operator.
We can also cascade input operator
E.g., cin>>a>>b;
In above example extraction operator can be used multiple times. In single sentence
we can insert value of a and b variable.
Object Oriented Programming and Data Structure Page 7
Unit-1 Concepts of OOPS
Various library (Header) file require for C++
C language has numerous libraries that include predefined functions to make
programming easier. In C language, header files contain the set of predefined
standard library functions.
Your request to use a header file in your program by including it with the C
preprocessing directive “#include”. All the header file have a ‘.h’ an extension.
By including a header file, we can use its contents in our program.
C++ also offers its users a variety of functions, one of which is included in header
files.
In C++, all the header files may or may not end with the “.h” extension but in C, all
the header files must necessarily end with the “.h” extension.
A header file contains:
o Function definitions
o Data type definitions
o Macros
It offers the above features by importing them into the program with the help of a
preprocessor directive “#include”. These preprocessor directives are used for
instructing compiler that these files need to be processed before compilation.
In C++ program has the header file which stands for input and output stream used
to take input with the help of “cin” and “cout” respectively.
There are of 2 types of header file:
o Pre-existing header files: Files which are already available in C/C++
compiler we just need to import them.
o User-defined header files: These files are defined by the user and can be
imported using “#include”.
Standard Header Files and their Uses:
1. #include<stdio.h>: It is used to perform input and output operations
using functions scanf() and printf().
2. #include<iostream>: It is used as a stream of Input and Output using cin
and cout.
Object Oriented Programming and Data Structure Page 8
Unit-1 Concepts of OOPS
3. #include<string.h>: It is used to perform various functionalities related
to string manipulation like strlen(), strcmp(), strcpy(), size(), etc.
4. #include<math.h>: It is used to perform mathematical operations
like sqrt(), log2(), pow(), etc.
5. #include<iomanip.h>: It is used to access set() and setprecision()
function to limit the decimal places in variables.
6. #include<signal.h>: It is used to perform signal handling functions
like signal() and raise().
7. #include<stdarg.h>:It is used to perform standard argument functions
like va_start() and va_arg(). It is also used to indicate start of the variable-
length argument list and to fetch the arguments from the variable-length
argument list in the program respectively.
8. #include<errno.h>: It is used to perform error handling operations
like errno(), strerror(), perror(), etc.
9. #include<fstream.h>: It is used to control the data to read from a file as
an input and data to write into the file as an output.
10. #include<time.h>: It is used to perform functions related to date()
and time() like setdate() and getdate(). It is also used to modify the system
date and get the CPU time respectively.
11. #include<float.h>: It contains a set of various platform-dependent
constants related to floating point values. These constants are proposed by
ANSI C. They allow making programs more portable. Some examples of
constants included in this header file are- e(exponent), b(base/radix), etc.
12. #include<limits.h>: It determines various properties of the various
variable types. The macros defined in this header, limits the values of various
variable types like char, int, and long. These limits specify that a variable
cannot store any value beyond these limits, for example an unsigned
character can store up to a maximum value of 255.
Structure of C++ Program
Typical C++ program would contain four sections as shown in following diagram.
Object Oriented Programming and Data Structure Page 9
Unit-1 Concepts of OOPS
Include Files
Class Declaration
Member Function
Definitions
Main Function Program
These sections may be places in separate code files and then compiled
independently or jointly.
Basic Data Types
1. Built-in Type
Integer: Keyword used for integer data types is int. Integers typically requires 4
bytes of memory space and ranges from -2147483648 to 2147483647.
Character: Character data type is used for storing characters. Keyword used for
character data type is char. Characters typically requires 1 byte of memory space
and ranges from -128 to 127 or 0 to 255.
Boolean: Boolean data type is used for storing boolean or logical values. A boolean
variable can store either true or false. Keyword used for boolean data type is bool.
Floating Point: Floating Point data type is used for storing single precision
floating point values or decimal values. Keyword used for floating point data type
is float. Float variables typically requires 4 byte of memory space.
Double Floating Point: Double Floating Point data type is used for storing
double precision floating point values or decimal values. Keyword used for double
floating point data type is double. Double variables typically require 8 byte of
memory space.
Object Oriented Programming and Data Structure Page 10
Unit-1 Concepts of OOPS
void: Void means without any value. void data type represents a valueless entity.
Void data type is used for those function which does not returns a value.
2. User Define Data Type
Structure: structure is a user-defined data type. A structure creates a data type
that can be used to group items of possibly different types into a single type.
The only difference between a structure and a class is that structure members have
public access by default and class members have private access by default, you can
use the keywords class or struct to define equivalent classes.
Union: A union in C programming is a user defined data type which may hold
members of different sizes and type. Union uses a single memory location to hold
more than one variables. However, only one of its members can be accessed at a
time and all other members will contain garbage values.
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.
Enumerated: Enum is a user defined data type where we specify a set of values
for a variable and the variable can only take one out of a small set of possible values.
We use enum keyword to define a Enumeration.
enum direction {East, West, North, South}dir;
Here Enumeration name is direction which can only take one of the four specified
values, the dir at the end of the declaration is an enum variable.
Here I have assigned the value West to the enum variable dir and when I displayed
the value of dir it shows 1. This is because by default the values are in increasing
order starting from 0, which means East is 0, West is 1, North is 2 and South is 3.
enum direction {East, West, North, South}dir;
int main()
{
dir = West;
cout<<dir;
return 0;
}
Object Oriented Programming and Data Structure Page 11
Unit-1 Concepts of OOPS
3. Derived Data Types
Data types that are derived from the built-in data types are known as derived data
types. The various derived data types provided by C++ are as following:
Array: An array is a set of elements of the same data type that are referred to by
the same name. All the elements in an array are stored at contiguous (one after
another) memory locations and each element is accessed by a unique index or
subscript value. The subscript value indicates the position of an element in an array.
Function: A function is a self-contained program segment that carries out a
specific well-defined task. In C++, every program contains one or more functions
which can be invoked from other parts of a program, if required.
Reference: A reference is an alternative name for a variable. That is, a reference is
an alias for a variable in a program. A variable and its reference can be used
interchangeably in a program as both refer to the same memory location.
Pointer: A pointer is a variable that can store the memory address of another
variable. Pointers allow to use the memory dynamically. That is, with the help of
pointers, memory can be allocated or de-allocated to the variables at run-time, thus,
making a program more efficient.
What is typedef?
C++ allows you to define explicitly new data type names by using the keyword
typedef. Using typedef doest not actually create a new data class, rather it defines a
new name for an existing type.
typedef type name;
Where type is any C++ data type and name is the new name for this type. This
defines another name for the standard type of C++. For example, you would create
a new name for float values by using the following statement :
typedef float amount;
New name for the type float has be created through typedef.
This statement tells the compiler to recognize amount as an alternative name for
float.
Object Oriented Programming and Data Structure Page 12
Unit-1 Concepts of OOPS
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
typedef int integer;
/* now you can easily use integer to create
* variables of type int like this */
integer num1, num2, sum;
cout<<"Enter two number: ";
cin>>num1>>num2;
sum=num1+num2;
cout<<"Sum = "<<sum;
getch();
}
Explain reference variable. Give its application with
example.
C++ introduces a new kind of variable known as Reference Variable. It provides an
alias (alternative name) for a previously defined variable.
A reference variable must be initialized at the time of declaration.
When a reference is created, you must tell it which variable it will become an alias
for. After you create the reference, whenever you use the variable, you can just treat
it as though it were a regular integer variable.
But when you create it, you must initialize it with another variable, whose address it
will keep around behind the scenes to allow you to use it to modify that variable.
Syntax:
Datatype &reference_variable = regular_variable;
Regular_variable is a variable that has already initialized, and reference_variable
is an alternative name(alias) to represent the regular_variable
int main()
{
int student_age=10;
int &age=student_age; // reference variable
cout<< " value of student_age :"<< student_age << endl;
cout<< " value of age :"<< age << endl;
Object Oriented Programming and Data Structure Page 13
Unit-1 Concepts of OOPS
age=age+10;
cout<<"\nAFTER ADDING 10 INTO REFERENCE VARIABLE \n";
cout<< " value of student_age :"<< student_age << endl;
cout<< " value of age :"<< age << endl;
return 0;
}
Main Function in C++
main() function is the entry point of any C++ program. It is the point at which
execution of program is started. When a C++ program is executed, the execution
control goes directly to the main() function. Every C++ program have a main()
function.
itn main()
{
//Program Body
return 0;
}
In C++, the main() returns a value of type int to the operating system. The
functions that have a return value should use the return statement for termination.
Concept of String
Character Array
String is actually a one-dimensional array of characters which is terminated by
a null character '\0'.
Thus a null-terminated string contains the characters that comprise the string
followed by a null.
The following declaration and initialization create a string consisting of the word
"Hello".
char str[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
To hold the null character at the end of the array, the size of the character array
containing the string is one more than the number of characters in the word
"Hello."
Object Oriented Programming and Data Structure Page 14
Unit-1 Concepts of OOPS
You can write the above statement as follows −
char str[] = "Hello";
Following is the memory presentation of above defined string
The C++ compiler automatically places the '\0' at the end of the string when it
initializes the array.
int main ()
{
char str[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
cout << "String is : ";
cout << str << endl;
char str1[100];
cout << "Enter a string: ";
cin >> str1;
cout << "You entered: " << str1 << endl;
return 0;
}
Pointer to Character Array
Pointer can also be used to create strings. Pointer variables of char type are treated
as string. Pointers are very useful in accessing character arrays. The character
strings can be assigned with a character pointer.
Example :
char array[ ] = “Love India”; //array version
char *str = "Hello";
This creates a string and stores its address in the pointer variable str. The pointer str
now points to the first character of the string "Hello". Another important thing to
note that string created using char pointer can be assigned a value at runtime.
Object Oriented Programming and Data Structure Page 15
Unit-1 Concepts of OOPS
char *str;
str = "hello"; //Legal
//The content of the string can be printed by cout
cout<<str;
Here str is pointer to the string, it is also name of the string. Therefore we do not
need to use indirection operator *.
Use of string.h and its important functions:
C++ support a large number of string handling functions that can be used to carry
out many of the string manipulations. These functions are packaged in the string.h
library.
Hence you must include string.h header file in your programs to use these
functions.
The following are the most commonly used string handling functions.
1. strcmp()
strcmp() is a built-in library function and is declared in <string.h> header file.
This function takes two strings as arguments and compare these two strings
lexicographically. This function will return the ASCII difference between first
matching characters of two strings.
Syntax:
int strcmp(const char *leftStr, const char *rightStr );
Here, function srtcmp takes two strings as parameters and returns an integer value
based on the comparison of strings.
strcmp() compares the two strings lexicographically means it starts comparison
character by character starting from the first character until the characters in both
strings are equal or a NULL character is encountered.
If first character in both strings are equal, then this function will check the second
character, if this is also equal then it will check the third and so on.
This process will be continued until a character in either string is NULL or the
characters are unequal.
This function can return three different integer values based on the
comparison:
Object Oriented Programming and Data Structure Page 16
Unit-1 Concepts of OOPS
I. Zero ( 0 ): A value equal to zero when both strings are found to be identical.
That is, That is, All of the characters in both strings are same.
II. Greater than zero ( >0 ): A value greater than zero is returned when the
first not matching character in leftStr have the greater ASCII value than the
corresponding character in rightStr.
III. Less than Zero ( <0 ): A value less than zero is returned when the first not
matching character in leftStr have lesser ASCII value than the corresponding
character in rightStr.
2. strcat()
strcat() is a built-in library function and is declared in <string.h> header file.
The strcat() function in C++ appends a copy of a string to the end of another string.
Syntax:
char* strcat( char* dest, const char* src );
The strcat() function takes two arguments: dest and src. This function appends a
copy of the character string pointed to by src to the end of string pointed to by dest.
The null terminating character at the end of dest is replaced by the first character
of src and the resulting character is also null terminated.
This function returns dest, the pointer to the destination string.
3. strcpy()
strcat() is a built-in library function and is declared in <string.h> header file.
This function copies the entire string to the destination string. It doesn’t append the
source string to the destination string. In other words, we can say that it replaces
the content of destination string by the content of source string.
Syntax:
char* strcpy(char* dest, const char* src);
Here dest pointer is the destination array where the content is to be copied and src
is string which will be copied.
After copying the source string to the destination string, the strcpy() function
returns a pointer to the destination string.
Object Oriented Programming and Data Structure Page 17
Unit-1 Concepts of OOPS
4. strlen()
strcat() is a built-in library function and is declared in <string.h> header file.
The strlen() function in C++ returns the length of the given string.
Syntax:
size_t strlen( const char* str );
The strlen() takes a null terminated byte string str as its argument and returns its
length. The length does not include the null character.
5. strrev()
strcat() is a built-in library function and is declared in <string.h> header file.
The strrev() function is used to reverse the given string.
Syntax:
char *strrev(char *str);
Here str is the given string which is needed to be reversed.
This function returns the string after reversing the given string.
Object Oriented Programming and Data Structure Page 18