0% found this document useful (0 votes)
8 views

OOP Unit-1 Notes

Oops concepts
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

OOP Unit-1 Notes

Oops concepts
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Object Oriented Programming Through C++ Balaji Lanka,CSE

Unit-1
Programming Paradigms
The programming paradigm is the way of writing computer programs. There are four programming
paradigms and they are as follows.

 Monolithic programming paradigm


 Structured-oriented programming paradigm
 Procedural-oriented programming paradigm
 Object-oriented programming paradigm

Monolithic Programming Paradigm


The Monolithic programming paradigm is the oldest. It has the following characteristics. It is also
known as the imperative programming paradigm.

 In this programming paradigm, the whole program is written in a single block.


 We use the goto statement to jump from one statement to another statement.
 It uses all data as global data which leads to data insecurity.
 There are no flow control statements like if, switch, for, and while statements in this paradigm.
 There is no concept of data types.

An example of a Monolithic programming paradigm is Assembly language.

Structure-oriented Programming Paradigm


The Structure-oriented programming paradigm is the advanced paradigm of the monolithic paradigm.
It has the following characteristics.

 This paradigm introduces a modular programming concept where a larger program is divided
into smaller modules.
 It provides the concept of code reusability.
 It is introduced with the concept of data types.
 It also provides flow control statements that provide more control to the user.
 In this paradigm, all the data is used as global data which leads to data insecurity.

Examples of a structured-oriented programming paradigm is ALGOL, Pascal, PL/I and Ada.

Procedure-oriented Programming Paradigm


The procedure-oriented programming paradigm is the advanced paradigm of a structure-oriented
paradigm. It has the following characteristics.

 This paradigm introduces a modular programming concept where a larger program is divided
into smaller modules.
 It provides the concept of code reusability.
 It is introduced with the concept of data types.
 It also provides flow control statements that provide more control to the user.
 It follows all the concepts of structure-oriented programming paradigm but the data is defined
as global data, and also local data to the individual modules.
 In this paradigm, functions may transform data from one form to another.

Examples of procedure-oriented programming paradigm is C, visual basic, FORTRAN, etc.

Object-oriented Programming Paradigm


The object-oriented programming paradigm is the most popular. It has the following characteristics.
1


Page

In this paradigm, the whole program is created on the concept of objects.


 In this paradigm, objects may communicate with each other through function.
Object Oriented Programming Through C++ Balaji Lanka,CSE

 This paradigm mainly focuses on data rather than functionality.


 In this paradigm, programs are divided into what are known as objects.
 It follows the bottom-up flow of execution.
 It introduces concepts like data abstraction, inheritance, and overloading of functions and
operators overloading.
 In this paradigm, data is hidden and cannot be accessed by an external function.
 It has the concept of friend functions and virtual functions.
 In this paradigm, everything belongs to objects.

Examples of procedure-oriented programming paradigm is C++, Java, C#, Python, etc.


OOP Vs Procedural Paradigm
Both object-oriented and procedure-oriented paradigms are very popular and most commonly used
programming paradigms. The following table gives the differences between those.

Procedure-oriented Object-oriented

It is often known as POP (procedure-oriented programming). It is often known as OOP


(object-oriented
programming).

It follows the top-bottom flow of execution. It follows the bottom-top flow


of execution.

Larger programs have divided into smaller modules called as functions. The larger program has
divided into objects.

The main focus is on solving the problem. The main focus is on data
security.

It doesn’t support data abstraction. It supports data abstraction


using access specifiers that
are public, protected, and
private.

It doesn’t support inheritance. It supports the inheritance of


four types.

Overloading is not supported. It supports the overloading of


function and also the
operator.

There is no concept of friend function and virtual functions. It has the concept of friend
function and virtual functions.

Examples - C, FORTRAN Examples - C++ , Java ,


VB.net, C#.net, Python, R
Programming, etc.
2
Page
Object Oriented Programming Through C++ Balaji Lanka,CSE

C++ Data Types


The data type is a category of data. In other words, a data type is a collection of data values with
similar characteristics. In the C++ programming language, every variable needs to be created with a
data type.
The data type of a variable specifies the following.

 The type of value can be stored in a variable.


 The amount of memory in bytes has to be allocated for a variable.
 The range of values has to be stored in a variable.

The C++ programming language supports the following data types.

 Integer Data type


 Floating-point Data type
 Double Data type
 Character Data type
 Boolean Data type
 Void Data type
 Wide Character Data type

Let's look at each data type in detail.

Integer Data type


An integer is a number without a decimal part. For example, the value 10 is an integer. In c++ integer
data type has the following characteristics.

 Integer data type is represented using the keyword “int”.


 The integer value is represented using the type specifier “%d” or “%i".
 The integer data type allows storing any value in the range from -32768 to 32767. However, it
may change using type modifier.

Floating-point Data type


A floating-point value is a number with a decimal part. For example, the value 10.65 is a floating-point.
In c++ floating-point data type has the following characteristics.

 Floating-point data type is represented using the keyword “float”.


 The floating-point value is represented using the type specifier “%f”.
 The floating-point data type allows storing any value in the range from 2-31 to 231.
 The floating-point data type does not allows type modifier.
 The floating-point data type allows upto 6 decimal points.

Double Data type


The double data type is similar to the floating-point data type but it allows a wide range of values. The
double data type has the following characteristics.

 The double data type is represented using the keyword “double”.


 The double value is represented using the type specifier “%ld”.
 The double data type allows storing any value in the range from 2-63 to 263.
 The double data type does not allows type modifier except long.
 The double data type allows double precision upto 12 decimal points.

Character Data type


3

A character is a symbol enclosed in a single quotation. Here, the symbol may be anything like an
Page

alphabet, a digit, or a special symbol. In C++, the character data type has the following
characteristics.
Object Oriented Programming Through C++ Balaji Lanka,CSE

 The character data type is represented using the keyword “char”.


 The character value is represented using the type specifier “%c” or "%s".
 The character data type allows storing any value in the range from -128 to 127.
 The character data type allows only signed and unsigned type modifiers.

Boolean Data type


The boolean data type contains only two values 0 and 1. Here the value 0 represents false, and 1
represents true. The boolean data type has the following characteristics.

 The boolean data type is represented using the keyword “bool”.


 The boolean value is represented using the type specifier “%d”.
 The boolean data type allows storing only 0 and 1.
 The boolean data type does not allows type modifier.

Void Data type


The void data type is a value less data type, and it represents nothing. The void data type has the
following characteristics.

 The void data type is represented using the keyword “void”.


 The void value does not have any type specifier.
 The void data type does not allows storing any value.
 The void data type does not allows type modifier.

Wide character Data type


The wide-character data type is similar to character data type, but it takes 2 bytes of memory. It allows
a wide range of character values compare to the character data type. This data type has supported by
the latest compilers only. The keyword wchar_t is used to represent wide character data type.
The following table describes the characteristics of each data type briefly.
C++ Variables
A variable is named memory location, where the user can store different values of the specified data
type. In simple words, a variable is a value holder. Every variable in the program has the following
properties.

 Every variable has a name (user-specified) and an address.


 Every variable must be created with a data type.
 Every variable is allocated with a memory based on the data type of it.
 Every variable has a value.

Types of Variables
Based on the location of variable declaration, variables are classified into five types. They are as
follows.

 Local Variables
 Global Variables
 Formal Variables
 Member Variables
 Instance Variables

Local Variables
The variables that are declared inside a function or a block are called local variables. The local
variable is visible only inside the function or block in which it is declared. That means the local
4

variables can be accessed by the statements that are inside the function or block in which the variable
Page

has declared. Outside the function or block, the local variable can't be accessible.
Object Oriented Programming Through C++ Balaji Lanka,CSE

The local variables are created upon execution control enters into the function or block and destroyed
upon exit.

Global Variables
The variables that are declared outside a function are called global variables. The global variable is
visible inside all the functions that are defined after its declaration. That means the global variables
can be accessed by all the functions that are created after the global variable declaration. The
functions that have created before the global variable declaration can't access it.
The local variables are created upon execution starts and destroyed upon exit.

Formal Variables
The variables that are created in the function definition as receivers to the parameter values are
called formal variables. The formal variables are also known as formal parameters, and they act as
local variables inside the function.

Member Variables
The variables that are created in a class are known as member variables. The member variables are
accessible to all the methods of that class. The member variables are also accessible to the methods
of other classes using inheritance mechanism.

Instance Variables
The instance variable is a special type of variable of a user-defined data type called class. That
means an instance variable is a variable of class type. The instance variables are also known as
objects. The instance variables are used to access the class members from outside the class.
C++ Expressions
An expression is collection of operators and operands which produce a unique value as result. The
expressions are used to perform mathematical and logical operations in a program. In an expression
operator is a symbol with pre-defined task and operands are the data values on which the operation is
performed.
There are three types of expressions and they are as follows.

 Infix Expression
 Prefix Expression
 Postfix Expression

The most commanly used expression type is infix expression.

Infix Expression
In this type of expression the operator is between the operands.

Prefix Expression
In this type of expression the operator is in-front of the operands.

Postfix Expression
In this type of expression the operator is after the operands.
C++ Operators
The C++ programming language provides a wide range of operators to perform mathematical, logical,
and other operations. An operator is a symbol used to perform mathematical and logical operations.
Every operator has a pre-defined functionality. However, C++ language provides a concept operator
overloading to assign user-defined functionality to most of the operators.
5

In C++ language, the operators are classified as follows.


Page

 Arithmetic Operators
Object Oriented Programming Through C++ Balaji Lanka,CSE

 Relational Operators
 Logical Operators
 Increment and Decrement Operators
 Assignment Operators
 Bitwise Operators
 Conditional Operators
 Scope Resolution Operators
 Other Operators

Arithmetic Operators (+, -, *, /, %)


The arithmetic operators are the symbols that are used to perform basic mathematical operations like
addition, subtraction, multiplication, division and percentage modulo. The following table provides
information about arithmetic operators.

Operator Meaning Example

+ Addition 10 + 5 = 15

- Subtraction 10 - 5 = 5

* Multiplication 10 * 5 = 50

/ Division 10 / 5 = 2

% Remainder of the Division 5%2=1

Relational Operators (<, >, <=, >=, ==, !=)


The relational operators are the symbols that are used to compare two values. That means the
relational operators are used to check the relationship between two values. Every relational operator
has two results TRUE or FALSE. In simple words, the relational operators are used to define
conditions in a program. The following table provides information about relational operators.

Operator Meaning Example

< Returns TRUE if the first value is smaller than second value otherwise 10 < 5 is
returns FALSE FALSE

> Returns TRUE if the first value is larger than second value otherwise 10 > 5 is TRUE
returns FALSE

<= Returns TRUE if the first value is smaller than or equal to second value 10 <= 5 is
otherwise returns FALSE FALSE

>= Returns TRUE if the first value is larger than or equal to second value 10 >= 5 is
otherwise returns FALSE TRUE
6
Page
Object Oriented Programming Through C++ Balaji Lanka,CSE

Operator Meaning Example

== Returns TRUE if both values are equal otherwise returns FALSE 10 == 5 is


FALSE

!= Returns TRUE if both values are not equal otherwise returns FALSE 10 != 5 is
TRUE

Logical Operators (&&, ||, !)


The logical operators are the symbols that are used to combine multiple conditions into one condition.
The following table provides information about logical operators.

Operator Meaning Example

&& Logical AND - Returns TRUE if all conditions are TRUE 10 < 5 && 12 > 10 is
otherwise returns FALSE FALSE

|| Logical OR - Returns FALSE if all conditions are FALSE 10 < 5 || 12 > 10 is


otherwise returns TRUE TRUE

! Logical NOT - Returns TRUE if condition is FLASE and returns !(10 < 5 && 12 > 10) is
FALSE if it is TRUE TRUE

Increment & Decrement Operators (++ & --)


The increment and decrement operators are called unary operators because both need only one
operand. The increment operators adds one to the existing value of the operand and the decrement
operator subtracts one from the existing value of the operand. The following table provides
information about increment and decrement operators.

Operator Meaning Example

++ Increment - Adds one to existing value int a = 5;


a++; ⇒ a = 6

-- Decrement - Subtracts one from existing value int a = 5;


a--; ⇒ a = 4

The increment and decrement operators are used infront of the operand (++a) or after the operand
(a++). If it is used infront of the operand, we call it as pre-increment or pre-decrement and if it is
used after the operand, we call it as post-increment or post-decrement.

Pre-Increment or Pre-Decrement
In the case of pre-increment, the value of the variable is increased by one before the expression
evaluation. In the case of pre-decrement, the value of the variable is decreased by one before the
expression evaluation. That means, when we use pre-increment or pre-decrement, first the value of
7

the variable is incremented or decremented by one, then the modified value is used in the expression
Page

evaluation.
Object Oriented Programming Through C++ Balaji Lanka,CSE

Post-Increment or Post-Decrement
In the case of post-increment, the value of the variable is increased by one after the expression
evaluation. In the case of post-decrement, the value of the variable is decreased by one after the
expression evaluation. That means, when we use post-increment or post-decrement, first the
expression is evaluated with existing value, then the value of the variable is incremented or
decremented by one.

Assignment Operators (=, +=, -=, *=, /=, %=)


The assignment operators are used to assign right-hand side value (Rvalue) to the left-hand side
variable (Lvalue). The assignment operator is used in different variants along with arithmetic
operators. The following table describes all the assignment operators in the C programming language.

Operator Meaning Example

= Assign the right-hand side value to left-hand side variable A = 15

+= Add both left and right-hand side values and store the result into left-hand side A += 10
variable ⇒A=
A+10

-= Subtract right-hand side value from left-hand side variable value and store the A -= B
result ⇒ A = A-B
into left-hand side variable

*= Multiply right-hand side value with left-hand side variable value and store the A *= B
result ⇒ A = A*B
into left-hand side variable

/= Divide left-hand side variable value with right-hand side variable value and A /= B
store the result ⇒ A = A/B
into the left-hand side variable

%= Divide left-hand side variable value with right-hand side variable value and A %= B
store the remainder ⇒A=
into the left-hand side variable A%B

Bitwise Operators (&, |, ^, ~, >>, <<)


The bitwise operators are used to perform bit-level operations in the c programming language. When
we use the bitwise operators, the operations are performed based on the binary values. The following
table describes all the bitwise operators in the C programming language.
Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).

Operator Meaning Example

& the result of Bitwise AND is 1 if all the bits are 1 otherwise it is 0 A&B
⇒ 16 (10000)
8
Page
Object Oriented Programming Through C++ Balaji Lanka,CSE

Operator Meaning Example

| the result of Bitwise OR is 0 if all the bits are 0 otherwise it is 1 A|B


⇒ 29 (11101)

^ the result of Bitwise XOR is 0 if all the bits are same otherwise it is 1 A^B
⇒ 13 (01101)

~ the result of Bitwise once complement is negation of the bit (Flipping) ~A


⇒ 6 (00110)

<< the Bitwise left shift operator shifts all the bits to the left by the specified A << 2
number of positions ⇒ 100
(1100100)

>> the Bitwise right shift operator shifts all the bits to the right by the specified A >> 2
number of positions ⇒ 6 (00110)

Conditional Operator (?:)


The conditional operator is also called a ternary operator because it requires three operands. This
operator is used for decision making. In this operator, first we verify a condition, then we perform one
operation out of the two operations based on the condition result. If the condition is TRUE the first
option is performed, if the condition is FALSE the second option is performed. The conditional
operator is used with the following syntax.

Condition ? TRUE Part : FALSE Part;


Example

A = (10<15)? 100 : 200; // ⇒ A value is 100

Scope Resolution Operator (: :)

The scope resolution operator in C++ is used to access the global variable when both local and global
variables are having the same name, to refer to the static members of a class, and to define a
function definition outside the class. We discuss in detail about scope resolution operator in the later
tutorial in this series.

Special Operators (sizeof, pointer, comma, dot, etc.)


The following are the special operators in c programming language.

sizeof operator
This operator is used to find the size of the memory (in bytes) allocated for a variable. This operator is
used with the following syntax.sizeof(variableName);
Example
9

sizeof(A); // ⇒ the result is 2 if A is an integer


Page
Object Oriented Programming Through C++ Balaji Lanka,CSE

Pointer operator (*)


This operator is used to define pointer variables in c programming language.

Comma operator (,)


This operator is used to separate variables while they are declaring, separate the expressions in
function calls, etc.

Dot operator (.)


This operator is used to access members of a class, and structure.
The operators are also classified based on the number of operands required by the operator.

 Unary Operators

- Requires only one operand like ++ and --.

 Binary Operators

- Requires two operands like +, *, ==, ||, >>, etc.

 Ternary Operators

- Requires three operands like conditional operator.

Operator Precedance
In any programming language, every operator has provided a preference that is used at the time of
expression evaluation. In C++, the following list provides the operators' preference from higher to
lower.

1. Pre-increment (or) pre- decrement


2. Peranthasis , shifting operators , sizeof
3. Astrick (*) , multiplication and division
4. Addition , substraction
5. Relational operators
6. Assignment operators
7. Post increment/post decrement

C++ Keywords

A keyword is a reserved word. You cannot use it as a variable name, constant name etc. A list of 32
Keywords in C++ Language which are also available in C language are given below.

auto break case char const continue default do

double else enum extern float for goto if

int long register return short signed sizeof static

struct switch typedef union unsigned void volatile while

A list of 30 Keywords in C++ Language which are not available in C language are given below.
10
Page

asm dynamic_cast namespace reinterpret_cast bool


Object Oriented Programming Through C++ Balaji Lanka,CSE

explicit new static_cast false catch

operator template friend private class

this inline public throw const_cast

delete mutable protected true try

typeid typename using virtual wchar_t

C++ Identifiers

C++ identifiers in a program are used to refer to the name of the variables, functions, arrays, or other
user-defined data types created by the programmer. They are the basic requirement of any language.
Every language has its own rules for naming the identifiers.

In short, we can say that the C++ identifiers represent the essential elements in a program which are
given below:

o Constants
o Variables
o Functions
o Labels
o Defined data types

Some naming rules are common in both C and C++. They are as follows:

o Only alphabetic characters, digits, and underscores are allowed.


o The identifier name cannot start with a digit, i.e., the first letter should be alphabetical. After
the first letter, we can use letters, digits, or underscores.
o In C++, uppercase and lowercase letters are distinct. Therefore, we can say that C++
identifiers are case-sensitive.
o A declared keyword cannot be used as a variable name.

Control Statements C++ if-else

In C++ programming, if statement is used to test the condition. There are various types of if
statements in C++.

o if statement
o if-else statement
o nested if statement
o if-else-if ladder

C++ IF Statement

The C++ if statement tests the condition. It is executed if condition is true.


11

1. if(condition){
Page

2. //code to be executed
Object Oriented Programming Through C++ Balaji Lanka,CSE

3. }

C++ If Example
1. #include <iostream>
2. using namespace std;
3.
4. int main () {
5. int num = 10;
6. if (num % 2 == 0)
7. {
8. cout<<"It is even number";
9. }
10. return 0;
11. }

Output:/p>

It is even number

C++ IF-else Statement

The C++ if-else statement also tests the condition. It executes if block if condition is true otherwise
else block is executed.

1. if(condition){
2. //code if condition is true
3. }else{
4. //code if condition is false
5. }

C++ If-else Example


1. #include <iostream>
2. using namespace std;
3. int main () {
4. int num = 11;
5. if (num % 2 == 0)
6. {
7. cout<<"It is even number";
8. }
9. else
10. {
11. cout<<"It is odd number";
12. }
13. return 0;
14. }

Output:
12

It is odd number
Page
Object Oriented Programming Through C++ Balaji Lanka,CSE

C++ If-else Example: with input from user


1. #include <iostream>
2. using namespace std;
3. int main () {
4. int num;
5. cout<<"Enter a Number: ";
6. cin>>num;
7. if (num % 2 == 0)
8. {
9. cout<<"It is even number"<<endl;
10. }
11. else
12. {
13. cout<<"It is odd number"<<endl;
14. }
15. return 0;
16. }

Output:

Enter a number:11
It is odd number

C++ IF-else-if ladder Statement

The C++ if-else-if ladder statement executes one condition from multiple statements.

1. if(condition1){
2. //code to be executed if condition1 is true
3. }else if(condition2){
4. //code to be executed if condition2 is true
5. }
6. else if(condition3){
7. //code to be executed if condition3 is true
8. }
9. ...
10. else{
11. //code to be executed if all the conditions are false
12. }

C++ If else-if Example


1. #include <iostream>
2. using namespace std;
3. int main () {
4. int num;
5. cout<<"Enter a number to check grade:";
6. cin>>num;
7. if (num <0 || num >100)
13

8. {
9. cout<<"wrong number";
Page

10. }
Object Oriented Programming Through C++ Balaji Lanka,CSE

11. else if(num >= 0 && num < 50){


12. cout<<"Fail";
13. }
14. else if (num >= 50 && num < 60)
15. {
16. cout<<"D Grade";
17. }
18. else if (num >= 60 && num < 70)
19. {
20. cout<<"C Grade";
21. }
22. else if (num >= 70 && num < 80)
23. {
24. cout<<"B Grade";
25. }
26. else if (num >= 80 && num < 90)
27. {
28. cout<<"A Grade";
29. }
30. else if (num >= 90 && num <= 100)
31. {
32. cout<<"A+ Grade";
33. }
34. }

Output:

Enter a number to check grade:66


C Grade

The C++ switch statement executes one statement from multiple conditions. It is like if-else-if ladder
statement in C++.

1. switch(expression){
2. case value1:
3. //code to be executed;
4. break;
5. case value2:
6. //code to be executed;
7. break;
8. ......
9.
10. default:
11. //code to be executed if all cases are not matched;
12. break;
13. }

C++ Switch Example


1. #include <iostream>
14

2. using namespace std;


3. int main () {
Page

4. int num;
Object Oriented Programming Through C++ Balaji Lanka,CSE

5. cout<<"Enter a number to check grade:";


6. cin>>num;
7. switch (num)
8. {
9. case 10: cout<<"It is 10"; break;
10. case 20: cout<<"It is 20"; break;
11. case 30: cout<<"It is 30"; break;
12. default: cout<<"Not 10, 20 or 30"; break;
13. }
14. }

Output:

Enter a number:
10
It is 10
C++ For Loop

The C++ for loop is used to iterate a part of the program several times. If the number of iteration is
fixed, it is recommended to use for loop than while or do-while loops.

The C++ for loop is same as C/C#. We can initialize variable, check condition and
increment/decrement value.

for(initialization; condition; incr/decr){


//code to be executed
}

C++ For Loop Example


#include <iostream>
using namespace std;
int main() {
for(int i=1;i<=10;i++){
cout<<i <<"\n";
}
}

C++ Nested For Loop

In C++, we can use for loop inside another for loop, it is known as nested for loop. The inner loop is
executed fully when outer loop is executed one time. So if outer loop and inner loop are executed 4
times, inner loop will be executed 4 times for each outer loop i.e. total 16 times.

C++ Nested For Loop Example

Let's see a simple example of nested for loop in C++.

#include <iostream>
using namespace std;
15
Page

int main () {
Object Oriented Programming Through C++ Balaji Lanka,CSE

for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
cout<<i<<" "<<j<<"\n";
}
}
}

C++ Infinite For Loop

If we use double semicolon in for loop, it will be executed infinite times. Let's see a simple example of
infinite for loop in C++.

#include <iostream>
using namespace std;

int main () {
for (; ;)
{
cout<<"Infinitive For Loop";
}
}
C++ While loop

In C++, while loop is used to iterate a part of the program several times. If the number of iteration is
not fixed, it is recommended to use while loop than for loop.

while(condition){
//code to be executed
}

C++ While Loop Example

Let's see a simple example of while loop to print table of 1.

#include <iostream>
using namespace std;
int main() {
int i=1;
while(i<=10)
{
cout<<i <<"\n";
i++;
}
}
C++ Do-While Loop

The C++ do-while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed and you must have to execute the loop at least once, it is recommended to use
16

do-while loop.
Page

The C++ do-while loop is executed at least once because condition is checked after loop body.
Object Oriented Programming Through C++ Balaji Lanka,CSE

do{
//code to be executed
}while(condition);

C++ do-while Loop Example

Let's see a simple example of C++ do-while loop to print the table of 1.

#include <iostream>
using namespace std;
int main() {
int i = 1;
do{
cout<<i<<"\n";
i++;
} while (i <= 10) ;
}
C++ Break Statement

The C++ break is used to break loop or switch statement. It breaks the current flow of the program at
the given condition. In case of inner loop, it breaks only inner loop.

1. jump-statement;
2. break;

C++ Comments

The C++ comments are statements that are not executed by the compiler. The comments in C++
programming can be used to provide explanation of the code, variable, method or class. By the help
of comments, you can hide the program code also.

There are two types of comments in C++.

o Single Line comment


o Multi Line comment

C++ Single Line Comment

The single line comment starts with // (double slash). Let's see an example of single line comment in
C++.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x = 11; // x is a variable
6. cout<<x<<"\n";
7. }
17
Page
Object Oriented Programming Through C++ Balaji Lanka,CSE

C++ Multi Line Comment

The C++ multi line comment is used to comment multiple lines of code. It is surrounded by slash and
asterisk (/∗ ..... ∗/). Let's see an example of multi line comment in C++.

1. #include <ostream>
2. using namespace std;
3. int main()
4. {
5. /* declare and
6. print variable in C++. */
7. int x = 35;
8. cout<<x<<"\n";
9. }
C++ 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.

Advantages of C++ Array


o Code Optimization (less code)
o Random Access
o Easy to traverse data
o Easy to manipulate data
o Easy to sort data etc.

Disadvantages of C++ Array


o Fixed size

C++ Array Types

There are 2 types of arrays in C++ programming:

1. Single Dimensional Array


2. Multidimensional Array
18
Page
Object Oriented Programming Through C++ Balaji Lanka,CSE

C++ Single Dimensional Array

Let's see a simple example of C++ array, where we are going to create, initialize and traverse array.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
6. //traversing array
7. for (int i = 0; i < 5; i++)
8. {
9. cout<<arr[i]<<"\n";
10. }
11. }

C++ Array Example: Traversal using foreach loop

We can also traverse the array elements using foreach loop. It returns array element one by one.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
6. //traversing array
7. for (int i: arr)
8. {
9. cout<<i<<"\n";
10. }
11. }
C++ Multidimensional Arrays

The multidimensional array is also known as rectangular arrays in C++. It can be two dimensional or
three dimensional. The data is stored in tabular form (row ∗ column) which is also known as matrix.

C++ Multidimensional Array Example

Let's see a simple example of multidimensional array in C++ which declares, initializes and traverse
two dimensional arrays.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int test[3][3]; //declaration of 2D array
6. test[0][0]=5; //initialization
7. test[0][1]=10;
19

8. test[1][1]=15;
9. test[1][2]=20;
Page

10. test[2][0]=30;
Object Oriented Programming Through C++ Balaji Lanka,CSE

11. test[2][2]=10;
12. //traversal
13. for(int i = 0; i < 3; ++i)
14. {
15. for(int j = 0; j < 3; ++j)
16. {
17. cout<< test[i][j]<<" ";
18. }
19. cout<<"\n"; //new line at each row
20. }
21. return 0;
22. }

Output:

5 10 0
0 15 20
30 0 10

Parameter Passing techniques

Actual Parameters are the parameters that appear in the function call statement.

Formal Parameters are the parameters that appear in the declaration of the function which has been
called.

Now let’s look at how each call mechanism works.

Call by Value

When a function is called in the call by value, the value of the actual parameters is copied into formal
parameters.
Both the actual and formal parameters have their own copies of values, therefore any change in one of
the types of parameters will not be reflected by the other.
20

This is because both actual and formal parameters point to different locations in memory (i.e. they both
have different memory addresses).
Page
Object Oriented Programming Through C++ Balaji Lanka,CSE

Call by value method is useful when we do not want the values of the actual parameters to be changed
by the function that has been invoked.

C++ Example implementing Call by Value

#include <iostream>
using namespace std;
void increment(int a){
a++;
cout << "Value in Function increment: "<< a <<endl;
}
int main()
{
int x = 5;
increment(x);
cout << "Value in Function main: "<< x <<endl;
return 0;
}

Output:

Note the output of the program. The value of ‘a’ has been increased to 6, but the value of ‘x’ in the main
method remains the same.

This proves that the value is being copied to a different memory location in the call by value.

Call by Reference

In the call by reference, both formal and actual parameters share the same value.
Both the actual and formal parameter points to the same address in the memory.
21
Page
Object Oriented Programming Through C++ Balaji Lanka,CSE

That means any change on one type of parameter will also be reflected by other.

Calls by reference are preferred in cases where we do not want to make copies of objects or variables,
but rather we want all operations to be performed on the same copy.

C++ Example implementing Call by Reference

#include <iostream>
using namespace std;
void increment(int &a){
a++;
cout << "Value in Function increment: "<< a <<endl;
}

int main()
{
int x = 5;
increment(x);
cout << "Value in Function main: "<< x <<endl;
return 0;
}

Output:

Note: For creating reference, the ‘&‘ operator is used in preceding of variable name.
Note the output in this case. The value of ‘a’ is increased to 6, the value of ‘x’ in the main also changes
to 6.

This proves that changes made to formal parameters are also reflected by the actual parameters as they
share the same memory address space.
22

Call by Address
Page

In the call by address method, both actual and formal parameters indirectly share the same variable.
Object Oriented Programming Through C++ Balaji Lanka,CSE

In this type of call mechanism, pointer variables are used as formal parameters.
The formal pointer variable holds the address of the actual parameter, hence the changes done by the
formal parameter is also reflected in the actual parameter.

As demonstrated in the diagram, both parameters point to different locations in memory, but since the
formal parameter stores the address of the actual parameter, they share the same value.

C++ Example implementing Call by Address

#include <iostream>
using namespace std;
void increment(int *a){
(*a)++;
cout << "Value in Function increment: "<< *a <<endl;
}
int main()
{
int x = 5;
increment(&x); //Passing address of x
cout << "Value in Function main: "<< x <<endl;
return 0;
}

Output:

The output here is the same as in the case of call by reference i.e. the value of both ‘a’ and ‘x’ changes.

C++ Namespaces
Namespaces in C++ are used to organize too many classes so that it can be easy to handle the application.
23

For accessing the class of a namespace, we need to use namespacename::classname. We can use using keyword so that
Page

we don't have to use complete name all the time.


Object Oriented Programming Through C++ Balaji Lanka,CSE

In C++, global namespace is the root namespace. The global::std will always refer to the namespace "std" of C++
Framework.

C++ namespace Example


Let's see the simple example of namespace which include variable and functions.

#include <iostream>
using namespace std;
namespace First {
void sayHello() {
cout<<"Hello First Namespace"<<endl; }
}
namespace Second {
void sayHello() {
cout<<"Hello Second Namespace"<<endl;
}
}
int main()
{
First::sayHello();
Second::sayHello();
return 0;
}

Default arguments in C++

Definition

A default argument is a value in the function declaration automatically assigned by the compiler if the
calling function does not pass any value to that argument.

Characteristics for defining the default arguments

Following are the rules of declaring default arguments -

The values passed in the default arguments are not constant. These values can be overwritten if the
value is passed to the function. If not, the previously declared value retains.

During the calling of function, the values are copied from left to right.

All the values that will be given default value will be on the right.

#include<iostream>
using namespace std;
int sum(int x, int y, int z=0, int w=0) // Here there are two values in the default arguments
{ // Both z and w are initialised to zero
return (x + y + z + w); // return sum of all parameter values
}
24

int main()
{
Page

cout << sum(10, 15) << endl; // x = 10, y = 15, z = 0, w = 0


Object Oriented Programming Through C++ Balaji Lanka,CSE

cout << sum(10, 15, 25) << endl; // x = 10, y = 15, z = 25, w = 0
cout << sum(10, 15, 25, 30) << endl; // x = 10, y = 15, z = 25, w = 30
return 0;
}
Constant argument:

A constant argument is the one whose modification cannot take place by the function. Furthermore, in
order to make an argument constant to a function, the use of a keyword const can take place like- int sum (const
int a, const int b).

#include<iostream>
using namespace std;
float area(int r,const int pi=3.14);// function declaration
int main()
{
int r;
cout<<"Enter radius of a circle:";
cin>>r;
cout<<"The area of circle is :"<<area(r);
return 0;
}
float area(int r,const int pi)
{
return pi*r*r;
//pi++ cannot be done as it is constant;
}

Reference argument:

#include <iostream>
using namespace std;
void swap(int &x, int &y);
int main ()
{
int a = 100;
int b = 200;
cout<< "Before swap, value of a :" << a <<endl;
cout<< "Before swap, value of b :" << b <<endl;
swap(a, b);
cout<< "After swap, value of a :" << a <<endl;
cout<< "After swap, value of b :" << b <<endl;
return 0;
}
void swap(int &x, int &y)
{
int temp;
temp = x;
x = y;
y = temp;
}

Object-Oriented Programming In C++


25
Page
Object Oriented Programming Through C++ Balaji Lanka,CSE

Object-oriented programming revolves around data. The main programming unit of OOP is the object.
An object is a representation of a real-time entity and consists of data and methods or functions that
operate on data. This way, data, and functions are closely bound and data security is ensured.

In OOP, everything is represented as an object and when programs are executed, the objects interact
with each other by passing messages. An object need not know the implementation details of another
object for communicating.

Apart from objects, OOP supports various features which are listed below:
 Classes
 Encapsulation
 Abstraction
 Inheritance
 Polymorphism

Using OOP, we write programs using classes and objects by utilizing the above features. A
programming language is said to be a true object-oriented programming language if everything it
represents is using an object. Smalltalk is one language which is a pure object-oriented programming
language.

On the other hand, programming languages like C++, and Java are said to be partial object-oriented
programming languages.

Why C++ Is Partial OOP?

C++ language was designed with the main intention of using object-oriented features to C language.

Although C++ language supports the features of OOP like Classes, objects, inheritance,
encapsulation, abstraction, and polymorphism, there are few reasons because of which C++ is
classified as a partial object-oriented programming language.

We present a few of these reasons below:

#1) Creation of class/objects is Optional

In C++, the main function is mandatory and is always outside the class. Hence, we can have only one
main function in the program and can do without classes and objects.

This is the first violation of Pure OOP language where everything is represented as an object.

#2) Use of Global Variables


C++ has a concept of global variables that are declared outside the program and can be accessed by
any other entity of the program. This violates encapsulation. Though C++ supports encapsulation with
respect to classes and objects, it doesn’t take care of it in case of global variables.

#3) Presence of a Friend Function

C++ supports a friend class or function that can be used to access private and protected members of
other classes by making them a friend. This is yet another feature of C++ that violates OOP paradigm.
26

To conclude, although C++ supports all the OOP features mentioned above, it also provides features
that can act as a workaround for these features, so that we can do without them. This makes C++ a
Page

partial Object-oriented programming language.


Object Oriented Programming Through C++ Balaji Lanka,CSE

OOP Features

Here we will introduce various OOP features that are used for programming.

Classes & Objects

An object is a basic unit in object-oriented programing. An object contains data and methods or
functions that operate on that data. Objects take up space in memory.

A class, on the other hand, is a blueprint of the object. Conversely, an object can be defined as an
instance of a class. A class contains a skeleton of the object and does not take any space in the
memory.

Let us take an Example of a car object. A car object named “Maruti” can have data such as color;
make, model, speed limit, etc. and functions like accelerate. We define another object “ford”. This can
have similar data and functions like that of the previous object plus some more additions.
Similarly, we can have numerous objects of different names having similar data and functions and
some minor variations.

Thus instead of defining these similar data and functions in these different objects, we define a
blueprint of these objects which is a class called Car. Each of the objects above will be instances of
this class car.

Abstraction

Abstraction is the process of hiding irrelevant information from the user. For Example, when we are
driving the car, first we start the engine by inserting a key. We are not aware of the process that goes
on in the background for starting the engine.
Using abstraction in programming, we can hide unnecessary details from the user. By using
abstraction in our application, the end user is not affected even if we change the internal
implementation.

Encapsulation

Encapsulation is the process using which data and the methods or functions operating on them are
bundled together. By doing this, data is not easily accessible to the outside world. In OOP we achieve
encapsulation by making data members as private and having public functions to access these data
members.

Inheritance

Using inheritance object of one class can inherit or acquire the properties of the object of another
class. Inheritance provides reusability of code.

As such we can design a new class by acquiring the properties and functionality of another class and
in this process, we need not modify the functionality of the parent class. We only add new functionality
27

to the class.
Page
Object Oriented Programming Through C++ Balaji Lanka,CSE

Polymorphism

Polymorphism means many forms.

Polymorphism is an important feature of OOP and is usually implemented as operator overloading or


function overloading. Operator overloading is a process in which an operator behaves differently in
different situations. Similarly, in function overloading, the same function behaves differently in different
situations.

Dynamic Binding

OOP supports dynamic binding in which function call is resolved at runtime. This means that the code
to be executed as a result of a function call is decided at runtime. Virtual functions are an example of
dynamic binding.

Message Passing

In OOP, objects communicate with each other using messages. When objects communicate,
information is passed back and forth between the objects. A message generally consists of the object
name, method name and actual data that is to be sent to another object.

Advantages Of OOP

Let us discuss some of the advantages of OOP.

#1) Reusability

OOP allows the existing code to be reused through inheritance. We can easily acquire the existing
functionality and improve on it without having to rewrite the code again. This results in less bloated
code.

#2) Modularity

As we modularize the program in OOP, it’s easy to modify or troubleshoot the program if a problem
occurs or new feature or enhancement is to be added. Modularization also helps in code clarity and
makes it more readable.

#3) Flexibility

OOP helps us with flexible programming using the polymorphism feature. As polymorphism takes
many forms, we can have operators or functions that will work with many objects and thus save us
from writing different functions for each object.

#4) Maintainability

Maintaining code is easier as it is easy to add new classes, objects, etc without much restructuring or
changes.
28

#5) Data and Information Hiding


Page
Object Oriented Programming Through C++ Balaji Lanka,CSE

OOP aids us in data hiding thereby keeping information safe from leaking. Only the data that is
required for the smooth functioning of the program are exposed to the user by hiding intrinsic details.

29
Page

You might also like