Introduction to Object-Oriented Programming
Introduction to Object-Oriented Programming
Introduction to OOP’s
- Introduction to oop’s
- Object oriented programming
- Basic concept of oop’s
- Benefits of oop’s
INTRODUCTION TO OOP’S
C++ is an object oriented programming language. It was developed by Bjarne
Stroustrup at AT & T Bell Laboratories in the early 1980’s. stroustrup, an admirer of
Simula67 and a strong supporter of C, wanted to combine the best of both the languages
and create a more powerful language that could support object oriented programming
features and still retain the power and elegance of C. the result was C++. However, later
in 1983, the name was changed to C++. The idea of C++ comes from the C increment
operator ++, thereby suggesting that C++ is an augmented (incremented) version of C.
C++ is a superset of C. Most of what we already know about C applies to C++ also.
Therefore, almost all C programs are also C++ programs.
The most important facilities that C++ adds on to C are classes, inheritance, function
overloading, and operator overloading. These features enable creating of abstract data
types, inherit properties from existing data types and support polymorphism, thereby
making C++ a truly object oriented language. C and C++ both are middle level
languages.
1
Procedure oriented programming
2
OBJECT ORIENTED PROGRAMMING (OOP)
Definition:
“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 templates for creating copies of such modules on
demand”
Object oriented programming (OOP) is an approach to program organization and
development that attempts to eliminate some of the pitfalls of conventional programming
methods by incorporating the best of structured programming features with several
powerful new concepts. It is a new way of organizing and developing programs and has
nothing to do with any particular language.
- 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.
- OOP allows decomposition of a problem into a number of entities called objects
and then builds data and functions around these objects.
- An object is considered to be a partitioned area of computer memory that
stores data and set of operations that can access that data.
3
Organization of data and functions in OOP
.
OBJECT
- Objects are basic run time entities in an object oriented system. (e.g. person, a
place, a bank account, etc)
- Objects are variables of the type class
- They may also represent user defined data such as vectors, time and lists.
- Objects take up space in the memory and have an associated address like a record
in a structure in C.
- When a program is executed, the objects interact by sending messages to one
another.
- Objects can interact without having to know details of each others data or code.
- Objects contain data and code to manipulate the data.
4
Object: student
DATA
Name
Date of birth
Marks
FUNTIONS
Total
Average
Display
CLASSES
- The entire set of data and code of an object can be made a user-defined data type
with the help of a class.
- A class is thus a collection of objects of similar type.
- Classes are user defined data types and behave like the built in types of a
programming language.
- The syntax used to create an object is no different than the syntax used to create
an integer object in C.
E.g.: if ‘student’ has been defined as class, then the statement
Syntax:
5
ABSTRACTION (construct)
- Abstraction refers to the act of representing essential features without including
the background details or explanations.
- Attributes are sometimes called data members because they hold information.
- The functions that operate on these data are sometimes called methods or
member functions.
- Class use the concept of data abstraction, they known as Abstract Data
Types(ADT)
INHERITANCE
- Inheritance is the process by which objects of one class acquire the properties of
object of another class.
- In OOP, 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 (‘old’ as well
as ‘new’)
- Note that each sub – class defines only those features that are unique to it.
POLYMORPHISM
- Polymorphism, a Greek term, means the ability to take more than one form.
- Polymorphism means one name, multiple forms. It allows us to have more than
one function with the same name in a program.
- The process of making an operator to exhibit different behaviours in different
instances is known as operator overloading.
- Using a single function name to perform different types of tasks is known as
function overloading.
DYNAMIC BUINDING
- Dynamic binding means that the code associated with a given procedure is not
known until the time of the call at run-time.
- 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.
- It is associated with a polymorphism and inheritance.
MESSAGE PASSING
- Message passing involves specifying the name of the object, the name of the
function (message) and the information to be sent.
- Object communicate with one another by sending and receiving information
much the same way as people pass messages to one another.
- Objects have a life cycle. They can be created and destroyed.
6
.
BENEFITS OF OOPS
OOP offers several benefits to both the program designer and the user.
- The new technology promises greater programmer productivity, better quality of
software and lesser maintenance cost.
- Through inheritance, we can eliminate redundant code and extend the use of
existing classes.
- We can build programs from the standard working modules, this leads to saving
of development time and higher productivity.
- The principle of data hiding helps the programmers to build secure programs.
- It is possible to have multiple instance of an object to co-exist without any
interference.
- 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 implemental form.
- Object oriented systems can be easily upgraded from small to large system.
- Software complexity can be easily managed.
7
Chapter 1 Introduction to C++
Tokens
As we know, the smallest individual units in a program are known as tokens. C++
has following tokens
Keywords
Identifiers
Constants
Strings
Operators
- A C++ program is written using these tokens, white spaces, and the syntax
of the language.
- Most of the C++ tokens are basically similar to the C tokens with the
exception of some additions and minor modifications.
Keywords
- There are 48 keywords in C++. (There are 32 keywords in C language).
- These keywords have specific meaning associated (related/connected) with
them.
- The keyword can not be used as variable name (user define data type).
C++ keywords
asm auto break case catch
char class const continue default
delete do double else enum
extern float for friend goto
if inline int long new
operator private protected public register
return short signed sizeof static
struct switch template this throw
try typedef union unsigned virtual
void volatile while
1
Chapter 1 Introduction to C++
- class - array
- enumeration Built in type - function
- structure - pointer
- union - reference
- Both C and C++ compilers support all the built-in (also known as basic
or fundamental) data types.
- ‘void’ data type is not having modifiers.
- Basic data type Character, integer are having modifiers like signed,
unsigned, long and short.
Declaration of variable:
- All variable must be declared before they are used in executable
statements.
- They can be declared any where in the program.
Syntax:
<data type > <variable name>
Example:
-int rollno; // “rollno” is the variable of type integer.
-char name[10]; // “name” is the variable of type character(string).
2
Chapter 1 Introduction to C++
Reference variable:
- A reference variable provides an alternative name (alias) for previously
defined variable.
Syntax:
data type &reference variable = variable - name
Example:
int total = 100;
int &sum = total;
Example:
void funct1(void);
3
Chapter 1 Introduction to C++
Output:
Enter student class [0-4]: 2
Select BSc CS
- But in C++, the size should be one larger than the number of character in
the string. For instance,
4
Chapter 1 Introduction to C++
Functions:
- We can say function is to do a given specific task.
- A function is a mechanism that enables us to use modular programming
and facilitates software reuse.
- A statement block in a program is a set of statements within curly braces.
- Function can use local and global variables and even other functions, in
their implementation.
Syntax:
Data-type function-name(argument-list); .
Pointers:
- A pointer is a variable that to holds a memory address of another
variable.
- Pointers are generally used in C++ for memory management and achieving
polymorphism.
Symbolic constant
There are two ways of creating symbolic constant in C++.
i. Using the qualifier “const”, and
ii. Defining a set of integer constant using “enum” keyword.
Structure of C ++ Program
- Typical C++ program would contain four sections.
- These sections may be placed in separate code files and then compiled
independently or jointly.
5
Chapter 1 Introduction to C++
Member Functions
server
Class definition
client
Main function program
I/O statements
Let us begin with a simple example
Output statement
// program to demonstrate simple output statement
- First include header files. That
#include<iostream.h> would be helpful to us during
the program.
void main() // start main() function - After that execution begin with
{ main() function. Every C or
cout << “ Welcome in OOP language”; C++ program must have main()
} function.
- With the help of cout (console
Output output and insertion operator)
Welcome in OOP language displays the message on
console.
C++ introduce new comment
symbol that is “//”(double slash).
Before that we are used “/* */”
in ANSI C as comment line.
6
Chapter 1 Introduction to C++
Input statement
// program to demonstrate simple input statement
#include<iostream.h> - With the help of cout (console
void main() // start main() function output and insertion operator)
{ displays the message on
char name[10]; console.
cout << “ Welcome in OOP language”; - With the help of cin(console
cout<< “Input good name please : ”; input and extraction operator)
cin >> name; take input from user.
cout<< “Your good name is :” << name;
}
Output:
Welcome in OOP language
Input good name please : anil
Your good name is : anil
Operators in C++
- All C operators are valid in C++ also.
In addition, C++ introduces some new operators.
Operator Name
<< Insertion operator
>> Extraction operator
:: Scope resolution operator
::* Pointer to member
->* Pointer to member operator
.* Pointer to member operator
delete Memory release operator
endl Line feed operator
new Memory allocation operator
setw Field width operator
7
Chapter 1 Introduction to C++
Example:
….
{
int x = 10;
}
….
{
int x =1;
}
8
Chapter 1 Introduction to C++
Output:
We are in inner block
k= 20
m= 30
::m= 10
Manipulators:
- Manipulators are operators that are used to format the data display.
- The most commonly used manipulators are endl and setw.
- The endl operator is similar to that of ‘\n’.
Example:
cout << “m = ” << endl;
cout << “n =” <<endl;
This would cause two lines of output.
Output: m = n =
Control structures
- A function is a set up to perform a task. When the task is complex, many
different algorithms can be designed to achieve the same goal.
- The format should be such that it is easy to trace the flow of execution of
statements.
Following are the control structures:
1. Selection structure (branching statement)
Action 1 Action 2
Action 3
9
Chapter 1 Introduction to C++
Nested if else
if(expression or condition)
{
Statement;
}
else
{
if (condition)
{
Statement;
}
else
{
Statement;
}
}
Switch statement:
switch (expression)
{
case (condition 1):
{
Statement 1;
}
case (condition 2):
10
Chapter 1 Introduction to C++
{
Statement 2;
}
default:
{
Statement 3;
}
}
- This is a multiple branching statement where, based on a condition, the
control is transferred to one of the many possible points.
- In a switch there can be either variable or expression
- If it is a variable it must be either integer or character
- If it is an expression it must be an arithmetic expression.
- There can be any number of cases.
- Every case should have unique value.
- These cases can be written in any sequence.
- In a case there can be any number of statements.
- It is possible to have the nested switch.
- After every case break statement is compulsory.
- Default is a case which gets selected when none of the case value
matches with the result of expression.
- Default case is optional.
i. do ..While
- Until the condition is false, all the statements within do while loop will be
execute.
- At least one time this loop will be executed, whether condition is true or
false.
Syntax:
do
{
Action1;
}while(condition is true);
Action2;
ii. While
11
Chapter 1 Introduction to C++
iii. for :
- This is also a loop structure.
- Under the for loop divide into three parts as follows:
1. Initial value
Under this first give a value to memory variable.
2. Condition
In this statement, there is condition.
This loop will execute until this given condition is satisfied or true.
3. Increment / Decrement
With the help of these we can able to increment / decrement the
value of given variable.
Syntax:
for(initial value; condition ; increment / decrement operator)
{
Action / statement 1;
}
Jump Statements in C++
Jump statements are implemented to change the flow of the program when particular
conditions are satisfied. It is used within a program to end or continue a loop or to pause
the execution of a function. C++ has four jump statements: continue, break, return, and
goto.
12
Chapter 1 Introduction to C++
Continue:
Instead of terminating the loop, it performs the next iteration of the same loop but
ignoring the parts specified by the condition. Within the loop, it must be used in
conjunction with a decision-making statement. This statement can be used within a for,
while, or do-while loop.
1st Program:
Consider a situation in which all of the numbers between 1 and 15 except 7 are present.
So, after the value of j is 7, the goal is to use the continue statement. The program for the
same is as follows:
C++ Program:
1 2 3 4 5 6 8 9 10 11 12 13 14
Break:
If the condition is met, the loop is terminated with the break command. When the
condition is met, the loop is broken and the remainder of the loop is skipped, unlike the
continue statement. Break statements are used in conjunction with decision-making
statements such as if, if-else, or switch statements in a for loop, which can be a for loop,
while loop, or do-while loop. It causes the loop to stop executing future iterations.
Consider the case when a number series is to be displayed but not after a specified value
p. In this scenario, the break statement is used once the value of j is p. The program or the
same is as follows:
C++ Program:
13
Chapter 1 Introduction to C++
9. break;
10. cout << j << " ";
11. }
12. return 0;
13. }
Output:
123456
Return:
It removes control from the function. It is more powerful than a break. It is used to end
the entire function after the function has completed or after a condition has been met.
Except for the void() function, every function contains a return statement that returns
some value. Although the void() function can also have a return statement to conclude the
function's execution.
C++ Program:
Start with 0 1 2 3 4 5 6
Arrays
Like other programming languages, array in C++ is a group of similar types of elements
that have contiguous memory location.
In C++ std::array is a container that encapsulates fixed size arrays. In C++, array index
starts from 0. We can store only fixed set of elements in C++ array.
14
Chapter 1 Introduction to C++
and other data types, which is an addition. The array representation in a picture is
provided below.
o Fixed size
Let's see a simple example of C++ array, where we are going to create, initialize and
traverse array.
1. #include <iostream>
2. int main()
3. {
4. int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
5. //traversing array
6. for (int i = 0; i < 5; i++)
7. {
8. cout<<arr[i]<<"\n";
9. }
10. }
Output:
10
0
20
0
30
15
Chapter 1 Introduction to C++
Two-Dimensional Array
A two-dimensional array in C++ is the simplest form of a multi-dimensional array. It
can be visualized as an array of arrays. The image below depicts a two-dimensional array.
2D Array Representation
A two-dimensional array is also called a matrix. It can be of any type like integer,
character, float, etc. depending on the initialization. In the next section, we are going to
discuss how we can initialize 2D arrays.
Initializing a 2D array in C++
int arr[4][2] = {
{1234, 56},
{1212, 33},
{1434, 80},
{1312, 78}
};
So, as you can see, we initialize a 2D array arr, with 4 rows and 2 columns as an array of
arrays. Each element of the array is yet again an array of integers.
We can also initialize a 2D array in the following way.
int arr[4][2] = {1234, 56, 1212, 33, 1434, 80, 1312, 78};
Copy
In this case too, arr is a 2D array with 4 rows and 2 columns.
Printing a 2D Array in C++
We are done initializing a 2D array, now without actually printing the same, we cannot
confirm that it was done correctly.
Also, in many cases, we may need to print a resultant 2D array after performing some
operations on it. So how do we do that?
#include<iostream>
main( )
{
int arr[4][2] = {
{ 10, 11 },
{ 20, 21 },
{ 30, 31 },
{ 40, 41 }
};
int i,j;
16
Chapter 1 Introduction to C++
cout<<"Printing a 2D Array:\n";
for(i=0;i<4;i++)
{
for(j=0;j<2;j++)
{
cout<<"\t"<<arr[i][j];
}
cout<<endl;
}
}
Output:
Printing A 2D Array
17