OOP Unit-1 Notes
OOP Unit-1 Notes
Unit-1
Programming Paradigms
The programming paradigm is the way of writing computer programs. There are four programming
paradigms and they are as follows.
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.
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.
Page
Procedure-oriented Object-oriented
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.
There is no concept of friend function and virtual functions. It has the concept of friend
function and virtual functions.
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
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
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
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
+ Addition 10 + 5 = 15
- Subtraction 10 - 5 = 5
* Multiplication 10 * 5 = 50
/ Division 10 / 5 = 2
< 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
!= Returns TRUE if both values are not equal otherwise returns FALSE 10 != 5 is
TRUE
&& Logical AND - Returns TRUE if all conditions are TRUE 10 < 5 && 12 > 10 is
otherwise returns FALSE FALSE
! Logical NOT - Returns TRUE if condition is FLASE and returns !(10 < 5 && 12 > 10) is
FALSE if it is TRUE TRUE
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.
+= 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
& 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
^ the result of Bitwise XOR is 0 if all the bits are same otherwise it is 1 A^B
⇒ 13 (01101)
<< 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)
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.
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
Unary Operators
Binary Operators
Ternary Operators
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.
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.
A list of 30 Keywords in C++ Language which are not available in C language are given below.
10
Page
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:
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
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
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. }
Output:
12
It is odd number
Page
Object Oriented Programming Through C++ Balaji Lanka,CSE
Output:
Enter a number:11
It is odd number
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. }
8. {
9. cout<<"wrong number";
Page
10. }
Object Oriented Programming Through C++ Balaji Lanka,CSE
Output:
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. }
4. int num;
Object Oriented Programming Through C++ Balaji Lanka,CSE
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.
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.
#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";
}
}
}
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
}
#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);
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.
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
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.
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. }
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.
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
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.
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.
#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.
#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.
#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
In C++, global namespace is the root namespace. The global::std will always refer to the namespace "std" of C++
Framework.
#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;
}
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.
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, 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 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.
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.
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.
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
OOP Features
Here we will introduce various OOP features that are used for programming.
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
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
#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
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