Oops 1 2 3 Units
Oops 1 2 3 Units
Oops 1 2 3 Units
Data
Data
Functions
Functions
Functions
Data
Some of the features of oops are.
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 accessed by external functions.
Page 1
C++
6) Objects may communicate with each other through functions.
7) New data and functions can be easily added wherever necessary.
8) Follows bottom up approach in program design.
BENEFITS OF OOPs:OOP offers several benefits to both the program designer and the user. The
principal advantages are.
i) Through inheritance, we can eliminate redundant code and extend the use of
existing classes
ii) We can build program from the standard working module 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.
iii) The principal of data hiding helps the programmer to build secure programs
that cannot be invaded by code in other part of the program.
iv) It is possible to have multiple instance of an object to co-exist without any
interference
v) It is easy to partition the work in a project, based on objects.
vi) Object oriented systems can be easily upgraded from small to large systems.
vii) Message passing techniques for communication between objects makes the
interface description with external systems much simpler.
viii) Software complexity can be easily managed
BASIC CONCEPT IN OOPS:-.
Some important concept in oops are
Objects.
Classes
Data abstraction & Encapsulation.
Inheritance
Dynamic binding.
Message passing.
Page 2
C++
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.
Programming problem is analyzed in terms of objects and the nature of
munication between them.
Objects take up space in the memory & have an associated address like
structure in c.
When a program executes, the object interacts by sending messages to one
another. Ex. If there are two objects .customer. and .account. Then the
customer object may send a message to account object requesting for the
bank balance. Thus each object contains data, and code to manipulate the
data.
Object Student
Data - Name
Roll No.
Marks
Functions: 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. Objects are actually variable of the type class.
Once a class has been defined, we can create any number of objects
belonging to that class. Thus a class is collection of objects of similar type.
Classes are user defined data types and behaves like the built in type of a
programming language.
The syntax for defining class is
class class-name
{
------------------------------}
Page 3
C++
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.
These functions provide the interface between the objects 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.
Classes use the concept of abstraction and are defined as a list of abstract
attributes such as size, weight and coast, and functions to operate on these
attributes.
Inheritance: Inheritance is the process by which object of one class acquire the
properties of objects of another class.
In OOPs, 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 combined features of both the classes.
Hybrid Inheritance
Page 4
C++
1. Single Inheritance: Derivation of a class from only one base class is called
single inheritance. The following shows the single inheritance.
PARENT CLASS
CHILD CLASS
BASE CLASS
DERIVED CLASS
A
B
BASE CLASS
DERIVED CLASS
Page 5
C++
4. Multi level Inheritance: Derivation of a class from another derived class is
called Multi level inheritance. The following diagram shows the multi level
inheritance
BASE CLASS
DERIVED CLASS
BASE CLASS
C
D
DERIVED CLASS
A B C
D
M.MANOJ KUMAR M.Tech (cs)
BASE CLASS
DERIVED CLASS
Page 6
C++
Polymorphism: Polymorphism is important oops concept. It means ability to take more than
one form.
In polymorphism an operations may shows different behavior in different
instances. The behavior depends upon the type of data used in the operation.
For Ex- Operation of addition for two numbers, will generate a sum. If the
operands are strings, then the operation would produce a third string by
Concatenation.
The process of making an operator to show different behavior in different
instance is called as operator overloading. C++support operator overloading
Shape
Draw ()
Circle
Draw (Circle)
Box
Draw (Box)
Triangle
Draw (Triangle)
Dynamic Binding: Binding referes to the linking of a procedure call to the code to be executed
in response to the call.
Dynamic 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: OOPs consist of a set of objects that communicate with each other.
Message passing involves following steps
i) Creating classes that define objects and their behavior
ii) Creating objects from class definitions and
A message for an object is a request for execution of a procedure &
therefore will invoke a function in the receiving object that generates the
desired result.
Message passing involves specifying the name of the object, the name of
the function i.e. message and the information to be sent.
Ex
customer.balance (account no)
object
message
information
Page 7
C++
Page 8
C++
108 - integer part
1517 - fractional part
C++ provides three floating-point object types
Float
Double
Long double
Character Object Types
Character type char is related to the integer types
Characters are encoded using a scheme where an integer
represents a particular character
ASCII is the dominant encoding scheme
Examples
' 'encoded as 32
'+' encoded as 43
'A' encoded as 65
'Z' encoded as 90
'a' encoded as 97
'z' encoded as 122
Meaning class:Class: A class is a user defined data type which binds data and its
associated functions together. It allows the data and functions to be
hidden, if necessary from external use. Generally, a class specification
has two parts.
i) Class declaration: it describes the type & scope of its members.
ii) Class function definitions: It describes how the class functions are
implemented.
Class declaration.
The general form of a class is
class class-name
{
Private:
Variable declaration;
Function declaration;
public:
Variable declaration;
Function declaration;
};
1) The class keyword specifies that what follows is an abstract data of type class
name. The body of a class is enclosed within braces &terminated by semicolon.
M.MANOJ KUMAR M.Tech (cs)
Page 9
C++
2) The class body consists of declaration of variables & functions which are called
as members & they are grouped under two sections i.e.private & public.
3) Private and public are known as visibility labels, where private canbe accessed
only from within the class where public members can be accessed from outside the
class also. By default, members of aclass are private.
4) The variable declared inside the class are known as data members& functions
are known as member functions. Only the member function can have access to the
private data members & private functions. However the public members can be
accessed from outside the class.
Simple class example
Class item
{
Int number;
variable
Float cost;
declaration
Public:
Void getdata (int a, float b);
function
Void putdata (void);
declaration
}
In above class class-name is item. These class data members are private by default
while both the functions are public by declaration. The function getdata () can be
used to assign values to the member variable number &cost, and putdata () for
displaying their values. These functions provide theonly access to data members of
the class.
Polymorphism: Polymorphism is important oops concept. It means ability to take more than
one form.
In polymorphism an operations may shows different behavior in different
instances. The behavior depends upon the type of data used in the operation.
Polymorphism classified in to two types
Compile time polymorphism
Runtime polymorphism
Page 10
C++
Polymorphism
Runtime polymorphism
Virtual function
Page 11
C++
declared by using virtual keyword, virtual key word reprojected basic class
member function.
Syntax:- virtual return type member function name( )
{
----}
Defining a Function:
The general form of a C++ function definition is as follows:
return_type function_name( parameter list )
{
body of the function
}
A C++ function definition consists of a function header and a function body. Here
are all the parts of a function:
Return Type: A function may return a value. The return_type is the data
type of the value the function returns. Some functions perform the desired
operations without returning a value. In this case, the return_type is the
keyword void.
Function Name: This is the actual name of the function. The function name
and the parameter list together constitute the function signature.
Parameters: A parameter is like a placeholder. When a function is invoked,
you pass a value to the parameter. This value is referred to as actual
parameter or argument. The parameter list refers to the type, order, and
number of the parameters of a function. Parameters are optional; that is, a
function may contain no parameters.
Function Body: The function body contains a collection of statements that
define what the function does.
Calling a Function:
While creating a C++ function, you give a definition of what the function has to
do. To use a function, you will 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 its return statement is
M.MANOJ KUMAR M.Tech (cs)
Page 12
C++
executed or when its function-ending closing brace is reached, it returns program
control back to the main program.
To call a function, you simply need to pass the required parameters along with
function name, and if function returns a value, then you can store returned value.
For example:
Function Arguments:
If a function is to use arguments, it must declare variables that accept the values of
the arguments. These variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are
created upon entry into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a
function:
Call Type
Description
Call by value
Call by pointer
Call by reference
Page 13
C++
By default, C++ uses call by value to pass arguments. In general, this means that
code within a function cannot alter the arguments used to call the function and
above mentioned example while calling max() function used the same method.
Loop characteristics:A loop statement allows us to execute a statement or group of statements multiple
times and following is the general from of a loop statement in most of the
programming languages:
Page 14
C++
C++ programming language provides the following types of loop to handle looping
requirements. Click the following links to check their detail.
Loop Type
Description
while loop
for loop
do...while loop
nested loops
You can use one or more loop inside any another while,
for or do..while loop.
Description
break statement
continue statement
goto statement
Page 15
C++
not advised to use goto statement in your program.
Software reusability:Reuse of existing software components increase the quality and productivity in
software development and maintenance. Software reuse reduces the amount of
software that needs to be produced from scratch and hence less testing time for
new software C++ templates are used to support the concept of reusability in
object-oriented programming. An object-oriented software system is a collection of
classes which are abstract data types and templates are a way of making classes
more abstract without actually knowing what data type will be handled by the
operations of the class. The ability to have a single class that can handle several
different data types means the code is easier to maintain, and it makes classes more
reusable. This raises questions about how generic programming included in the
form of templates in the code can be measured to identify effectiveness of this
reuse strategy. The measurement of reuse would help developers to monitor
current levels of reuse and provide insight in developing software that is easily
reused
Page 16
C++
Creation of new data type:In c++ has added two new data types to enhance the range of data types
available in C++. They are bool and wchar_t.
The bool data type :The data type bool has added to hold a Boolean value, true or flase. The values
true and false have been added as keywords to the C++ language.the bool type
variables can be declared as follows
Bool b1;
//declare b1 as bool type
B1=true;
//assign true value to it
Bool b2 =false //declare and initialize
The default numeric value of true is 1 and false is 0.it is possible to convert
implicitly the data types pointers, integers or floating point values to bool type.
The Wchar_t data type:
The character type wchar_t has been defined in C++ to hold 16-bit wide
characters. The 16-bit characters are used to represent the character set of
languages that have more than 255 characters, such as Japanese. This is important
if we are writing programs for international distribution.
C++ also introduces a new character literal known as wide_character literal
which uses two bytes of memory. Wide_character literals begin with the letter L,
as follows:
Lxy//wide_character literal.
C++ is an object oriented programming language developed by Biarne
stroustrup at & T Bell laboratories.
C++ is an extension of c with a major addition of the class constructfeature.
# include<iostream.h>
int main()
{
cout<<.Hello Wold.;
return 0;
}
C++ program is a collection of functions. Every C++ program must have a
main() function.
The iostream file:The header file iostream should be included at the beginning of all programs that
uses one output statement.
Page 17
C++
Input / Output operator
1. Input Operator cin: - The identifier cin is a predefined object in c++ that
corresponds to the standard input stream. Here this streamrepresents keyboard.
Syntax:- cin>>variable;
The operator >> is known as extraction or get from operator &assigns it to the
variable on its right.
2. Output operator cout:-The identifier cout is predefined object that represents
the standard output stream in c++. Here standard output stream represents the
screen.
Syntax:- cout<<string;
The operator << is called the insertion or put to operator. It inserts the contents of
the variable on its right to the object on its left.
3. Return type of main():- In C++, main returns an integer type value to the
operating system. So return type for main() is explicitly specified as int. Therefore
every main() in c++ should end with a return 0 statement.
Page 18
C++
C++
1. C++ is non Procedural i.e. Object
oriented Language.
1. C is Procedural Language.
4. Operator
possible in C.
overloading
is
Page 1
C++
Program Design.
Program Design.
/* hello.c */
#include <stdio.h>
int main(){
printf("Hello world\n");
return 0;
// hello.cc
#include <iostream>
using namespace std;
int main(){
cout << "Hello world" << endl;
return 0;
}
}
9. Mapping between Data and 9. Mapping between Data and Function
Function is difficult and complicated. can be used using "Objects"
10. In C, we can call main() Function 10. In C++, we cannot call main ()
through other Functions
Function through other functions.
11. C++ allows the declaration of variable
11. C requires all the variables to be
anywhere in the scope i.e at time of its
defined at the starting of a scope.
First use.
12. No inheritance is possible in C.
Page 2
C++
Built in type
Derived type
Structure Array
Union Function
Class Pointer
Enumeration
array
function
pointer
reference
Integral Type
int
char
void
Floating type
Float
double
Data Type
A set of valid data values along with the operations that may
be performed on those values. The C++ data types we will use in this class
are as follows
CharOne alphanumeric character enclosed in single quotes.
a ! C $ x *
M.MANOJ KUMAR M.Tech (cs)
Page 3
C++
signed
unsigned
short
long
Type
char
1byte
unsigned char
1byte
0 to 255
signed char
1byte
-127 to 127
int
4bytes
-2147483648 to 2147483647
unsigned int
4bytes
0 to 4294967295
signed int
4bytes
-2147483648 to 2147483647
Page 4
C++
short int
2bytes
-32768 to 32767
0 to 65,535
Range
-32768 to 32767
long int
4bytes
-2,147,483,647 to 2,147,483,647
4bytes
4bytes
0 to 4,294,967,295
float
4bytes
double
8bytes
long double
8bytes
wchar_t
2 or 4 bytes
1 wide character
Input statements
The extraction operator >> is used for general input of variable values. The
extraction operator is defined for all the built-in basic C++ types. It is possible to
input values for multiple variables in the same statement by chaining them together
with the extraction operator. For each occurrence of >> you must supply the name
of the variable where you want the input value assigned (a statement cant end with
>>).
cin >> value1 >> value2; is the same as cin >> value1; cin >> value2;
Rules for how C++ reads different types of values:
int
Page 5
C++
of the line
(result of pressing Enter)
double Skip any leading spaces or blank lines, read digits until
encountering a
character that is not valid in a floating-point value, like a
blank space
or a special character other than a decimal point, or a letter,
or the end
of the line.
char
Skip any leading spaces or blank lines and read the first
non-blank
character encountered.
string
When youre reading from the keyboard, you should precede your input statements
with output statements explaining what it is that your program is expecting the user
of the program to enter these are called prompting messages. Otherwise, the
cursor will be blinking on the output screen, but the user of the program has no
way of knowing what the program is waiting for. Prompting messages should be
brief because people tend not to read instructions very well. Sometimes it helps to
give the user an example of the input the program expects rather than to try and
write out a long detailed description .Some knowledge about the anticipated users
of your program may give you an idea of the amount of detail that would be
necessary or desirable in your instructions. You can input the values your program
needs in any order you want and in any combination you want (one at a time, two
at a time, etc.). I strongly recommend reading only one value at a time because it
greatly simplifies the instructions and possibly helps to prevent errors by the user
while keying the input values. If you expect the user to enter multiple values
M.MANOJ KUMAR M.Tech (cs)
Page 6
C++
Output statement
The insertion operator << is used for general output. It has been defined to
Output values in a default format for all of the built-in basic C++ types. Each
occurrence of << must be followed by a value to be printed or a manipulator
that affects the state of the output stream (a statement cant end with <<).
It is possible to output multiple values in the same statement by chaining them
together with the << (insertion) operator:
Cout << value1 << value2;
Where the variables (or constants or expressions) may be of any of the built-in
Basic types.
The insertion operator converts values to text form. By default, values are
displayed in a width equal to their size and formatted as follows:
char
int
Page 7
C++
compiler. Typically,
values with a non-zero fractional part are displayed with 6
digits to the
right of the decimal. Trailing fractional zeros aren't
displayed. If there
are no significant digits to the right of the decimal point,
printing of the
decimal point is suppressed along with the trailing zeros.
Depending on the compiler, the final fractional digit printed
may be
rounded or the excess digits simply truncated.
The number may be displayed in E-notation, depending
upon the value
of the number (which depends on the compiler being used).
Again, the
field is just wide enough to hold the number and, for a
negative value,
a leading minus sign.
string
OPERATORS IN C++
An operator is a symbol that tells the compiler to perform specific mathematical or
logical manipulations. C++ is rich in built-in operators and provides the following
types of operators:
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Arithmetic Operators:
There are following arithmetic operators supported by C++ language
M.MANOJ KUMAR M.Tech (cs)
Page 8
C++
Operator
Description
Example
+
Adds two operands
A + B will give 30
- Subtracts second operand from the first
A - B will give -10
*
Multiplies both operands
A * B will give 200
/ Divides numerator by de-numerator
B / A will give 2
% Modulus Operator and remainder of after an B % A will give 0
Integer division
++
--
Relational Operators:
There are following relational operators supported by C++ language
Operator
Description
==
Checks if the values of two operands are equal
or not, if yes then condition becomes true.
Example
(A == B) is not true.
!=
>
<
>=
<=
(A != B) is true.
Page 9
C++
Logical Operators:
There are following logical operators supported by C++ language
Operator
&&
||
Description
Called Logical AND operator. If both the
operands are non-zero, then condition
becomes true.
Example
(A && B) is false.
Bitwise Operators:
Bitwise operator works on bits and perform bit-by-bit operation. T he truth tables
for &, |, and ^ are as follows
Operator
Description
&
Binary AND Operator copies a bit to the result
if it exists in both operands.
Example
(A & B) will give 12 which is 0000 110
|
Binary OR Operator copies a bit if it exists in
either operand.
Example
(A | B) will g ive 61 which is 0011 1101
^
Binary XOR Operator copies the bit if it is set in
one operand but not both.
Example
(A ^ B) will g ive 49 which is 0011 0001
~
Binary Ones Complement Operator is unary
and has the effect of 'flipping ' bits.
Example
(~A ) will give -61 which is 1100 0011 in 2's
complement form due to a sig ned binary
number.
<<
Binary Left Shift Operator. T he left operands
M.MANOJ KUMAR M.Tech (cs)
Page 10
C++
Ex:-=
Ex:*=
Ex:/=
Ex:%=
Ex:<<=
>>=
Ex:-
Description
Simple assignment operator, Assigns values
from rig ht side operands to left side operand
C = A + B will assign value of A + B into C
Add AND assignment operator, It adds rig ht
operand to the left operand and assign the
result to left operand
C += A is equivalent to C = C + A
Subtract AND assignment operator, It
subtracts rig ht operand from the left operand
and assign the result to left operand
C -= A is equivalent to C = C - A
Multiply AND assignment operator, It multiplies
right operand with the left operand and assign
the result to left operand
C *= A is equivalent to C = C * A
Divide AND assignment operator, It divides
left operand with the rig ht operand and assign
the result to left operand
C /= A is equivalent to C = C / A
Modulus AND assignment operator, It takes
modulus using two operands and assign the
result to left operand
C %= A is equivalent to C = C % A
Left shift AND assignment operator
C <<= 2 is same as C = C << 2
Rig ht shift AND assignment operator
C >>= 2 is same as C = C >> 2
Page 11
C++
&=
Bitwise AND assignment operator
Ex:C &= 2 is same as C = C & 2
^=
bitwise exclusive OR and assignment operator
Ex:C ^= 2 is same as C = C ^ 2
|=
bitwise inclusive OR and assignment operator
Ex:C |= 2 is same as C = C | 2
Misc Operators
There are few other operators supported by C++ Language.
Operator
Description
Size of
size of operator returns the size of a variable.
For example, sizeof(a),here a is integer, will return 4.
Condition? X : Y Conditional operator. If Condition is true ? then it returns value
X : otherwise value Y
,
Comma operator causes a sequence of operations to be performed. The
value of the entire comma expression is the value of the last expression of the
comma-separated list.
. (dot) and -> (arrow) Member operators are used to reference individual members
of classes, structures, and unions.
Cast
Casting operators convert one data type to another. For example,
int(2.2000) would return 2.
&
Pointer operator & returns the address of an variable. For example
&a; will give actual address of the variable.
*
Pointer operator * is pointer to a variable. For example *var; will
pointer to
a variable var.
Page 12
C++
C++
Switch Statement:The purpose of switch statement is to select single option into a multiple options.
Switch (expression)
{
Case label 1:
Statements
Breaks;
Case label 2:
Statements;
Break;
Case label n;
Statements;
Break; case terminated
Default;
Statements;
2
M.MANOJKUMAR M.Sc, M.Tech.
C++
Flow chart:SWITCH
EXPERSSION
Exp1
Statement
Exp2
Statement
Exp3
Statement
default
Exit
Statement
LOOPS (Iteration statements):Iteration means operated process. In iteration statements depending upon given
condition. Body of the loop executed continuously. This is also known as loop.
Loops can be classified into
While loop
Do-While
For loop
While loop:While loop is a control statement it can be executed depending upon given condition.
In While loop first check the condition, if the condition is true body of the loop executed ,once
again check the while condition if the condition is true body of the loop executed once. This
process is continue until condition is false.
Syntax:- While (condition)
{
Body of loop;
}
3
M.MANOJKUMAR M.Sc, M.Tech.
C++
Flow Chart:False
WHILE LOOP
CONDITION
True
Body of loop
Next statement
Do While:Do-while is a iteration statement in a Do-while first body of the loop executed and next
check the condition ,if the condition is true body of the loop executed once, this process is
repeated until condition is false. In Do While first time condition is false body of the loop
executed once again i.e., Do-While is a exit control loop.
Syntax:- Do
{
Body of the loop;
}
While (condition);
Flowchart:Body of loop
False
Condition
True
Next statement
4
M.MANOJKUMAR M.Sc, M.Tech.
C++
For loop:For loop is iteration statement it depending upon given condition to executed group of
statements repeatly. The For loop contains initialization part condition part and increment part.
Syntax:For (initialization; condition; increment) statement;
{
Statements;
}
Here statement part contains either single statement ( ) or group of statements.
Statement part contains single statement braces are optional statement part contains group of
statement.
Do-While
Executed repeatly.
In while loop at the first time condition
5
M.MANOJKUMAR M.Sc, M.Tech.
C++
Syntax:
Syntax:
While (condition)
Do
{
Body of loop
body of loop
}
While (condition)
Flowchart:-
Flowchart:-
While condition
body of loop
True
False
Body of loop
true
false
Next statement
condition
Next statement
ex:do
{
D=n%10;
d=n%10;
Sum=sum+d;
sum=sum+d;
N=n/10;
}
The body of the loop
n=n/10;
}
While (n!=0) This is similar to while
6
M.MANOJKUMAR M.Sc, M.Tech.