Oops C++ Notes
Oops C++ Notes
1
INTRODUCTION TO C++
UNIT-1 OOPs
Introduction
2
Entity refers to anything that exists and is distinguishable from one another. E.g.
table, chair, pen, fan , light, book, student, ball etc.
All these entities / objects have some features/attributes/ characteristics of their own.
E.g. ball has attributes like it is round, it is white in colour, its diameter etc.
The need is to model the real world entities or objects in order to solve a
problem.
These entities are nothing else but the objects around us.
Thus, many object-oriented languages were developed like C++, JAVA,
SMALLTALK, PYTHON, SCALA, JULIA, LISP, OBJECTIVE-C, SIMULA and so
on.
UNIT-1 OOPs-
Reusability of the code is the central core concept of these OOP languages.
Here, you divide the problem into different objects rather than functions as in
structured programming languages like C.
Several OOPs languages support AI tasks also like Python, LISP, SCALA, JULIA.
Several compilers also exists for C++ like TC++, Borland C++ , GCC is free
C++ compiler etc.
LABS. in 1980s.
UNIT-1 OOPs-
I. Functional Decomposition
It is used to visualize the data flow between different processes in a business.
It is based on classical DFD.
It is used to specify the global functions that operate on the objects.
By performing functional decomposition we can develop a functional model.
Functional model = DFDs + constraints = Data Flow Diagrams The need is to
verify, iterate and refine these models.
UNIT-1 OOPs-
Objects
6
An object is a logical entity containing data and code that manipulates that data.
It is an instance of a class.
It is a run-time entity.
Objects may be-
A) logical objects like a library software.
B) physical objects like a person, a chair, a table etc.
The state of an object changes according to the methods applied to it. Objects communicate
with other objects through functions.
An object is a variable only that represents data as well as functions required for
operating data.
UNIT-1 OOPs-
Classes
7
A class is an entity that specifies what data and functions will be included in object
of this class.
Collection of an object that has the common attributes and methods. A blueprint for
creating objects.
E.g. objects representing different types of employees in an organization may
be represented by a class employee.
It’s objects may be declared as employee obj1, obj2, obj3;
Where employee is the class name and obj1, obj2, obj3 are the objects of class
employee.
UNIT-1 OOPs-
Features of OOPs
8
may be protected.
6. Inheritance-The process of creating new classes (derived classes/ subclasses/ child
classes)from the existing classes (base classes/ super classes/ parent classes). The child classes
inherits the properties of its parent classes.
UNIT-1 OOPs-
Review of C
10
UNIT-1 OOPs-
c
Init. , calc. Module
11
Notations of a flowchart
Start/stop decis
ions
I/O
call
UNIT-1 OOPs
term assembly language.(covertes machine language to assembly language)
Q3. define the following terms with examples:-
12
A) Interpreter an interpreter is a computer program that directly executes instructions written in a
programming or scripting language, without requiring them previously to have been compiled into a machine
language program.
B) compilerIn computing, a compiler is a computer program that translates computer code written in one
programming language into another language. The name "compiler" is primarily used for programs that translate
source code from a high-level programming language to a lower level language to create an executable
program.
C) assemblerAn assembler is a program that takes basic computer instructions and converts them into a
pattern of bits that the computer's processor can use to perform its basic operations. Some people call these
instructions assembler language and others use the
D) linker.a linker or link editor is a computer system program that takes one or more object files (generated
by a compiler or an assembler) and combines them into a single executable file, library file, or another "object"
file.
E) loader In computer systems a loader is the part of an operating system that is responsible for loading
programs and libraries. It is one of the essential stages in the process of starting a program, as it places
programs into memory and prepares them for execution.
https://www.geeksforgeeks.org/difference-between-linker-and-loader/
Unit-1-lect-2 13
….continued
unit-1; lect-2; -
I (read)/O(write) operations in C++ are done using cin and cout cin is pre-defined that
represents a standard input stream; it passes data The file iostream.h header file defines cin
object. The cin object uses >> operator that moves data from input device to the
14
Input /Output in C++
statements.
variable.
>> is a redirection operator in C++ and is also called as stream extract operator as it
extracts data values from the input stream (stream means sequence of bytes).
unit-1; lect-2; -
cin >> u;
cin >> v;
15
For e.g.
cin >> w;
Or we can combine it also as follows:
cin>> u >> v >> w;
This is also called as cascading.
So, we can cascade this redirection operator without any limits. unit-1; lect-2; -
Similarly, cout object is a standard output stream that passes data out of cout<<“\nEnter the
values of u and v: “;
This insertion operator inserts data which is on the rhs into output stream on its lhs.
Even cout allows cascading
of the output operator, <<.
16
the program.
For e.g.
int u,v;
int u,v;
cout<< u << v;
<< is the output operator / insertion operator.
unit-1; lect-2; -
Int *p1 = (int *) malloc(sizeof(int));
int *p1 = new int;
Also new operator automatically call the constructor while malloc() doesn’t. furthermore,
new operator can be overloaded also. (to study a bit later).
unit-1; lect-2; -
18
Similarly, delete operator is used to free the memory used by the object.
Remember, C has free() to deallocate memory.
Just as new automatically calls the constructor, similarly delete calls the
destructor of the class whose object is being destroyed.
E.g.
delete a;
This statement will delete the complete array.
unit-1; lect-2; -
unit-1; lect-2; -
20
unit-1; lect-2; -
void main() means no return value whereas int main() means value is being
21
3. Global declaration section- sometimes we need same variables in both the functions
and in the main program. In such cases we use global variables. Such variables are
declared at the start of the program, before main() program.
Whenever there is a fight between a local and a global variable then it is the
local variable that gets the priority first.
4. main() function- the program execution starts from the main function.
returned and thus we must have return (0); at the last.
It is user-defined section only.
unit-1; lect-2; -
C) special characters-- , ; & * ^ : ! + - / [ ] {} () % / \ _ and so on.
unit-1; lect-2; -
Identifiers are the names that we specify for the variables, types, functions, classes and labels in
our program.
Identifiers includes everything like variables, labels (used with goto) etc. It may be upto 32
characters but may vary from compiler to compiler.
Keywords:
unit-1; lect-2; -
Constants
24
unit-1; lect-2; -
unit-1; lect-2; -
Variables
E.g. t, area, length_of_side, radius, rad etc are valid variables while area 2, len.a,
for, int are invalid variables.
26
A variable is a storage location that contains a data value.
All variables must be declared before using them.
Rules for forming variable names:-
Each variable name begins with a letter or an underscore (_).
Variable name can have 8 characters (C++ version dependent).
They are case sensitive. It means that uppercase and lowercase letters are treated as different.
They cannot be reserved words.
It cannot have a blank space, period, comma, slash or a semicolon.
unit-1; lect-2; -
unit-1; lect-2; -
unit-1; lect-2; -
29
A bit is the lowest unit in memory.
A bit can be 0 or 1.
A byte consists of 8 bits.
It represents 1 character in the ASCII code.
From table, we see that both short and int take 2 bytes.
long takes twice the memory reserved for an int.
double takes twice the float / long data type.
long double requires higher memory than the double data type. unit-1; lect-2; -
E.g. an unsigned int can be twice as large as the signed int. (see table). Type Size (bytes)
Range
unsigned char 1 0 to 255 unsigned short 2 0 to 65,535 unsigned long 4 0 to 4,294,967,295
E.g.
bool x, y;
y = false;
foreign language character sets have more than 256 chars. To solve this problem, C++ provides wchar_t type to
accommodate character sets that
unit-1; lect-2; -
These assignment statements work from right to left i.e. the value of rhs is assigned and
unit-1; lect-2; -
UNIT-1, LECTURE-4,5 33
Continued….
unit-1, lect4,5-
E.g. in an expression (a+b) we say ‘+’ is an operator while a and ‘b’ are
Operators
34
An operator is a symbol that causes the compiler to take action.
operands.
Operators inherited from C lang. are as follows:-
Arithmetic operators.
Unary operators.
Assignment operators.
Bit operators.
Relational operators.
Logical operators.
Boolean operators.
Conditional operators.
unit-1, lect4,5-
unit-1, lect4,5-
* Logical NOT
sizeof
%
~
&
!
unit-1, lect4,5-
e.g. int x = 2, y=4;
Eg2. – (arithmetic negation/unary minus): this operator turns positive no. into a int x = 10;
37
Unary operators take one operand and are associated from right to left.
E.g1 ! (logical NOT)
negative no.
x = -x;
Here, the value of x becomes -10.
unit-1, lect4,5-
Eg. a + (b – c);
& (adess operator): gives adess of an operand. E.g. m = &n[10]; It assigns the adess of pointer. E.g. int *point, x;
x = *point; // assigns int value being pointed by *point to a variable, x.
38
+ (unary plus) : used to group the enclosed operations when it precedes the
operation.
* (indirection operator): it accesses the value of an operand indirectly through a unit-1, lect4,5-
In C, sizeof(‘c’) is same as sizeof(int). In C++, ‘c’ is not promoted to int and Like C, in C++ also we have ++
(increment) and decrement (- -) operators that
inre/decre variable’s value by 1. i.e ++count and - - count; (called as pre-increment)
while count++ and count- - (called as
post-increment).
E.g. count = count++; //assign value of count to count variable on left and then
39
//incre.
count = ++count; //first increment value of count and then assign it.
unit-1, lect4,5-
Meaning
Addition assignment
40 Subtraction assignment Multiplication assignment
Division assignment
Modulus assignment
unit-1, lect4,5-
Meaning
Greater than
41 Less than Equal to
Not equal to
Less than equal to
Relational operators
Are used to compare two expressions.
Symbol Greater than equal to
>
<
==
!=
<=
>=
unit-1, lect4,5-
Meaning
Logical operators Logical AND
Logical OR42
Symbol
&& Logical Not
||
!=
unit-1, lect4,5-
on expressions.
Meaning
Bitwise &
Bitwise exclusive OR (XOR)
Bitwise right shift
Bitwise left shift
Bitwise operators
43
These operators perform operations on bit level while logical operators work
Symbol 1s complement
& Bitwise OR
|
^
>>
<<
~
unit-1, lect4,5-
BA&B
00
44 1 0 0 0
11
unit-1, lect4,5-
BA^B
00
1 145 1 0
unit-1, lect4,5-
A ~A 0 1
10
unit-1, lect4,5-
Right shift operator (>>) and Left shift
47
operator (<<)
E.g. if numb1 = 154 then numb1 >> 4 yields 5 (in decimals) or (00000101) in
binary.
E.g.2 if numb1 = 154 then numb1 << 4 yields 224 (in decimals) or (11100000) in
binary.
During shifting, zeros are inserted while during rotations these zeros are not
inserted.
unit-1, lect4,5-
z = (x++, y--, x+y);
cout << z; }
Here, firstly x++ is evaluated then y- - and finally x+y. As x+y is the rightmost expression, so result of x+y is
assigned to z. Final output is 40.
Comma operator
48
#include<iostream.h>
void main()
{
int x, y, z;
x=y=20;
unit-1, lect4,5-
49
sizeof(long); // gives size of the data type (long) as 4 bytes sizeof(char); // gives size of the
data type (char) as 1 byte.
sizeof(char); // gives size of the data type (char) as 1 byte.
Application:
unit-1, lect4,5-
Multiplication x * y 60 Division x / y 2 Modulus x % y 2 Addition x + y 17 Binary
Operators
50 Subtraction x – y 7
They take two operands and are associated from left to right. They may be
arithmetic operators as follows:- Say, x = 12, y=5;
operators
It takes three operands, hence is named as ternary.
Syntax:
expression1? expression2 : expression3;
It means that if expression1 is true then the expression2 is evaluated else expression3 is
evaluated.
E.g. u = 20;
v= 30;
unit-1, lect4,5-
type_name (expression);
Pay = (float) total; //C type
Pay = float (total); // C++ type
Also called as coercion i.e. to type cast/ coerce the data to another type of data.
This is done with the help of cast operator.
The case operator casts the data to any type given in parentheses preceding the
original data type.
Syntax:
E.g.
unit-1, lect4,5-
Q1. Write a C++ program to find the roots of a given quaatic equation.
unit-1, lect4,5-
Unit-1, lect-6,7 Oops using C++ by
int main( )
cha = 97 a cha + 1= 98 b
cout<<“cha+1= “<<int (cha)<<“ “<<cha<<endl;
cout<<“uppercase shift(cha-32)= “<<int (cha)<<“
cha + 24 = 122 z
cout<<“lowercase shift(cha+32)= “<<int (cha)<<“
cout<<“cha + 24= “ <<int (cha)<<“ “ <<cha <<endl;
OUTPUTs:
cout<<“cha = “ <<(int)cha<<“ “ <<cha <<endl;
cha++;
uppercase shift(cha-32)= 66 B
cha = cha – 32; cha = cha – 32;
cha = cha + 24;
“<<cha<<endl;
return 0; }
cha = cha + 32;
uppercase shift(cha-32)= 66 B lowercase shift(cha+32)= 98b
“<<cha<<endl;
The character ‘a’ is stored in variable cha.
The value of cha is unary incremented which increases its ASCII code from
97 to 98. The no. 98
uppercase
character into lowercase character by adding 32 to the value of character. The
difference between the two types of characters is constant 32.
Explanation of outputs…
56
1. if…..else statement
If (test-condition)
{
statement(s);
}
else
{
Statement(s);
}
58Default: str = “many”;
The switch statement
Switch(x) {
Case 0: str=“none”; break;
Case 1:
Str = “single”; break;
}
Switch cannot handle ranges like if can.
It cannot have float constant, a variable, an expression, a string or any other object in case
statement.
Loops in C++ 59
1. while loop:
Syntax:
while (condition)
{
statements;
}
Eg.1 while (!false) { …..stmts}
E.g.2 while (number < 5) {…}
e.g. do
60 } while (b <=3);
2. do while loop: Syntax: do {
statements; } while (test-condition);
{
b = 1;
}
e.g. for(int i=2; i< n; i++,j--) //compound statement in for-loops can be used.
61
3. for-loop: Syntax: for (expr1; boolexpre; expr2)
{ Statements;
….
}
1. break statement: when a break statement is executed inside a loop, itskips the remaining
statements of that loop and the control is immediately
transferred outside the loop. E.g. when a
break statement appears inside a loop or in a switchcontrol to the statement immediately following
that loop or switch So, it does an early exit from the loop or a switch statement, wherever it is
When multiple statements are nested then the control transfers to its
immediate outer level (it
Other statements
62
statement, it terminates the execution at that point andtransfersthestatement, it terminates the
statement.
used.
; //null statement
63
2. continue statement- it is used within the loops to end the execution of the current
iteration and proceed to the next iteration.
3. empty statement- also known as a null statement that do nothing. E.g. (for
int i=0; i<100; i++)
(for int i=0; i<100; i++)
{
Exercise Questions
65
cout<< “ “;
}
Width length
11 5
12 5
66
10
15
20
25 (this completes the printing of first row)
10
15
20
25 (this completes the printing of first row)
Similarly, for width = 13, 14….till 20.
{
sum = sum + r;
}
cout<<sum;
B) 0! = 1, 1! = 1, 2! = 2 *1, 3! = 3 *2 *1, 4! = 4 * 3 * 2 * 1. so,
c- -;
69r = num % 10;
num = num /10;
fact = 1;
while (c > 0)
{
fact = fact * c;
}
d) b = num;
while (num > 0) { s = (s * 10) + r;
}
if (b == s) cout<<“It is a palinome”; else
cout<<“It is not a palinome”; }
Unit1-lect-8 Oops using C++ by
Functions in C++
71
Functions are small modules that are written to accomplish some task. They help us
in achieving modularity.
But under-modularity and over-modularity should not be done. The
encapsulations of code are called as functions.
We have used several in-built functions like sqrt( ), abs( ) etc.
Also programmers can write their own programs that are called as user
defined functions.
unit-1-functions-
Advantages of functions
72
Function definition
73
A function definition has a function header and a function body. The function
header has three parts:-
A function name.
A parameter list.
A return type.
Each function is represented by its name. the function operates on its
parameters/arguments, if given. Parameters are separated by commas and are enclosed
within braces. The result of a function is reflected back through its return value, also
called as function return types.
unit-1-functions-
Working of functions 74
f1 ( );//function called by main( )
return;
……. }
void main( ) { ………….
………….
f1( ) { …………… ……………
}
unit-1-functions-
return_type function_name(list_of_parameters)
int add(int u, int v);
prototype
Syntax:
Examples:
void get_data(void);
Function call
76
Syntax:
function_name(list_of_arguments);
e.g.
display( );
unit-1-functions-
2. functions with arguments and no return value. E. g. void power (int , int);
3. functions with no arguments but return value. E.g. int add (void);
Types of Functions
77
unit-1-functions-
unit-1-functions-
{ {
t = x; t = x;
cout<<a << b; }
cout<<x << y; }
unit-1-functions-
void main( )
*y = t; cout<<x << y; } x = 20 y = 10
{
{ //swapped in swapv( )
a = 20 b = 10 // change is reflected
t = *x; *x = *y;
//back in main ( )
*x = *y;
cout<<a << b; }
unit-1-functions-