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

UNIT 2 OOP Notes

Object oriented programming notes handwriting notes

Uploaded by

sammholder547
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)
13 views

UNIT 2 OOP Notes

Object oriented programming notes handwriting notes

Uploaded by

sammholder547
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/ 50

UNIT 02

User-Defined DataTypes: The data types that are defined by the user are called the
derived datatype or user-defined derived data type.
These types include:
 Class
 Structure
 Union
 Enumeration
 Typedef defined Data Type
Class: The building block of C++ that leads to Object-Oriented programming is a Class. It
is a user-defined data type, which holds its own data members and member functions,
which can be accessed and used by creating an instance of that class. A class is like a
blueprint for an object.

Structure: A structure is a user defined data type in C/C++. A structure creates a data type
that can be used to group items of possibly different types into a single type.
Syntax:
struct address {

char name[50];

char street[100];

char city[50];

char state[20];
int pin;

};

Union: Like Structures, union is a user defined data type. In union, all members share the
same memory location. For example in the following C program, both x and y share the
same location. If we change x, we can see the changes being reflected in y.
Enumeration: Enumeration (or enum) is a user defined data type in C. It is mainly used to
assign names to integral constants, the names make a program easy to read and maintain.
Syntax:
enum State {Working = 1, Failed = 0};

Example:
enum week_days{sun, mon, tues, wed, thur, fri, sat};

int main()

enum week_days d;

d = mon;

cout << d;

return 0;

}
Typedef : C++ allows you to define explicitly new data type names by using the keyword
typedef. Using typedef does not actually create a new data class, rather it defines a name for
an existing type. This can increase the portability(the ability of a program to be used across
different types of machines; i.e., mini, mainframe, micro, etc; without much changes into
the code)of a program as only the typedef statements would have to be changed. Using
typedef one can also aid in self-documenting code by allowing descriptive names for the
standard data types.
Syntax:
typedef type name;
Example
typedef int score;

int main()
{

score s1, s2;

s1 = 80;

cout << " " << b1;

return 0;

Benefits of User-Defined Data Types


1. User-Defined data types store data elements of either the same types or different types.
This gives more flexibility for the programmer to store different data types in a single
variable as per their needs and requirements.
2. Encapsulation – In Java/Python the variables and data values stored in User Defined Data
types are hidden from other classes as per their accessibility declaration i.e. public,
private, protected. The data values remain hidden and safe.
3. Flexibility – They provide us the ability to create a data structure as per our requirements
and needs.
4. Reusability – Once defined, these data types can be reused within many definitions,
saving coding time.
Derived Data Types
The data-types that are derived from the primitive or built-in datatypes are referred to as
Derived Data Types. These can be of four types namely:
 Function
 Array
 Pointers
 References
 Function: A function is a block of code or program-segment that is defined to
perform a specific well-defined task. A function is generally defined to save the user
from writing the same lines of code again and again for the same input. All the lines
of code are put together inside a single function and this can be called anywhere
required. main() is a default function that is defined in every program of C++.
 Syntax:
 FunctionType FunctionName(parameters)
void function ();
 The example mentioned below contains the data type for its functions as the function
returning int. Here is how the code will be:
 int add()
 {
 int x=10, y=10, z;
 z=x+y;
 return z;
 }
Array: An array is a collection of items stored at continuous memory locations. The idea of
array is to represent many instances in one variable. An array is one of the most frequently
used data types (derived) in the C language. We can form arrays by collecting various
primitive data types such as int, float, char, etc. Thus, when we create a collection of these
data types and store them in the contiguous memory location, they are known as arrays.
We can create an array with any valid and complete data type. An array type will only get
completed when the types and numbers of the array members are implicitly or explicitly
specified. We can complete the member types in the same compilation unit or a different one.
Syntax:
DataType ArrayName[size_of_array];
Pointers: Pointers are symbolic representation of addresses. They enable programs to
simulate call-by-reference as well as to create and manipulate dynamic data structures. The
pointers are also derived data types in the C language. The size that a pointer takes up in the
memory is always pretty much fixed. Still, the type of pointer that we get depends entirely on
the type of that element for which it stores the address. Thus, it‟s like if the pointer stores the
address of an available integer, then the pointer type would be equal to the integer point. On
the other hand, if the pointer happens to store an array‟s address, then the pointer type would
be equal to the array pointer. It‟s general declaration in C/C++ has the format:
Syntax:
datatype *var_name;

Reference: When a variable is declared as reference, it becomes an alternative name


for an existing variable. A variable can be declared as reference by putting „&‟ in
the declaration.
Abstract Data Types
before understanding what ADT is let us consider different in-built data types that are
provided to us. Data types such as int, float, double, long, etc. are considered to be in-built
data types and we can perform basic operations with them such as addition, subtraction,
division, multiplication, etc. Now there might be a situation when we need operations for
our user-defined data type which have to be defined. These operations can be defined only
as and when we require them. So, in order to simplify the process of solving problems, we
can create data structures along with their operations, and such data structures that are not
in-built are known as Abstract Data Type (ADT). Abstract Data type (ADT) is a type (or
class) for objects whose behavior is defined by a set of values and a set of operations. The
definition of ADT only mentions what operations are to be performed but not how these
operations will be implemented. It does not specify how data will be organized in memory
and what algorithms will be used for implementing the operations. It is called “abstract”
because it gives an implementation-independent view.
The process of providing only the essentials and hiding the details is known as abstraction.

The user of data type does not need to know how that data type is implemented, for
example, we have been using Primitive values like int, float, char data types only with the
knowledge that these data type can operate and be performed on without any idea of how
they are implemented.
So a user only needs to know what a data type can do, but not how it will be implemented.
Think of ADT as a black box which hides the inner structure and design of the data type.
Now we‟ll define three ADTs namely List ADT, Stack ADT, Queue ADT.
1. List ADT

 The data is generally stored in key sequence in a list which has a head structure
consisting of count, pointers and address of compare function needed to compare the
data in the list.
 The data node contains the pointer to a data structure and a self-referential
pointer which points to the next node in the list.
 The List ADT Functions is given below:
 get() – Return an element from the list at any given position.
 insert() – Insert an element at any position of the list.
 remove() – Remove the first occurrence of any element from a non-empty list.
 removeAt() – Remove the element at a specified location from a non-empty list.
 replace() – Replace an element at any position by another element.
 size() – Return the number of elements in the list.
 isEmpty() – Return true if the list is empty, otherwise return false.
 isFull() – Return true if the list is full, otherwise return false.
2. Stack ADT
 In Stack ADT Implementation instead of data being stored in each node, the pointer to
data is stored.
 The program allocates memory for the data and address is passed to the stack ADT.
 The head node and the data nodes are encapsulated in the ADT. The calling function
can only see the pointer to the stack.
 The stack head structure also contains a pointer to top and count of number of entries
currently in stack.
 push() – Insert an element at one end of the stack called top.
 pop() – Remove and return the element at the top of the stack, if it is not empty.
 peek() – Return the element at the top of the stack without removing it, if the stack is
not empty.
 size() – Return the number of elements in the stack.
 isEmpty() – Return true if the stack is empty, otherwise return false.
 isFull() – Return true if the stack is full, otherwise return false.
3. Queue ADT

 The queue abstract data type (ADT) follows the basic design of the stack abstract data
type.
 Each node contains a void pointer to the data and the link pointer to the next element in
the queue. The program‟s responsibility is to allocate memory for storing the data.
 enqueue() – Insert an element at the end of the queue.
 dequeue() – Remove and return the first element of the queue, if the queue is not empty.
 peek() – Return the element of the queue without removing it, if the queue is not empty.
 size() – Return the number of elements in the queue.
 isEmpty() – Return true if the queue is empty, otherwise return false.
 isFull() – Return true if the queue is full, otherwise return false.
Features of ADT: Abstract data types (ADTs) are a way of encapsulating data and
operations on that data into a single unit. Some of the key features of ADTs include:
 Abstraction: The user does not need to know the implementation of the data structure
only essentials are provided.
 Better Conceptualization: ADT gives us a better conceptualization of the real world.
 Robust: The program is robust and has the ability to catch errors.
 Encapsulation: ADTs hide the internal details of the data and provide a public interface
for users to interact with the data. This allows for easier maintenance and modification
of the data structure.
 Data Abstraction: ADTs provide a level of abstraction from the implementation details
of the data. Users only need to know the operations that can be performed on the data,
not how those operations are implemented.
 Data Structure Independence: ADTs can be implemented using different data
structures, such as arrays or linked lists, without affecting the functionality of the ADT.
 Information Hiding: ADTs can protect the integrity of the data by allowing access
only to authorized users and operations. This helps prevent errors and misuse of the
data.
 Modularity: ADTs can be combined with other ADTs to form larger, more complex
data structures. This allows for greater flexibility and modularity in programming.
Overall, ADTs provide a powerful tool for organizing and manipulating data in a structured
and efficient manner.
Abstract data types (ADTs) have several advantages and disadvantages that should be
considered when deciding to use them in software development. Here are some of the main
advantages and disadvantages of using ADTs:
Advantages:
 Encapsulation: ADTs provide a way to encapsulate data and operations into a single
unit, making it easier to manage and modify the data structure.
 Abstraction: ADTs allow users to work with data structures without having to know
the implementation details, which can simplify programming and reduce errors.
 Data Structure Independence: ADTs can be implemented using different data
structures, which can make it easier to adapt to changing needs and requirements.
 Information Hiding: ADTs can protect the integrity of data by controlling access and
preventing unauthorized modifications.
 Modularity: ADTs can be combined with other ADTs to form more complex data
structures, which can increase flexibility and modularity in programming.
Disadvantages:
 Overhead: Implementing ADTs can add overhead in terms of memory and processing,
which can affect performance.
 Complexity: ADTs can be complex to implement, especially for large and complex
data structures.
 Learning Curve: Using ADTs requires knowledge of their implementation and usage,
which can take time and effort to learn.
 Limited Flexibility: Some ADTs may be limited in their functionality or may not be
suitable for all types of data structures.
 Cost: Implementing ADTs may require additional resources and investment, which can
increase the cost of development.
Overall, the advantages of ADTs often outweigh the disadvantages, and they are widely
used in software development to manage and manipulate data in a structured and efficient
way. However, it is important to consider the specific needs
and requirements of a project when deciding whether to use ADTs.
From these definitions, we can clearly see that the definitions do not specify how these
ADTs will be represented and how the operations will be carried out. There can be different
ways to implement an ADT, for example, the List ADT can be implemented using arrays,
or singly linked list or doubly linked list. Similarly, stack ADT and Queue ADT can be
implemented using arrays or linked lists.
C++ Operators
Operators are symbols that perform operations on variables and values. For example, + is an
operator used for addition, while - is an operator used for subtraction.
Operators in C++ can be classified into 6 types:
1. Arithmetic Operators
2. Assignment Operators
3. Relational Operators
4. Logical Operators
5. Bitwise Operators
6. Other Operators
1. C++ Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on variables and data. For
example,

a + b;

Here, the + operator is used to add two variables a and b. Similarly there are various other
arithmetic operators in C++.

Operator Operation

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulo Operation (Remainder after division)

Example 1: Arithmetic Operators


#include <iostream>
using namespace std;

int main() {
int a, b;
a = 7;
b = 2;

// printing the sum of a and b


cout << "a + b = " << (a + b) << endl;

// printing the difference of a and b


cout << "a - b = " << (a - b) << endl;
// printing the product of a and b
cout << "a * b = " << (a * b) << endl;

// printing the division of a by b


cout << "a / b = " << (a / b) << endl;

// printing the modulo of a by b


cout << "a % b = " << (a % b) << endl;

return 0;
}
Run Code
Output

a+b=9
a-b=5
a * b = 14
a/b=3
a%b=1

Here, the operators +, - and * compute addition, subtraction, and multiplication respectively
as we might have expected.
/ Division Operator
Note the operation (a / b) in our program. The / operator is the division operator.
As we can see from the above example, if an integer is divided by another integer, we will get
the quotient. However, if either divisor or dividend is a floating-point number, we will get the
result in decimals.

In C++,

7/2 is 3
7.0 / 2 is 3.5
7 / 2.0 is 3.5
7.0 / 2.0 is 3.5

% Modulo Operator
The modulo operator % computes the remainder. When a = 9 is divided by b = 4, the
remainder is 1.

Note: The % operator can only be used with integers.

Increment and Decrement Operators


C++ also provides increment and decrement operators: ++ and -- respectively.
 ++ increases the value of the operand by 1
 -- decreases it by 1
For example,

int num = 5;

// increment operator
++num; // 6

Here, the code ++num; increases the value of num by 1.


Example 2: Increment and Decrement Operators
// Working of increment and decrement operators

#include <iostream>
using namespace std;

int main() {
int a = 10, b = 100, result_a, result_b;

// incrementing a by 1 and storing the result in result_a


result_a = ++a;
cout << "result_a = " << result_a << endl;
// decrementing b by 1 and storing the result in result_b
result_b = --b;
cout << "result_b = " << result_b << endl;

return 0;
}
Run Code
Output

result_a = 11
result_b = 99

In the above program, we have used the ++ and -- operators as prefixes (++a and --b).
However, we can also use these operators as postfix (a++ and b--).
To learn more, visit increment and decrement operators.
2. C++ Assignment Operators
In C++, assignment operators are used to assign values to variables. For example,

// assign 5 to a
a = 5;

Here, we have assigned a value of 5 to the variable a.

Operator Example Equivalent to

= a = b; a = b;

+= a += b; a = a + b;

-= a -= b; a = a - b;

*= a *= b; a = a * b;

/= a /= b; a = a / b;
%= a %= b; a = a % b;

Example 3: Assignment Operators


#include <iostream>
using namespace std;

int main() {
int a, b;

// 2 is assigned to a
a = 2;

// 7 is assigned to b
b = 7;

cout << "a = " << a << endl;


cout << "b = " << b << endl;
cout << "\nAfter a += b;" << endl;

// assigning the sum of a and b to a


a += b; // a = a +b
cout << "a = " << a << endl;

return 0;
}
Run Code
Output

a=2
b=7

After a += b;
a=9
3. C++ Relational Operators
A relational operator is used to check the relationship between two operands. For example,

// checks if a is greater than b


a > b;

Here, > is a relational operator. It checks if a is greater than b or not.


If the relation is true, it returns 1 whereas if the relation is false, it returns 0.

Operator Meaning Example

== Is Equal To 3 == 5 gives us false

!= Not Equal To 3 != 5 gives us true

> Greater Than 3 > 5 gives us false

< Less Than 3 < 5 gives us true

>= Greater Than or Equal To 3 >= 5 give us false

<= Less Than or Equal To 3 <= 5 gives us true

Example 4: Relational Operators


#include <iostream>
using namespace std;

int main() {
int a, b;
a = 3;
b = 5;
bool result;
result = (a == b); // false
cout << "3 == 5 is " << result << endl;

result = (a != b); // true


cout << "3 != 5 is " << result << endl;

result = a > b; // false


cout << "3 > 5 is " << result << endl;

result = a < b; // true


cout << "3 < 5 is " << result << endl;

result = a >= b; // false


cout << "3 >= 5 is " << result << endl;

result = a <= b; // true


cout << "3 <= 5 is " << result << endl;

return 0;
}
Run Code
Output

3 == 5 is 0
3 != 5 is 1
3 > 5 is 0
3 < 5 is 1
3 >= 5 is 0
3 <= 5 is 1

Note: Relational operators are used in decision-making and loops.


4. C++ Logical Operators
Logical operators are used to check whether an expression is true or false. If the expression
is true, it returns 1 whereas if the expression is false, it returns 0.

Operator Example Meaning

expression1 && Logical AND.


&&
expression2 True only if all the operands are true.

Logical OR.
|| expression1 || expression2 True if at least one of the operands is
true.

Logical NOT.
! !expression
True only if the operand is false.

In C++, logical operators are commonly used in decision making. To further understand the
logical operators, let's see the following examples,

Suppose,
a=5
b=8

Then,

(a > 3) && (b > 5) evaluates to true


(a > 3) && (b < 5) evaluates to false

(a > 3) || (b > 5) evaluates to true


(a > 3) || (b < 5) evaluates to true
(a < 3) || (b < 5) evaluates to false

!(a < 3) evaluates to true


!(a > 3) evaluates to false
Example 5: Logical Operators
#include <iostream>
using namespace std;

int main() {
bool result;

result = (3 != 5) && (3 < 5); // true


cout << "(3 != 5) && (3 < 5) is " << result << endl;

result = (3 == 5) && (3 < 5); // false


cout << "(3 == 5) && (3 < 5) is " << result << endl;

result = (3 == 5) && (3 > 5); // false


cout << "(3 == 5) && (3 > 5) is " << result << endl;

result = (3 != 5) || (3 < 5); // true


cout << "(3 != 5) || (3 < 5) is " << result << endl;

result = (3 != 5) || (3 > 5); // true


cout << "(3 != 5) || (3 > 5) is " << result << endl;

result = (3 == 5) || (3 > 5); // false


cout << "(3 == 5) || (3 > 5) is " << result << endl;

result = !(5 == 2); // true


cout << "!(5 == 2) is " << result << endl;

result = !(5 == 5); // false


cout << "!(5 == 5) is " << result << endl;

return 0;
}
Run Code
Output

(3 != 5) && (3 < 5) is 1
(3 == 5) && (3 < 5) is 0
(3 == 5) && (3 > 5) is 0
(3 != 5) || (3 < 5) is 1
(3 != 5) || (3 > 5) is 1
(3 == 5) || (3 > 5) is 0
!(5 == 2) is 1
!(5 == 5) is 0

Explanation of logical operator program


 (3 != 5) && (3 < 5) evaluates to 1 because both operands (3 != 5) and (3 < 5) are 1 (true).
 (3 == 5) && (3 < 5) evaluates to 0 because the operand (3 == 5) is 0 (false).
 (3 == 5) && (3 > 5) evaluates to 0 because both operands (3 == 5) and (3 > 5) are 0 (false).
 (3 != 5) || (3 < 5) evaluates to 1 because both operands (3 != 5) and (3 < 5) are 1 (true).
 (3 != 5) || (3 > 5) evaluates to 1 because the operand (3 != 5) is 1 (true).
 (3 == 5) || (3 > 5) evaluates to 0 because both operands (3 == 5) and (3 > 5) are 0 (false).
 !(5 == 2) evaluates to 1 because the operand (5 == 2) is 0 (false).
 !(5 == 5) evaluates to 0 because the operand (5 == 5) is 1 (true).

5. C++ Bitwise Operators


In C++, bitwise operators are used to perform operations on individual bits. They can only be
used alongside char and int data types.

Operator Description

& Binary AND


| Binary OR

^ Binary XOR

~ Binary One's Complement

<< Binary Shift Left

>> Binary Shift Right

6. Other C++ Operators


Here's a list of some other common operators available in C++. We will learn about them in

Operator Description Example

sizeof returns the size of data type sizeof(int); // 4

string result = (5 > 0) ? "even" :


?: returns value based on the condition
"odd"; // "even"

represents memory address of the


& &num; // address of num
operand

accesses members of struct variables


. s1.marks = 92;
or class objects

used with pointers to access the class


-> ptr->marks = 92;
or struct variables

<< prints the output value cout << 5;

>> gets the input value cin >> num;

later tutorials.
Boolean Logic
Boolean values on their own do not appear to be very useful, however when combined with
control statements they become one of the most powerful tools that any programing language
has to offer. As stated in the data types notes, boolean variables (bool) can be either true or
false. There are also binary operators that return a boolean value depending on specific
conditions. Some operators compare, such as ==, !=, >, etc., the values on either side of it and
return true if the entire statement is true. Others, work with boolean values to return another
boolean, such as && and ||.

Operator Symbol Usage Example

Returns true if the statements on either side of the


operator are the same value, otherwise it returns false.
Equals == x == 'A'
Can be used with int, double/float, char, boolean, and
string.

Returns true if the statements on either side of the


Not Equal != x != 2
operator are not the same, otherwise it returns false.

Returns true if the first term is greater than the second,


Greater
> otherwise it returns false. Note: If both terms are equal it x > 0
Than
returns false.

Returns true if the first term is less than the second,


Less Than < x < 10
otherwise it returns false.

Greater
Returns true if the first term is greater than or equal to the
Than or >= x >= 0
second, otherwise it returns false.
Equal

Less Than Returns true if the first term is less than or equal to the
<= x <= -2
or Equal second, otherwise it returns false.

x && True
Returns true if both terms on either side of the operator
(x == 2)
And && are true, otherwise it returns false. It is commonly used to
&& (y >=
concatenate statements together.
0)

Returns true if any of the terms on either side of the


Or || x || y
operator are true, otherwise it returns false.
Not ! Negates the value of the statement that follows it. !(x > 2)

Control Statements
Control Statements in C++:
In C++, Control Statements are usually jumped from one part of the C++ code to another
depending on whether a particular condition is satisfied or not. There are three types of C++
Control Statements are given as follows:
1. Sequence Statement
2. Selection Statement
3. Loop Statement
A C++ control statement redirects the flow of a program in order to execute additional code.
These statements come in the form of conditionals and loops.Each of them relies on a logical
condition that evaluates to a boolean value in order to run one piece of code over another.

1. if Statement
2. if-else Statement
3. Nested if Statement
4. if-else-if Ladder
5. switch Statement
6. Conditional Operator
7. Jump Statements:
 break
 continue
 goto
 return
if Statement:
The if statement is the simplest of the three and is used to run a certain piece of code nly if a
certain condition is true. For example: int x = 5;
if (x == 5) {
std::cout << "x is 5" << std::endl;
}
In this example, the block of code inside the curly braces will only be executed if the
condition inside the parentheses is true.
If-Else
If-Else statements allow the program to execute different blocks of code depending on
conditionals. All If statements have the following form:
if ( condition ) {
//body
}
An If statement executes the code in the body section if the condition evaluates to True,
otherwise it skips the body. When the condition evaluates to False, the program will either
test another condition with a following Else-if, run the code inside an Else statement, or
continue as normal if neither an Else-if nor Else block exist. An Else statement acts as a
default case for If statements. In the case that an If is directly followed by an Else and the
condition is false, the code in the Else is executed. Else statements do not have a condition
themselves.

if ( condition ) {
//body
} else {
// else body
}
An If statement can followed by any number of Else-if blocks. Each Else-if has its own
conditional statement and body of code. If an Else-if conditional is False, then its body of
code is skipped and the program will check the next Else-if in order that they appear. An If
followed by a long list of Else-IF's is usually referred to as an If-Else ladder.
if ( condition ) {
//body
} else if ( 2nd condition ) {
// else if body
} else {
// else body
}
Loops:
Loops are used in C++ to execute a block of code multiple times, either until a certain
condition is met or for a specific number of times. There are generally three types of loops in
C++: while, do-while, and for.
For Loop
A for loop allows for a block of code to be executed until a conditional becomes false. For
loops are usually used when a block of code needs to executed a fixed number of times. Each
loop consists of 3 parts, an initialization step, the conditional, and an iteration step. The
initialization is run before entering the loop, the condition is checked at the beginning of each
run through the loop ( including the first run ), and the iteration step executes at the end of
each pass through the loop, but before the condition is rechecked. It is usual practice to have
the iteration step move the loop on step closer to making the condition false, thus ending the
loop, but this does not need to be the case.
for( initialization ; conditional ; iteration ) {
// loop body
}
While Loop
A while loop is a simple loop that will run the same code over and over as long as a given
conditional is true. The condition is checked at the beginning of each run through the loop (
including the first one ). If the conditional is false for the beginning, the while loop will be
skipped all together.
while ( conditional ) {
// loop body
}
Do-while Loop
A do-while loop acts just like a while loop, except the condition is checked at the end of each
pass through the loop body. This means a do-while loop will execute at least once.
do {
// loop body
} while ( condition );
Break
Break is a useful keyword that allows the program to exit a loop or switch statement before
the expected end of a that code block. This is useful in error checking or if the outcome of a
loop is not certain. For example, the following code will break out of the for loop if a user
asks to leave.
string inputs[10];
string input;
for (int i = 0; i < 10; i++ ) {
cin >> input;
if ( input == "quit" ) {
break;
}
inputs[i] = input;
}
goto Statement
Syntax of goto statement:
goto pgr;
|||
pgr :
pgr is known as label. It is a user defined identifier. After the execution of goto statement, the
control transfers to the line after label pgr.
It is not a good programming to use goto statement in a program.
continue Statement
The continue statement is used in loops and causes a program to skip the rest of the body of
the loop.
while (condition)
{
statement 1;
If (condition)
continue ;
statement 2;
}
statement 3;
exit ( ) function
The execution of a program can be stopped at any point with exit ( ) and a status code can be
informed to the calling program. The general format is:
exit (code) ;
where code is an integer value. The code has a value 0 for correct execution. The value of the
code varies depending upon the operating system. It requires a process.h header file.
switch statement:
It is multiple branching statement where based on a condition, the control is transferred to
one of the many possible points. It has the following syntax:

 switch(expression)
 {
 case1:
 {
 action 1;
 }
 case 2:
 {
 action 2;
 }
 case 3:
 {
 action 3;
 }
 default:
 {
 default statement;

Functions in C++: Functions:-


A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
Functions are used to perform certain actions, and they are important for reusing code: Define
the code once, and use it many times.
Create a Function
C++ provides some pre-defined functions, such as main(), which is used to execute code. But
you can also create your own functions to perform certain actions.
To create (often referred to as declare) a function, specify the name of the function, followed
by parentheses ():
Syntax
void myFunction() {
// code to be executed
}
Example Explained
 myFunction() is the name of the function
 void means that the function does not have a return value. You will learn more about
return values later in the next chapter
 inside the function (the body), add code that defines what the function should do
Call a Function
Declared functions are not executed immediately. They are "saved for later use", and will be
executed later, when they are called.
To call a function, write the function's name followed by two parentheses () and a semicolon ;
In the following example, myFunction() is used to print a text (the action), when it is called:

Example
Inside main, call myFunction():
// Create a function
void myFunction() {
cout << "I just got executed!";
}
int main() {
myFunction(); // call the function
return 0;
}
// Outputs "I just got executed!"
A function can be called multiple times:
Example
void myFunction() {
cout << "I just got executed!\n";
}
int main() {
myFunction();
myFunction();
myFunction();
return 0;
}
// I just got executed!
// I just got executed!
// I just got executed!
Function Declaration and Definition
A C++ function consist of two parts:
 Declaration: the return type, the name of the function, and parameters (if any)
 Definition: the body of the function (code to be executed)
void myFunction()
{ // declaration
// the body of the function (definition)
}
If a user-defined function, such as myFunction() is declared after the main() function, an
error will occur:
Example
int main() {
myFunction();
return 0;
}
void myFunction()
{
cout << "I just got executed!";
}
You will often see C++ programs that have function declaration above main(), and function
definition below main(). This will make the code better organized and easier to read:
Example
// Function declaration
void myFunction();
// The main method
int main() {
myFunction(); // call the function
return 0;
}
// Function definition
void myFunction() {
cout << "I just got executed!";
}
A function is a block of code that performs a specific task.
Suppose we need to create a program to create a circle and color it. We can create two
functions to solve this problem:
 a function to draw the circle
 a function to color the circle
Dividing a complex problem into smaller chunks makes our program easy to understand and
reusable.
There are two types of function:
1. Standard Library Functions: Predefined in C++
2. User-defined Function: Created by users
In this tutorial, we will focus mostly on user-defined functions.
C++ User-defined Function
C++ allows the programmer to define their own function.
A user-defined function groups code to perform a specific task and that group of code is
given a name (identifier).
When the function is invoked from any part of the program, it all executes the codes defined
in the body of the function.
C++ Function Declaration
The syntax to declare a function is:
returnType functionName (parameter1, parameter2,...) {
// function body
}

Here's an example of a function declaration.


// function declaration

void greet() {
cout << "Hello World";
}

Here,
 the name of the function is greet()
 the return type of the function is void
 the empty parentheses mean it doesn't have any parameters
 the function body is written inside {}

Note: We will learn about returnType and parameters later in this tutorial.

Calling a Function
In the above program, we have declared a function named greet(). To use
the greet() function, we need to call it.
Here's how we can call the above greet() function.

int main() {

// calling a function
greet();

Example 1: Display a Text


#include <iostream>
using namespace std;

// declaring a function
void greet() {
cout << "Hello there!";
}
int main() {

// calling the function


greet();

return 0;
}
Output

Hello there!

Function Parameters
s mentioned above, a function can be declared with parameters (arguments). A parameter is a
value that is passed when declaring a function.
For example, let us consider the function below:

void printNum(int num) {


cout << num;
}

Here, the int variable num is the function parameter.


We pass a value to the function parameter while calling the function.

nt main() {
int n = 7;

// calling the function


// n is passed to the function as argument
printNum(n);

return 0;
}

Example 2: Function with Parameters


// program to print a text

#include <iostream>
using namespace std;

// display a number
void displayNum(int n1, float n2) {
cout << "The int number is " << n1;
cout << "The double number is " << n2;
}

int main() {

int num1 = 5;
double num2 = 5.5;

// calling the function


displayNum(num1, num2);

return 0;
}
Run Code
Output

The int number is 5


The double number is 5.5
In the above program, we have used a function that has one int parameter and
one double parameter.
We then pass num1 and num2 as arguments. These values are stored by the function
parameters n1 and n2 respectively.
Return Statement
In the above programs, we have used void in the function declaration. For example,

void displayNumber() {
// code
}

This means the function is not returning any value.


It's also possible to return a value from a function. For this, we need to specify
the returnType of the function during function declaration.
Then, the return statement can be used to return a value from a function.

For example,

int add (int a, int b) {


return (a + b);
}

Here, we have the data type int instead of void. This means that the function returns
an int value.
The code return (a + b); returns the sum of the two parameters as the function value.
The return statement denotes that the function has ended. Any code after return inside the
function is not executed.
Example 3: Add Two Numbers
// program to add two numbers using a function
#include <iostream>

using namespace std;

// declaring a function
int add(int a, int b) {
return (a + b);
}
int main() {
int sum;

// calling the function and storing


// the returned value in sum
sum = add(100, 78);
cout << "100 + 78 = " << sum << endl;

return 0;
}
Output

100 + 78 = 178

In the above program, the add() function is used to find the sum of two numbers.
We pass two int literals 100 and 78 while calling the function.
We store the returned value of the function in the variable sum, and then we print it.
Notice that sum is a variable of int type. This is because the return value of add() is
of int type.
Function Prototype
In C++, the code of function declaration should be before the function call. However, if we
want to define a function after the function call, we need to use the function prototype. For
example,

// function prototype
void add(int, int);
int main() {
// calling the function before declaration.
add(5, 3);
return 0;
}

// function definition
void add(int a, int b) {
cout << (a + b);
}

In the above code, the function prototype is:

void add(int, int);

This provides the compiler with information about the function name and its parameters.
That's why we can use the code to call a function before the function has been defined.
The syntax of a function prototype is:

returnType functionName(dataType1, dataType2, ...);

Example 4: C++ Function Prototype


// using function definition after main() function
// function prototype is declared before main()

#include <iostream>

using namespace std;

// function prototype
int add(int, int);
int main() {
int sum;

// calling the function and storing


// the returned value in sum
sum = add(100, 78);

cout << "100 + 78 = " << sum << endl;

return 0;
}

// function definition
int add(int a, int b) {
return (a + b);
}
Run Code
Output

100 + 78 = 178

The above program is nearly identical to Example 3. The only difference is that here, the
function is defined after the function call.
That's why we have used a function prototype in this example.

Benefits of Using User-Defined Functions


 Functions make the code reusable. We can declare them once and use them multiple times.
 Functions make the program easier as each small task is divided into a function.
 Functions increase readability.

C++ Library Functions


Library functions are the built-in functions in C++ programming.
Programmers can use library functions by invoking the functions directly; they don't need to
write the functions themselves.
Some common library functions in C++ are sqrt(), abs(), isdigit(), etc.
In order to use library functions, we usually need to include the header file in which these
library functions are defined.
For instance, in order to use mathematical functions such as sqrt() and abs(), we need to
include the header file cmath.

Example 5: C++ Program to Find the Square Root of a Number


#include <iostream>
#include <cmath>
using namespace std;

int main() {
double number, squareRoot;

number = 25.0;

// sqrt() is a library function to calculate the square root


squareRoot = sqrt(number);

cout << "Square root of " << number << " = " << squareRoot;

return 0;
}
Output

Square root of 25 = 5

In this program, the sqrt() library function is used to calculate the square root of a number.
The function declaration of sqrt() is defined in the cmath header file. That's why we need to
use the code #include <cmath> to use the sqrt() function.
C++ Overloading (Function and Operator)
If we create two or more members having the same name but different in number or type of
parameter, it is known as C++ overloading. In C++, we can overload:
o methods,
o constructors, and
o indexed properties
It is because these members have parameters only.
Types of overloading in C++ are:
o Function overloading
o Operator overloading

C++ Function Overloading


Function Overloading is defined as the process of having two or more function with the same
name, but different in parameters is known as function overloading in C++. In function
overloading, the function is redefined by using either different types of arguments or a
different number of arguments. It is only through these differences compiler can differentiate
between the functions.
The advantage of Function overloading is that it increases the readability of the program
because you don't need to use different names for the same action.
C++ Function Overloading Example
Let's see the simple example of function overloading where we are changing number of
arguments of add() method.
// program of function overloading when number of arguments vary.
#include <iostream>
using namespace std;
class Cal {
public:
static int add(int a,int b){
return a + b;
}
static int add(int a, int b, int c)
{
return a + b + c;
}
};
int main(void) {
Cal C; // class object declaration.
cout<<C.add(10, 20)<<endl;
cout<<C.add(12, 20, 23);
return 0;
}
Output:
30
55
Let's see the simple example when the type of the arguments vary.
// Program of function overloading with different types of arguments.
#include<iostream>
using namespace std;
int mul(int,int);
float mul(float,int);
int mul(int a,int b)
{
return a*b;
}
float mul(double x, int y)
{
return x*y;
}
int main()
{
int r1 = mul(6,7);
float r2 = mul(0.2,3);
std::cout << "r1 is : " <<r1<< std::endl;
std::cout <<"r2 is : " <<r2<< std::endl;
return 0;
}
Output:
r1 is : 42
r2 is : 0.6
Function Overloading and Ambiguity
When the compiler is unable to decide which function is to be invoked among the overloaded
function, this situation is known as function overloading.
When the compiler shows the ambiguity error, the compiler does not run the program.
Causes of Function Overloading:
o Type Conversion.
o Function with default arguments.
o Function with pass by reference.

o Type Conversion:
Let's see a simple example.
#include<iostream>
using namespace std;
void fun(int);
void fun(float); void fun(int i)
{
std::cout << "Value of i is : " <<i<< std::endl;
}
void fun(float j)
{
std::cout << "Value of j is : " <<j<< std::endl;
}
int main()
{
fun(12);
fun(1.2);
return 0;
}
The above example shows an error "call of overloaded 'fun(double)' is ambiguous". The
fun(10) will call the first function. The fun(1.2) calls the second function according to our
prediction. But, this does not refer to any function as in C++, all the floating point constants
are treated as double not as a float. If we replace float to double, the program works.
Therefore, this is a type conversion from float to double.
o Function with Default Arguments
Let's see a simple example.
#include<iostream>
using namespace std;
void fun(int);
void fun(int,int);
void fun(int i)
{
std::cout << "Value of i is : " <<i<< std::endl;
}
void fun(int a,int b=9)
{
std::cout << "Value of a is : " <<a<< std::endl;
std::cout << "Value of b is : " <<b<< std::endl;
}
int main()
{
fun(12);

return 0;
}
The above example shows an error "call of overloaded 'fun(int)' is ambiguous". The fun(int a,
int b=9) can be called in two ways: first is by calling the function with one argument, i.e.,
fun(12) and another way is calling the function with two arguments, i.e., fun(4,5). The fun(int
i) function is invoked with one argument. Therefore, the compiler could not be able to select
among fun(int i) and fun(int a,int b=9).
o Function with pass by reference
Let's see a simple example.
#include <iostream>
using namespace std;
void fun(int);
void fun(int &);
int main()
{
int a=10;
fun(a); // error, which f()?
return 0;
}
void fun(int x)
{
std::cout << "Value of x is : " <<x<< std::endl;
}
void fun(int &b)
{
std::cout << "Value of b is : " <<b<< std::endl;
}
The above example shows an error "call of overloaded 'fun(int&)' is ambiguous". The first
function takes one integer argument and the second function takes a reference parameter as
an argument. In this case, the compiler does not know which function is needed by the user as
there is no syntactical difference between the fun(int) and fun(int &).
Friend Function in C++
Introduction
In this tutorial, we will learn how to create a friend function in C++ with the help of some
examples.
Data hiding is a fundamental concept in object-oriented programming, and it restricts the
access of private members from outside the class.
What is a Friend Function in C++?
A friend function in C++ is defined as a function that can access private, protected and public
members of a class.
The friend function is declared using the friend keyword inside the body of the class.
Friend Function Syntax:
class className {
... .. ...
friend returnType functionName(arguments);
... .. ...
}
By using the keyword, the ‘friend’ compiler understands that the given function is a friend
function.
We declare friend function inside the body of a class, whose private and protective data needs
to be accessed, starting with the keyword friend to access the data. We use them when we
need to operate between two different classes at the same time.
What is Friend Function?
Friend functions of the class are granted permission to access private and protected
members of the class in C++. They are defined globally outside the class scope. Friend
functions are not member functions of the class. So, what exactly is the friend function?
A friend function in C++ is a function that is declared outside a class but is capable of
accessing the private and protected members of the class. There could be situations in
programming wherein we want two classes to share their members. These members may be
data members, class functions or function templates. In such cases, we make the desired
function, a friend to both these classes which will allow accessing private and protected data
of members of the class.
Generally, non-member functions cannot access the private members of a particular class.
Once declared as a friend function, the function is able to access the private and the protected
members of these classes.
Friend functions in C++ have the following types
 Function with no argument and no return value
 Function with no argument but with return value
 Function with argument but no return value
 Function with argument and return value
Declaration of friend function in C++
class class_name
{
friend data_type function_name(argument/s); // syntax of friend function.
};
In the above declaration, the friend function is preceded by the keyword friend. The function
can be defined anywhere in the program like a normal C++ function. The function definition
does not use either the keyword friend or scope resolution operator.

Use of Friend function in C++


As discussed, we require friend functions whenever we have to access the private or
protected members of a class. This is only the case when we do not want to use the objects of
that class to access these private or protected members.
To understand this better, let us consider two classes: Tokyo and Rio. We might require a
function, metro(), to access both these classes without any restrictions. Without the friend
function, we will require the object of these classes to access all the members. Friend
functions in c++ help us avoid the scenario where the function has to be a member of either
of these classes for access.
Characteristics of Friend Function in C++
 The function is not in the „scope‟ of the class to which it has been declared a friend.
 Friend functionality is not restricted to only one class
 Friend functions can be a member of a class or a function that is declared outside the
scope of class.
 It cannot be invoked using the object as it is not in the scope of that class.
 We can invoke it like any normal function of the class.
 Friend functions have objects as arguments.
 It cannot access the member names directly and has to use dot membership operator
and use an object name with the member name.
 We can declare it either in the „public‟ or the „private‟ part.
 These are some of the friend functions in C++ characteristics
C++ friend function Example
Let's see the simple example of C++ friend function used to print the length of a box.
#include <iostream>
using namespace std;
class Box
{
private:
int length;
public:
Box(): length(0) { }
friend int printLength(Box); //friend function
};
int printLength(Box b)
{
b.length += 10;
return b.length;
}
int main()
{
Box b;
cout<<"Length of box: "<< printLength(b)<<endl;
return 0;
}
Output:
Length of box: 10
Let's see a simple example when the function is friendly to two classes.
#include <iostream>
using namespace std;
class B; // forward declarartion.
class A
{
int x;
public:
void setdata(int i)
{
x=i;
}
friend void min(A,B); // friend function.
};
class B
{
int y;
public:
void setdata(int i)
{
y=i;
}
friend void min(A,B); // friend function
};
void min(A a,B b)
{
if(a.x<=b.y)
std::cout << a.x << std::endl;
else
std::cout << b.y << std::endl;
}
int main()
{
A a;
B b;
a.setdata(10);
b.setdata(20);
min(a,b);
return 0;
}
Output:
10
In the above example, min() function is friendly to two classes, i.e., the min() function can
access the private members of both the classes A and B.
C++ Friend class
A friend class can access both private and protected members of the class in which it has
been declared as friend.
Let's see a simple example of a friend class.
#include <iostream>

using namespace std;


class A
{
int x =5;
friend class B; // friend class.
};
class B
{
public:
void display(A &a)
{
cout<<"value of x is : "<<a.x;
}
};
int main()
{
A a;
B b;
b.display(a);
return 0;
}
Output:
value of x is : 5
In the above example, class B is declared as a friend inside the class A. Therefore, B is a
friend of class A. Class B can access the private members of class A.
C++ virtual function
o A C++ virtual function is a member function in the base class that you redefine in a
derived class. It is declared using the virtual keyword.
o It is used to tell the compiler to perform dynamic linkage or late binding on the
function.
o There is a necessity to use the single pointer to refer to all the objects of the different
classes. So, we create the pointer to the base class that refers to all the derived objects.
But, when base class pointer contains the address of the derived class object, always
executes the base class function. This issue can only be resolved by using the 'virtual'
function.
o A 'virtual' is a keyword preceding the normal declaration of a function.
o When the function is made virtual, C++ determines which function is to be invoked at
the runtime based on the type of the object pointed by the base class pointer.
Rules of Virtual Function
Virtual functions must be members of some class.
Virtual functions cannot be static members.
They are accessed through object pointers.
They can be a friend of another class.
A virtual function must be defined in the base class, even though it is not used.
The prototypes of a virtual function of the base class and all the derived classes must
be identical. If the two functions with the same name but different prototypes, C++
will consider them as the overloaded functions.
We cannot have a virtual constructor, but we can have a virtual destructor
Consider the situation when we don't use the virtual keyword.
#include <iostream>
using namespace std;
class A
{
int x=5;
public:
void display()
{
std::cout << "Value of x is : " << x<<std::endl;
}
};
class B: public A
{
int y = 10;
public:
void display()
{
std::cout << "Value of y is : " <<y<< std::endl;
}
};
int main()
{
A *a;
B b;
a = &b;
a->display();
return 0;
}
Output:
Value of x is : 5
In the above example, * a is the base class pointer. The pointer can only access the base class
members but not the members of the derived class. Although C++ permits the base pointer to
point to any object derived from the base class, it cannot directly access the members of the
derived class. Therefore, there is a need for virtual function which allows the base pointer to
access the members of the derived class.
C++ virtual function Example
Let's see the simple example of C++ virtual function used to invoked the derived class in a
program.
#include <iostream>
{
public:
virtual void display()
{
cout << "Base class is invoked"<<endl;
}
};
class B:public A
{
public:
void display()
{
cout << "Derived Class is invoked"<<endl;
}
};
int main()
{
A* a; //pointer of base class
B b; //object of derived class
a = &b;
a->display(); //Late Binding occurs
}
Output:
Derived Class is invoked
Pure Virtual Function
o A virtual function is not used for performing any task. It only serves as a placeholder.
o When the function has no definition, such function is known as "do-nothing"
function.
o The "do-nothing" function is known as a pure virtual function. A pure virtual
function is a function declared in the base class that has no definition relative to the
base class.
o A class containing the pure virtual function cannot be used to declare the objects of its
own, such classes are known as abstract base classes.
o The main objective of the base class is to provide the traits to the derived classes and
to create the base pointer used for achieving the runtime polymorphism.

You might also like