11zon - OOP Using C++ - Unit - I C
11zon - OOP Using C++ - Unit - I C
INTRODUCTION TO C++
The first high-level programming languages were designed in the 1950s. Now there
are dozens of different languages, including Ada, Algol, BASIC, COBOL, C, C++, JAVA,
FORTRAN, LISP, Pascal, and Prolog. Such languages are considered high-level because
they are closer to human languages and farther from machine languages. In contrast,
F.Motcha rani, Asst. Prof., Dept. of CS,Karan Arts & Science College, Tiruvannamalai. Page 1
assembly languages are considered low-level because they are very close to machine
languages.
F.Motcha rani, Asst. Prof., Dept. of CS,Karan Arts & Science College, Tiruvannamalai. Page 2
Object Oriented Programming Paradigm
F.Motcha rani, Asst. Prof., Dept. of CS,Karan Arts & Science College, Tiruvannamalai. Page 3
It does not have any access It has access specifiers named as
4
specifier. Public, Private, Protected, etc.
Data can move freely from Objects can move and communicate
5 function to function in the with each other through member
system. functions.
To add new data and function in OOP provides an easy way to add new
6
POP is not so easy. data and function.
Most function uses Global data In OOP, data can‟ t move easily from
for sharing that can be accessed function to function, it can be kept
7
freely from function to function public or private so we can control
in the system. the access of data.
It does not have any proper way
It provides a proper way for hiding
8 for hiding data, so it is less
data, so it is more secure.
secure.
Overloading is possible here in the
9 Overloading isn‟ t possible. form of Function Overloading and
Operator Overloading.
1. Objects
2. Classes
3. Data abstraction and encapsulation
4. Inheritance
5. Polymorphism
6. Dynamic binding
7. Message passing
1. Objects
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. The fundamental idea behind object oriented approach is to combine both
data and function into a single unit and these units are called objects.
F.Motcha rani, Asst. Prof., Dept. of CS,Karan Arts & Science College, Tiruvannamalai. Page 4
Fig: Two ways of representing an object
2. Classes
Class is defined as a User Defined Data type. Objects are variables of the type
class. Once a class has been defined, we can create any number of objects belonging to
that class. Each object is associated with the data of type class with which they are
created. Thus, a class is nothing but a collection of objects of similar types.
Ex:
fruit mango;
Here, fruit is a class and mango is the object of the class fruit.
The class is like a blueprint where the memory space for it, will be allocated only
when an object is created for it.
3. Data abstraction and encapsulation
The wrapping up of data and function 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. These functions provide 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.
F.Motcha rani, Asst. Prof., Dept. of CS,Karan Arts & Science College, Tiruvannamalai. Page 5
4. Inheritance
Inheritance is the process by which objects of one class acquire the properties of
objects 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 designing a new class from the existing one. The new
class will have the combined features of both the classes.
5. Polymorphism
Polymorphism (Greek term) means the ability to take more than one form. An
operation may exhibit different instance. The behaviour depends upon the types of data
used in the operation. The process of making an operator to exhibit different behaviours
in different instances is known as Operator Overloading. The way of using single
function name to perform different types of tasks is known as Function Overloading.
6. Dynamic binding
Dynamic 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 polymorphism and
inheritance.
7. Message passing
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.
F.Motcha rani, Asst. Prof., Dept. of CS,Karan Arts & Science College, Tiruvannamalai. Page 6
ADVANTAGES OF OOP
OOP offers several benefits to both the program designer and the user. Object-
oriented contributes to the solution of many problems associated with the development
and quality of software products. The principal advantages are:
1. Through inheritance, we can eliminate redundant code and extend the use of
existing classes.
2. We can build programs from the standard working modules that communicate with
one another, rather than having to start writing the code from scratch. This leads to
saving of development time and higher productivity.
3. The principle of data hiding helps the programmer to build secure programs that
can‟ t be invaded by code in other parts of the program.
4. It is possible to have multiple instances of an object to co-exist without any
interference.
7. Message passing techniques for communication between objects makes the interface
description with external systems much simpler.
OOP is not the right of any particular language. The programming languages
should support several of the OOP concepts to claim that they are object-oriented.
Depending upon the features they support, they can be classified into the following two
categories:
Languages that support almost all the OOP concepts are said to be object-
oriented programming languages. Ex: C++, Smalltalk, Java.
F.Motcha rani, Asst. Prof., Dept. of CS,Karan Arts & Science College, Tiruvannamalai. Page 7
I/O IN C++
C++ comes with libraries that provide us with many ways for performing input and
output. In C++ input and output are performed in the form of a sequence of bytes or
more commonly known as streams.
Input Stream: If the direction of flow of bytes is from the device (for example, Keyboard)
to the main memory then this process is called input.
Output Stream: If the direction of flow of bytes is opposite, i.e. from main memory to
device (for example, display screen) then, this process is called output.
Header files available in C++ for Input/Output operations are:
1. iostream: iostream stands for standard input-output stream. This header file
contains definitions of objects like cin, cout, cerr, etc.
2. iomanip: iomanip stands for input-output manipulators. The methods declared in
these files are used for manipulating streams. This file contains definitions of setw,
setprecision, etc.
3. fstream: This header file mainly describes the file stream. This header file is used
to handle the data being read from a file as input or data being written into the file
as output.
Output Operator:
The statement cout<<“Hello, world” displays the string with in quotes on the
screen. The identifier cout can be used to display individual characters, strings and even
numbers. It is a predefined object that corresponds to the standard output stream.
Stream just refers to a flow of data and the Standard Output stream normally flows to
the screen display. The cout object, whose properties are defined in iostream.h
represents that stream. The insertion operator << also called the „put to‟ operator
directs the information on its right to the object on its left.
Ex: cout<<“C++ is better than C”;
Input Operator:
The statement cin>> number1; is an input statement. The program to wait for the
user to type in a number. The number keyed-in is placed in the variable number1. The
identifier cin is a predefined object in C++ that corresponds to the standard input
stream. Here this stream represents the key board. The operator >> is known as get
from operator. It extracts value from the keyboard and assigns it to the variable on its
right.
F.Motcha rani, Asst. Prof., Dept. of CS,Karan Arts & Science College, Tiruvannamalai. Page 8
C++ DECLARATIONS
All the variables must be declared before they are used in the executable
statements. C++ allows the declaration of a variable anywhere in the scope, i.e., a
variable can be declared right at the place of its first use. This makes the program easier
to understand, because the variables are declared in the context of their use.
Ex:
int main( )
{
float x; // Declaration
float sum = 0;
for(int i=1; i<5; i++) // Declaration
{
cin >> x;
sum = sum + x;
}
float average; // Declaration
average = sum / (i-1);
cout << average;
return 0;
}
The only disadvantage of this style is that we cannot see all the variables used in a
scope at a glance.
CONTROL STRUCTURES
Control Structures or Control Statements are used to transfer control from one
statement to any other statement in a program.
F.Motcha rani, Asst. Prof., Dept. of CS,Karan Arts & Science College, Tiruvannamalai. Page 9
DECISION MAKING STATEMENTS
1. Simple if statement
if (test condition)
{
Statement block(s);
}
next statement;
If the test condition is true, statement block will be executed, otherwise execution
starts from the next statement.
Flowchart:
2. If..else statement
The „if statement‟ alone, tells us that if a condition is true it will execute a block of
statements and if the condition is false it won‟ t do anything. But, if we want to do
something else when the condition is false, then we can use the else statement with the
if statement to execute a block of code when the condition is false. The if-else
statement consists of two blocks, one for false expression and one for true
expression.
F.Motcha rani, Asst. Prof., Dept. of CS,Karan Arts & Science College, Tiruvannamalai. Page 10
Syntax:
if (test condition)
{
True block Statement (s);
}
else
{
False block Statement (s);
}
next statement;
Flowchart:
Example Program
// C program to illustrate if..else statement
#include <iostream.h>
int main()
{
int i = 20;
if (i < 15)
{
cout<<"i is smaller than 15";
}
else
F.Motcha rani, Asst. Prof., Dept. of CS,Karan Arts & Science College, Tiruvannamalai. Page 11
{
cout<<"i is greater than 15";
}
return 0;
}
Output
i is greater than 15
3. Nested if statement
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition 2 is true
}
else
{
// Executes when condition 2 is false
}
}
Example Program
#include <iostream.h>
int main()
{
int i = 10;
if (i == 10)
{
if (i < 15)
cout<<"i is smaller than 15\n";
// Nested - if statement will only be executed if statement above is true
if (i < 12)
cout<<"i is smaller than 12 too\n";
F.Motcha rani, Asst. Prof., Dept. of CS,Karan Arts & Science College, Tiruvannamalai. Page 12
else
cout<<"i is greater than 15";
}
return 0;
}
Output
i is smaller than 15
i is smaller than 12 too
4. Switch Statement
The switch case statement provides a way of choosing between a set of alternatives
based on the values of an expression.
Syntax:
switch (expression)
{
case Label 1:
statements;
break;
case Label 2:
statements;
break;
....
....
....
default:
statements;
break;
}
F.Motcha rani, Asst. Prof., Dept. of CS,Karan Arts & Science College, Tiruvannamalai. Page 13
Flowchart:
Example Program
#include <iostream.h>
#include <conio.h>
void main()
{
char ch;
cout<<“\n Enter a Character:”;
cin>>ch;
switch(ch)
{
case „a‟ :
cout<<ch<<“ is a vowel”;
break;
case „e‟ :
cout<<ch<<“ is a vowel”;
break;
case „i‟ :
cout<<ch<<“ is a vowel”;
break;
case „o‟ :
F.Motcha rani, Asst. Prof., Dept. of CS,Karan Arts & Science College, Tiruvannamalai. Page 14
cout<<ch<<“ is a vowel”;
break;
case „u‟ :
cout<<ch<<“ is a vowel”;
break;
default:
cout<<ch<<“ is not a vowel”;
break;
}
getch( );
}
Output
Enter a Character:
a
a is a vowel
These statements are used in C or C++ for the unconditional flow of control
throughout the functions in a program. They support the following types of jump
statements:
A) break
This loop control statement is used to terminate the loop. As soon as the break
statement is encountered from within a loop, the loop iterations stop there, and control
returns from the loop immediately to the first statement after the loop. Basically, break
statements are used in situations when we are not sure about the actual number of
iterations for the loop or we want to terminate the loop based on some condition.
Syntax:
break;
B) continue
This loop control statement is just like the break statement. The continue
statement is opposite to that of the break statement, instead of terminating the loop, it
forces to execute the next iteration of the loop. When the continue statement is executed
in the loop, the code inside the loop following the continue statement will be skipped and
the next iteration of the loop will begin.
Syntax:
continue;
F.Motcha rani, Asst. Prof., Dept. of CS,Karan Arts & Science College, Tiruvannamalai. Page 15
C) goto
The goto statement in C/C++ also referred to as the unconditional jump statement
can be used to jump from one point to another within a function.
Syntax:
In the above syntax, the first line tells the compiler to go to or jump to the
statement marked as a label. Here, a label is a user-defined identifier that indicates the
target statement. The statement immediately followed after „label:‟ is the destination
statement. The „label:‟ can also appear before the „goto label;‟ as in the above syntax.
LOOPS IN C++
If the condition is tested before entering the statement block, then it is called as
Entry Controlled Statement.
If the condition is tested at the exit of the statement block, then it is called as Exit
Controlled Statement. Here, the statement block will be executed at least once.
A for loop is a repetition control structure, that allows you to efficiently write a
loop that needs to execute a specific number of times. It is an entry control loop that
provides a more crisp structure.
F.Motcha rani, Asst. Prof., Dept. of CS,Karan Arts & Science College, Tiruvannamalai. Page 16
Syntax:
For statement is divided into three expressions each is separated by semi colon;
#include<iostream.h>
#include<conio.h>
void main()
{
int i, sum=0, n;
cout<<”Enter the number of numbers to be added: \n";
cin>>n;
for(i=1;i<=n;i++) // for(initialization; test expression; increment/decrement)
{
sum = sum + i;
}
cout<<“Sum of first”<<n<<” natural numbers is ”<<sum;
getch();
}
Output
A while loop statement is an entry controlled loop. The condition is evaluated and
if it is true then body of loop is executed. After execution of body, the condition is once
F.Motcha rani, Asst. Prof., Dept. of CS,Karan Arts & Science College, Tiruvannamalai. Page 17
again evaluated and if is true, body is executed once again. This goes on until test
condition becomes false.
Syntax:
while(test condition)
{
body of the loop
}
Example Program:
#include<iostream.h>
#include<conio.h>
void main()
{
int i=1, sum=0, n;
cout<<”Enter the number of numbers to be added: \n";
cin>>n;
while(i<=n)
{
sum = sum + i;
i=i+1;
}
cout<<“Sum of first”<<n<<” natural numbers is ”<<sum;
getch();
}
Output
Unlike for and while loops, which test the loop condition at the top of the loop,
the do..while loop checks its condition at the bottom of the loop. The while loop does
not allow body to be executed, if test condition is false. A do…while loop is similar to a
while loop, except that a do…while loop is guaranteed to execute at least one time.
Hence, the do while is called as an exit controlled loop.
F.Motcha rani, Asst. Prof., Dept. of CS,Karan Arts & Science College, Tiruvannamalai. Page 18
Syntax:
do
{
body of the loop
} while(test condition);
Example Program:
#include<iostream.h>
#include<conio.h>
void main()
{
int i=1, sum=0, n;
cout<<”Enter the number of numbers to be added: \n";
cin>>n;
do
{
sum = sum + i;
i=i+1;
} while(i<=n);
cout<<“Sum of first”<<n<<” natural numbers is ”<<sum;
getch();
}
Output
Sl.
do-while loop while loop
No.
Condition is checked at the end of Condition is checked at the beginning of
1
the loop. the loop.
Set of statements within the loop If the condition fails, then the statements
2
will be executed at least once. will not be executed even once
F.Motcha rani, Asst. Prof., Dept. of CS,Karan Arts & Science College, Tiruvannamalai. Page 19
FUNCTIONS IN C++
1. Inline Functions
When a function is declared as inline, the compiler copies the code of the function
in the calling function. i.e., function body is inserted in place of function call during
compilation.
Syntax:
The inline functions are similar to macros of C. The main limitation of macros is
that they are not functions, and errors are not checked at the time of compilation. The
inline function offers better type testing and does not contain limitations as present in
macros.
Example Program:
#include <iostream.h>
#include <conio.h>
int sum(int a, int b, int c)
{
return a+b+c;
}
inline int volume(int a)
{
return(a*a*a);
}
void main()
{
cout<<"The sum of 1, 2 and 5 is "<<sum(1,2,5)<<endl;
cout<<"The volume of cube of side 2cm is "<<volume(2)<<endl;
return 0;
}
F.Motcha rani, Asst. Prof., Dept. of CS,Karan Arts & Science College, Tiruvannamalai. Page 20
Output
It is possible in C++ to use the same function name for number of times and for
different intentions. Defining multiple functions with same name is known as function
overloading or function polymorphism. Polymorphism means one function having many
forms. The overloaded function must be different in their argument list and with
different data types. The following are examples of overloaded functions. All the
functions defined should be equivalent to their prototypes.
int test() { }
int test(int a) { }
int test(double a) { }
int test(int a, double b) { }
Principles of Function Overloading:
1. If two functions have the similar type and number of arguments (data type), the
function cannot be overloaded. The return type may be similar or void, but argument
data type or number of arguments must be different. For example,
a) sum(int,int,int);
sum(int,int);
Here, the above function sum is overloaded. Though the data type of arguments in
both the functions are similar, number of arguments are different.
b) sum(int,int,int);
sum(float,float,float);
In the above example, number of arguments in both the functions are same, but
data types are different. Hence, the above function can be overloaded.
3. The compiler attempts to find an accurate function definition that matches in types
and number of arguments and invokes that function. The arguments passed are checked
with all declared function. If matching function is found then that function gets
executed.
4. If there are no accurate match found, compiler makes the implicit conversion of actual
argument. For example, char is converted to int and float is converted to double.
F.Motcha rani, Asst. Prof., Dept. of CS,Karan Arts & Science College, Tiruvannamalai. Page 21
Precautions with Function Overloading
1. Only those functions that basically do the same task, on different sets of data, should
be overloaded. The overloading of function with identical name but for different purposes
should be avoided.
2. In function overloading, more than one function has to be actually defined and each of
these occupy memory.
3. Instead of function overloading, using default arguments may make more sense and
fewer overheads.
4. Declare function prototypes before main() and pass variables instead of passing
constant directly. This will avoid ambiguity that frequently occurs while overloading
functions.
Example Program:
#include <iostream.h>
#include <conio.h>
float volume(int r, int h)
{
return(3.14*r*r*h);
}
int volume(int a)
{
return(a*a*a);
}
int volume(int l, int b, int h)
{
return(l*b*h);
}
void main()
{
cout<<"The volume of cylinder of radius 1cm and height 5cm is "<<volume(1,5)<<endl;
cout<<"The volume of cube of side 2cm is "<<volume(2)<<endl;
cout<<"The volume of cuboid of 1cm, 2cm and 5cm is "<<volume(1,2,5)<<endl;
getch();
}
Output
F.Motcha rani, Asst. Prof., Dept. of CS,Karan Arts & Science College, Tiruvannamalai. Page 22