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

Unit-4 OOSD Note

C++ is a general-purpose programming language that is widely used for competitive programming and runs on many platforms. It has both low-level and high-level features. The structure of a C++ program includes documentation, linking, definition, global declaration, function declaration, and main sections. Namespaces provide unique naming scopes to avoid name collisions between identifiers, while variables are names given to memory locations that can store changing values.

Uploaded by

rajputakshay8940
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)
47 views

Unit-4 OOSD Note

C++ is a general-purpose programming language that is widely used for competitive programming and runs on many platforms. It has both low-level and high-level features. The structure of a C++ program includes documentation, linking, definition, global declaration, function declaration, and main sections. Namespaces provide unique naming scopes to avoid name collisions between identifiers, while variables are names given to memory locations that can store changing values.

Uploaded by

rajputakshay8940
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/ 32

Basic of c++

C++ is a general-purpose programming language and is widely used nowadays for


competitive programming. It has imperative, object-oriented, and generic
programming features. C++ runs on lots of platforms like Windows, Linux, Unix,
Mac, etc.
Before explaining the basics of C++, we would like to clarify two more ideas: low-
level and high-level. To make it easy to understand, let’s consider this scenario –
when we go to the Google search engine and search for some queries, Google
displays some websites according to our question. Google does this for us at a
very high level. We don’t know what’s happening at the low level until we look into
Google servers (at a low level) and further to the level where the data is in the form
of 0s/1s. The point we want to make here is that a low level means nearest to the
hardware, and a high level means farther from the hardware with a lot of layers of
abstraction. C ++ is considered a low-level language as it is closer to hardware
than most general-purpose programming languages. However to become proficient
in any programming language, one Firstly needs to understand the basics of that
language.
program Structure of c++

The C++ program is written using a specific template structure. The structure of the
program written in C++ language is as follows:

Documentation Section:
• This section comes first and is used to document the logic of the program that
the programmer going to code.
• It can be also used to write for purpose of the program.
• Whatever written in the documentation section is the comment and is not
compiled by the compiler.
• Documentation Section is optional since the program can execute without them.
Below is the snippet of the same:

Linking Section:
• Generally, a program includes various programming elements like built-in
functions, classes, keywords, constants, operators, etc. that are already defined
in the standard C++ library.
• In order to use such pre-defined elements in a program, an appropriate header
must be included in the program.
• Standard headers are specified in a program through the preprocessor
directive #include. In Figure, the iostream header is used. When the compiler
processes the instruction #include<iostream>, it includes the contents of the
stream in the program. This enables the programmer to use standard input,
output, and error facilities that are provided only through the standard streams
defined in <iostream>. These standard streams process data as a stream of
characters, that is, data is read and displayed in a continuous flow. The
standard streams defined in <iostream> are listed here.

Definition Section:
• It is used to declare some constants and assign them some value.
• In this section, anyone can define your own datatype using primitive data types.
• In #define is a compiler directive which tells the compiler whenever the
message is found to replace it with “Factorial\n”.
• typedef int INTEGER; this statement tells the compiler that whenever you will
encounter INTEGER replace it by int and as you have declared INTEGER as
datatype you cannot use it as an identifier.

Global Declaration Section:
• Here, the variables and the class definitions which are going to be used in the
program are declared to make them global.
• The scope of the variable declared in this section lasts until the entire program
terminates.
• These variables are accessible within the user-defined functions also.

Function Declaration Section:
• It contains all the functions which our main functions need.
• Usually, this section contains the User-defined functions.
• This part of the program can be written after the main function but for this, write
the function prototype in this section for the function which for you are going to
write code after the main function.

Main Function:
• The main function tells the compiler where to start the execution of the program.
The execution of the program starts with the main function.
• All the statements that are to be executed are written in the main function.
• The compiler executes all the instructions which are written in the curly
braces {} which encloses the body of the main function.
• Once all instructions from the main function are executed, control comes out of
the main function and the program terminates and no further execution occur.
Namespace
• Namespace provide the space where we can define or declare identifier i.e.
variable, method, classes.
• Using namespace, you can define the space or context in which identifiers are
defined i.e. variable, method, classes. In essence, a namespace defines a
scope.

Advantage of Namespace to avoid name collision.

• Example, you might be writing some code that has a function called xyz() and
there is another library available which is also having same function xyz(). Now
the compiler has no way of knowing which version of xyz() function you are
referring to within your code.
• A namespace is designed to overcome this difficulty and is used as additional
information to differentiate similar functions, classes, variables etc. with the
same name available in different libraries.
• The best example of namespace scope is the C++ standard library (std) where
all the classes, methods and templates are declared. Hence while writing a C++
program we usually include the directive using namespace std;

Defining a Namespace

A namespace definition begins with the keyword namespace followed by the


namespace name as follows −

namespace namespace_name {
// code declarations
}
Advantage
The primary advantage of namespaces is that they resolve any naming conflict. For
example, sometimes, you may need more than one function with the same name.
And namespaces provide a way to declare such functions without making the
compiler ambiguous.

Disadvantage

The primary disadvantage of namespaces is that there can be conflicts when using
multiple libraries. This is because they may have namespaces with the same
names.
C++ Identifiers


In C++ programming language, identifiers are the unique names assigned to
variables, functions, classes, structs, or other entities within the program. For
example, in the below statement,

int num = 11;


num is an identifier.

Rules to Name of an Identifier in C++


We can use any word as an identifier as long as it follows the following rules:
1. An identifier can consist of letters (A-Z or a-z), digits (0-9), and underscores
(_). Special characters and spaces are not allowed.
2. An identifier can only begin with a letter or an underscore only.
3. C++ has reserved keywords that cannot be used as identifiers since they have
predefined meanings in the language. For example, int cannot be used as an
identifier as it has already some predefined meaning in C++. Attempting to use
these as identifiers will result in a compilation error.
4. Identifier must be unique in its namespace.

Difference between Keyword and Identifier

SR.
NO. KEYWORD IDENTIFIER

Keywords are predefined word Identifiers are the values used to


that gets reserved for working define different programming items
1 program that have special such as variables, integers, structures,
meaning and cannot get used unions and others and mostly have an
anywhere else. alphabetic character.

2 Specify the type/kind of entity. Identify the name of a particular entity.

It always starts with a lowercase First character can be a uppercase,


3
letter. lowercase letter or underscore.

A keyword should be in lower An identifier can be in upper case or


4
case. lower case.

A keyword contains only An identifier can consist of alphabetical


5
alphabetical characters. characters, digits and underscores.
SR.
NO. KEYWORD IDENTIFIER

They help to identify a specific They help to locate the name of the
6 property that exists within a entity that gets defined along with a
computer language. keyword.

No special symbol, punctuation No punctuation or special symbol


7
is used. except ‘underscore’ is used.

Examples of keywords are: int, Examples of identifiers are: Test,


8
char, if, while, do, class etc. count1, high_speed, etc.
C++ Variables


Variables in C++ is a name given to a memory location. It is the basic unit of storage
in a program.
• The value stored in a variable can be changed during program execution.
• A variable is only a name given to a memory location, all the operations done on
the variable effects that memory location.
• In C++, all the variables must be declared before use.

How to Declare Variables
A typical variable declaration is of the form:
// Declaring a single variable
type variable_name;

// Declaring multiple variables:


type variable1_name, variable2_name, variable3_name;

A variable name can consist of alphabets (both upper and lower case), numbers,
and the underscore ‘_’ character. However, the name must not start with a number.

Difference between Constant and Variables


The following table lists the differences between the constant and variables in C:

Constant Variables

A constant is a variable or value that cannot A variable is a name associated


be altered once defined. with some memory location.

A constant is used to hold the fixed values A variable is used to hold some
which we can retrieve later but cannot value that can be changed
change. according to the requirement.

The variables are stored inside a


The constants are generally stored in the data segment, heap, or stack
text segment as they are read-only depending on the environment it
is declared in.
Constant Variables

We can only assign a value to the constant We can assign value to the
while defining it. variable anytime.

A variable can only be defined


A constant can be defined by
using the standard variable
using #define or const keyword.
definition syntax.

Example: #define pi 3.14 Example: int var = 25;


const int pi = 3.14; var = 10;
Enumeration in C++
Enumeration (Enumerated type) is a user-defined data type that can be assigned
some limited values. These values are defined by the programmer at the time of
declaring the enumerated type.
If we assign a float value to a character value, then the compiler generates an
error. In the same way, if we try to assign any other value to the enumerated data
types, the compiler generates an error. Enumerator types of values are also known
as enumerators. It is also assigned by zero the same as the array. It can also be
used with switch statements.
Syntax:
enum enumerated-type-name
{
value1, value2, value3…..valueN
};
Why Do You Use Enums
Enums or enumerations are generally used when you expect the variable to select
one value from the possible set of values. It increases the abstraction and enables
you to focus more on values rather than worrying about how to store them. It is also
helpful for code documentation and readability purposes.

Advantages of Enums:

1. Readability and Maintainability: Enums enhance code readability by providing

self-descriptive names for a set of related values. By using enums, developers

can communicate the intention and meaning of the values more effectively. This

makes the code easier to understand and maintain, especially when multiple

developers are collaborating on a project.

Example 1:

enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,

SATURDAY, SUNDAY; }

The usage of Day.MONDAY is much more expressive than using a numeric

representation, such as 1.
2. Type Safety: Enums provide type safety by restricting the possible values to a

predefined set. This prevents errors caused by assigning invalid or unintended values

to variables. The compiler can detect and flag any attempts to assign values that are

not part of the enum, reducing runtime errors and improving code reliability.

Example 2:

enum Color { RED, GREEN, BLUE;}

Color myColor = Color.GREEN;

myColor = Color.YELLOW;

N/B: Compilation error: YELLOW is not a valid value

3. Code Consistency: Enums promote code consistency by ensuring that the same

set of values is used consistently throughout the codebase. By centralizing the

definition of a fixed set of values, enums help prevent typos or variations in different

parts of the code, leading to more reliable and maintainable software.

4. Compile-Time Validation: Enums undergo compile-time validation, which means

any errors or inconsistencies related to enum usage are caught during the

compilation process. This early detection of issues helps to reduce bugs and provides

immediate feedback to developers, allowing them to address problems before

deploying the code.

While enums have several advantages, it’s essential to consider their potential

disadvantages as well.
Disadvantages of Enums:

1. Lack of Extensibility: Enums have a fixed set of values defined at compile-time,

making it challenging to add or modify values dynamically at runtime. This

limitation can be problematic when dealing with situations that require flexibility or

when the set of values is subject to change.

Example: Consider the use case of Example 2.

2. Limited Representation: Enums can only represent discrete, finite sets of values.

They are not suitable for representing continuous or infinite ranges of values. For

example, if you need to represent a range of floating-point numbers, enums are

not the appropriate choice.

3. Difficulty in Serialization: Enums can present challenges when serializing or

deserializing data. If an enum value is serialized and later modified (e.g., adding

or rearranging enum values), deserialization can result in unexpected behavior or

errors.

4. Increased Coupling: Using enums can introduce tight coupling between different

parts of the code. When an enum is used across multiple classes or modules,

any changes made to the enum may require updating all the dependent code.

This can lead to maintenance challenges and potential issues if not managed

carefully.

5. Reduced Flexibility: Enums restrict the possible values to a predefined set,

limiting the flexibility of the code. If there is a need to handle values outside the

defined enum set, alternative solutions or more flexible data structures may be

necessary.

6. Inability to Customize Behavior: Enums typically cannot have associated


behaviors or methods. While some languages provide limited capabilities for
adding methods to enums, they lack the flexibility of full-fledged classes or

objects.

7. Limited Enum Composition: Enum values cannot be composed or combined

easily. For example, if you need to represent a set of permissions or flags that

can be combined or manipulated, enums may not provide the required

functionality.

8. Increased Memory Usage: Each enum value consumes memory, which can add

up if the enum has a large number of values or is used extensively throughout

the codebase. In some cases, this can impact memory usage and performance.

9. Reduced Debugging Capabilities: Debugging code that uses enums can be more

challenging compared to debugging plain values or variables. Enum values can

be harder to inspect and may not provide as much contextual information during

debugging sessions.

10. Language-Specific Limitations: The limitations of enums can vary depending on

the programming language being used. Some languages may impose additional

constraints or lack certain features that could be essential for specific use cases.
Operators in C++
An operator is a symbol that operates on a value to perform specific mathematical
or logical computations. They form the foundation of any programming language. In
C++, we have built-in operators to provide the required functionality.
An operator operates the operands. For example,
int c = a + b;
Here, ‘+’ is the addition operator. ‘a’ and ‘b’ are the operands that are being ‘added’.
Operators in C++ can be classified into 6 types:

1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Ternary or Conditional Operators

1) Arithmetic Operators

These operators are used to perform arithmetic or mathematical operations on the


operands. For example, ‘+’ is used for addition, ‘-‘ is used for subtraction ‘*’ is used
for multiplication, etc.
Arithmetic Operators can be classified into 2 Types:
A) Unary Operators: These operators operate or work with a single operand. For
example: Increment(++) and Decrement(–) Operators.
Name Symbol Description Example

int a = 5;
Increment Increases the integer value of the
++ a++; //
Operator variable by one
returns 6

int a = 5;
Decrement Decreases the integer value of the
— a–; // returns
Operator variable by one
4

Example:
the description
Output
a++ is 10
++a is 12
b-- is 15
--b is 13

Note: ++a and a++, both are increment operators, however, both are slightly
different.
In ++a, the value of the variable is incremented first and then It is used in the
program. In a++, the value of the variable is assigned first and then It is incremented.
Similarly happens for the decrement operator.
B) Binary Operators: These operators operate or work with two operands. For
example: Addition(+), Subtraction(-), etc.
Name Symbol Description Example

int a = 3, b = 6;
Addition + Adds two operands int c = a+b; // c
=9

int a = 9, b = 6;
Subtracts second operand from
Subtraction – int c = a-b; // c
the first
=3

int a = 3, b = 6;
Multiplication * Multiplies two operands int c = a*b; // c
= 18

int a = 12, b =
Divides first operand by the 6;
Division /
second operand int c = a/b; // c
=2

int a = 8, b = 6;
Modulo Returns the remainder an integer
% int c = a%b; // c
Operation division
=2

2) Relational Operators

These operators are used for the comparison of the values of two operands. For
example, ‘>’ checks if one operand is greater than the other operand or not, etc. The
result returns a Boolean value, i.e., true or false.
Name Symbol Description Example

int a = 3, b
= 6;
Is Equal To == Checks if both operands are equal a==b;
// returns
false

int a = 3, b
= 6;
Checks if first operand is greater than
Greater Than > a>b;
the second operand
// returns
false

int a = 3, b
= 6;
Greater Than Checks if first operand is greater than
>= a>=b;
or Equal To or equal to the second operand
// returns
false

int a = 3, b
= 6;
Checks if first operand is lesser than
Less Than < a<b;
the second operand
// returns
true

int a = 3, b
= 6;
Less Than or Checks if first operand is lesser than
<= a<=b;
Equal To or equal to the second operand
// returns
true

int a = 3, b
Checks if both operands are not = 6;
Not Equal To !=
equal
a!=b;
Name Symbol Description Example

// returns
true

3) Logical Operators

These operators are used to combine two or more conditions or constraints or to


complement the evaluation of the original condition in consideration. The result
returns a Boolean value, i.e., true or false.
Name Symbol Description Example

int a = 3, b =
6;
Logical Returns true only if all the operands are
&& a&&b;
AND true or non-zero
// returns
true

int a = 3, b =
6;
Logical Returns true if either of the operands is
|| a||b;
OR true or non-zero
// returns
true

int a = 3;
Logical Returns true if the operand is false or !a;
!
NOT zero
// returns
false

4) Bitwise Operators
These operators are used to perform bit-level operations on the operands. The
operators are first converted to bit-level and then the calculation is performed on the
operands. Mathematical operations such as addition, subtraction, multiplication, etc.
can be performed at the bit level for faster processing.
Name Symbol Description Example

int a = 2, b =
Copies a bit to the evaluated result if 3;
Binary AND &
it exists in both operands (a & b);
//returns 2

int a = 2, b =
Copies a bit to the evaluated result if 3;
Binary OR |
it exists in any of the operand (a | b);
//returns 3

int a = 2, b =
Copies the bit to the evaluated result 3;
Binary XOR ^ if it is present in either of the
operands but not both (a ^ b);
//returns 1

int a = 2, b =
Shifts the value to left by the number 3;
Left Shift <<
of bits specified by the right operand. (a << 1);
//returns 4

int a = 2, b =
Shifts the value to right by the 3;
Right Shift >> number of bits specified by the right
operand. (a >> 1);
//returns 1

int b = 3;
One’s Changes binary digits 1 to 0 and 0 to
~ (~b);
Complement 1
//returns -4

5) Assignment Operators

These operators are used to assign value to a variable. The left side operand of the
assignment operator is a variable and the right side operand of the assignment
operator is a value. The value on the right side must be of the same data type as the
variable on the left side otherwise the compiler will raise an error.
Namemultiply Symbol Description Example

Assignment Assigns the value on the right to the int a = 2;


=
Operator variable on the left // a = 2

First adds the current value of the int a = 2,


Add and b = 4;
variable on left to the value on the
Assignment +=
right and then assigns the result to a+=b; // a
Operator
the variable on the left =6

First subtracts the value on the right int a = 2,


Subtract and b = 4;
- from the current value of the variable
Assignment
= on left and then assign the result to a-=b; // a
Operator
the variable on the left = -2

First multiplies the current value of int a = 2,


Multiply and b = 4;
the variable on left to the value on
Assignment *=
the right and then assign the result a*=b; // a
Operator
to the variable on the left =8

First divides the current value of the int a = 4,


Divide and b = 2;
variable on left by the value on the
Assignment /=
right and then assign the result to a /=b; // a
Operator
the variable on the left =2

6) Ternary or Conditional Operators(?:)

This operator returns the value based on the condition.


Expression1? Expression2: Expression3
The ternary operator ? determines the answer on the basis of the evaluation
of Expression1. If it is true, then Expression2 gets evaluated and is used as the
answer for the expression. If Expression1 is false, then Expression3 gets
evaluated and is used as the answer for the expression.
This operator takes three operands, therefore it is known as a Ternary Operator.

A) sizeof Operator: This unary operator is used to compute the size of its operand
or variable.
sizeof(char); // returns 1
B) Comma Operator(,): This binary operator (represented by the token) is used to
evaluate its first operand and discards the result, it then evaluates the second
operand and returns this value (and type). It is used to combine various expressions
together.
int a = 6;
int b = (a+1, a-2, a+5); // b = 11
C) -> Operator: This operator is used to access the variables of classes or
structures.
cout<<emp->first_name;
D) Cast Operator: This unary operator is used to convert one data type into another.
float a = 11.567;
int c = (int) a; // returns 11
E) Dot Operator(.): This operator is used to access members of structure variables
or class objects in C++.
cout<<emp.first_name;
F) & Operator: This is a pointer operator and is used to represent the memory
address of an operand.
G) * Operator: This is an Indirection Operator
H) << Operator: It is called the insertion operator. It is used with cout to print the
output.
I) >> Operator: It is called the extraction operator. It is used with cin to get the input.
Typecasting in C++
A type cast is basically a conversion from one type to another. There are two types
of type conversion:
1. Implicit Type Conversion Also known as ‘automatic type conversion’.
• Done by the compiler on its own, without any external trigger from the user.
• Generally takes place when in an expression more than one data type is
present. In such condition type conversion (type promotion) takes place to
avoid lose of data.
• All the data types of the variables are upgraded to the data type of the
variable with largest data type.
• It is possible for implicit conversions to lose information, signs can be lost
(when signed is implicitly converted to unsigned), and overflow can occur
(when long long is implicitly converted to float).

2.Explicit Type Conversion: This process is also called type casting and it is user-
defined. Here the user can typecast the result to make it of a particular data type.
Advantages of Type Conversion:
• This is done to take advantage of certain features of type hierarchies or type
representations.
• It helps to compute expressions containing variables of different data types.
Control Structures
Control Structures are just a way to specify flow of control in programs. Any
algorithm or program can be more clear and understood if they use self-contained
modules called as logic or control structures. It basically analyzes and chooses in
which direction a program flows based on certain parameters or conditions. There
are three basic types of logic, or flow of control, known as:
1. Sequence logic, or sequential flow
2. Selection logic, or conditional flow
3. Iteration logic, or repetitive flow

Sequential Logic (Sequential Flow)(switch case)


Sequential logic as the name suggests follows a serial or sequential flow in which
the flow depends on the series of instructions given to the computer. Unless new
instructions are given, the modules are executed in the obvious sequence. The
sequences may be given, by means of numbered steps explicitly. Also, implicitly
follows the order in which modules are written. Most of the processing, even some
complex problems, will generally follow this elementary flow pattern.
Selection Logic (Conditional Flow)(if else)
Selection Logic simply involves a number of conditions or parameters which
decides one out of several written modules. The structures which use these type of
logic are known as Conditional Structures.

Iteration Logic (Repetitive Flow)(loop)


The Iteration logic employs a loop which involves a repeat statement followed by a
module known as the body of a loop.
Functions in C++

function is a set of statements that takes input, does some specific


computation, and produces output. The idea is to put some commonly or
repeatedly done tasks together to make a function so that instead of writing the
same code again and again for different inputs, we can call this function.
In simple terms, a function is a block of code that runs only when it is called.

Why Do We Need Functions?


• Functions help us in reducing code redundancy. If functionality is performed at
multiple places in software, then rather than writing the same code, again and
again, we create a function and call it everywhere. This also helps in maintenance
as we have to make changes in only one place if we make changes to the
functionality in future.
• Functions make code modular. Consider a big file having many lines of code. It
becomes really simple to read and use the code, if the code is divided into
functions.
• Functions provide abstraction. For example, we can use library functions without
worrying about their internal work.

Types of Functions

User Defined Function

User-defined functions are user/customer-defined blocks of code specially


customized to reduce the complexity of big programs. They are also commonly
known as “tailor-made functions” which are built only to satisfy the condition in
which the user is facing issues meanwhile reducing the complexity of the whole
program.

Library Function

Library functions are also called “built-in Functions“. These functions are part of a
compiler package that is already defined and consists of a special function with
special and different meanings. Built-in Function gives us an edge as we can directly
use them without defining them whereas in the user-defined function we have to
declare and define a function before using them.
Call By Value
A function is a collection of statements that accept inputs, carry out certain
calculations, and output the results. The concept is to group similar or often
performed actions into a function so that we may call the function rather than
writing the same code again for various inputs. A function is a section of code that
executes only when it is called, to put it simply.

Use of Call by Value


• When you do not want to change the actual parameters of the function.
• When you want to make copies of the data instead of the actual data.
• When space is not an issue.
• Usually, when you do not deal with recursion or backtracking.

Limitations of using Call by Value


• Data passed is then stored in temporary memory
• Can’t operate over the actual data rather need to work on temporary copy made
of the data, because of which changes made in the data in the function is not
reflected in main function.
• Memory Space required while using string ,array , vector, etc can be huge.
• Tackling Backtracking and recursion can be complex using call by values.

Call by Reference

In this method, instead of passing the values of the actual parameters to the formal
ones, the addresses of the actual parameters are passed. Therefore, the
modification by the called function to the formal parameters affects the actual
parameters as well.
When a programmer opts for the call by reference, the memory space for the formal
parameters and the actual parameters are the same. All the operations in the function
are performed on the value stored at the address of the actual parameters, and the
modified value gets stored at the same address.
This technique not only conserves memory but also simplifies collaboration, as
complex data types like arrays or structures can easily be manipulated without being
duplicated needlessly.

Use of Call by Reference


1.Since arguments are not copied into the new variables, it provides greater time and
space efficiency.
2. The function can change the value of the argument and the change is reflected in
the calling function.
3. A function can return only one value. In case we need to return multiple values,
we can pass those arguments by reference, so that the modified values are visible in
the calling function.
Difference between Call by Value and Call by Reference in C++

Aspect Call by Value Call by Reference


Passes a reference or
What is passed Copies the actual value of the argument. memory address of the
argument.
Changes made to the
Changes made to the parameter inside
Modification of parameter inside the
the function do not affect the original
argument function directly affect the
argument.
original argument.
May consume more
Typically consumes less memory as it memory as it uses
Memory Usage
creates a separate copy of the argument. references to the original
data.
May be slower due to the
Generally faster due to the smaller data
Performance need to access data
transfer.
through references.
Suitable for complex data
Data Type Suitable for simple data types (int, float,
types (arrays, objects,
Constraints etc.).
etc.).
Risk of
Reduces the risk of unintentional side Increases the risk of
unintended
effects. unintentional side effects.
changes

Return by reference

In C++, a reference is a way to refer to an object indirectly. A reference is like an


alias, or a nickname, for an existing object. To return a reference, the function
definition must include an ampersand (&) after the type of the returned value.

Returning a reference can be useful when you want to avoid making a copy of a
large object, or when you want to modify an object that was passed to a function by
reference. It also allows you to chain function calls, since the return value of the
function can be used as the input to another function.
Inline Functions
C++ provides inline functions to reduce the function call overhead. An inline function
is a function that is expanded in line when it is called. When the inline function is
called whole code of the inline function gets inserted or substituted at the point of the
inline function call. This substitution is performed by the C++ compiler at compile
time. An inline function may increase efficiency if it is small.
Syntax:
inline return-type function-name(parameters)
{
// function code
}

Why Inline Functions are Used

When the program executes the function call instruction the CPU stores the
memory address of the instruction following the function call, copies the arguments
of the function on the stack, and finally transfers control to the specified function.
The CPU then executes the function code, stores the function return value in a
predefined memory location/register, and returns control to the calling function.
This can become overhead if the execution time of the function is less than the
switching time from the caller function to called function (callee).
For functions that are large and/or perform complex tasks, the overhead of the
function call is usually insignificant compared to the amount of time the function
takes to run. However, for small, commonly-used functions, the time needed to
make the function call is often a lot more than the time needed to actually execute
the function’s code. This overhead occurs for small functions because the
execution time of a small function is less than the switching time.
Inline functions Advantages:
1. Function call overhead doesn’t occur.
2. It also saves the overhead of push/pop variables on the stack when a function is
called.
3. It also saves the overhead of a return call from a function.
4. When you inline a function, you may enable the compiler to perform context-
specific optimization on the body of the function. Such optimizations are not
possible for normal function calls. Other optimizations can be obtained by
considering the flows of the calling context and the called context.
5. An inline function may be useful (if it is small) for embedded systems because
inline can yield less code than the function called preamble and return.

Inline function Disadvantages:


1. The added variables from the inlined function consume additional registers,
After the in-lining function if the variable number which is going to use the
register increases then they may create overhead on register variable resource
utilization. This means that when the inline function body is substituted at the
point of the function call, the total number of variables used by the function also
gets inserted. So the number of registers going to be used for the variables will
also get increased. So if after function inlining variable numbers increase
drastically then it would surely cause overhead on register utilization.
2. If you use too many inline functions then the size of the binary executable file
will be large, because of the duplication of the same code.
3. Too much in lining can also reduce your instruction cache hit rate, thus reducing
the speed of instruction fetch from that of cache memory to that of primary
memory.
4. The inline function may increase compile time overhead if someone changes
the code inside the inline function then all the calling location has to be
recompiled because the compiler would be required to replace all the code once
again to reflect the changes, otherwise it will continue with old functionality.
5. Inline functions may not be useful for many embedded systems. Because in
embedded systems code size is more important than speed.
6. Inline functions might cause thrashing because inlining might increase the size
of the binary executable file. Thrashing in memory causes the performance of
the computer to degrade. The following program demonstrates the use of the
inline function.
Macro Function
A macro is a piece of code in a program that is replaced by the value of the
macro. Macro is defined by #define directive. Whenever a macro name is
encountered by the compiler, it replaces the name with the definition of the
macro. Macro definitions need not be terminated by a semi-colon(;).
Below are the programs to illustrate the use of macros in C++

Advantages of Macros
1. Increased productivity: Macros can save time and reduce errors by
automating repetitive tasks.
2. Customization: Macros can be customized to fit specific needs, allowing for
greater flexibility in how tasks are completed.
3. Consistency: Macros can help ensure consistency in tasks by following a set
of predetermined instructions.
4. Efficiency: Macros can perform tasks more quickly than humans, improving
overall efficiency.
5. Ease of use: Macros are easy to create and use, requiring little to no
programming knowledge

Disadvantages of Macros
1. Security risks: Macros can be a security risk if they are not properly secured or
if they are used to execute malicious code.
2. Limited functionality: Macros may not be able to perform more complex tasks,
limiting their usefulness.
3. Compatibility issues: Macros may not be compatible with all software
applications, limiting their usefulness.
4. Maintenance: Macros may require maintenance and updates, which can be
time-consuming and costly.
5. Dependence: Over-reliance on macros can result in decreased problem-solving
skills and critical thinking.

Difference between Inline and Macro in C++

S.NO Inline Macro

Whereas the macros are


An inline function is defined
1. defined by
by the inline keyword.
the #define keyword.

Through inline function, the


Whereas macro can’t access
2. class’s data members can
the class’s data members.
be accessed.
S.NO Inline Macro

In the case of inline Whereas in the case of macros,


3. function, the program can the program can’t be easily
be easily debugged. debugged.

Whereas in the case of macro,


In the case of inline, the
the arguments are evaluated
4. arguments are evaluated
every time whenever macro is
only once.
used in the program.

In C++, inline may be Whereas the macro is all the


5. defined either inside the time defined at the beginning of
class or outside the class. the program.

In C++, inside the class, the


short length functions are While the macro is specifically
6.
automatically made the defined.
inline functions.

Inline is not as widely used


7. While the macro is widely used.
as macros.

While the macro is very much


Inline is not used in
8. used in competitive
competitive programming.
programming.

Inline function is terminated While the macro is not


9. by the curly brace at the terminated by any symbol, it is
end. terminated by a new line.
Function Overloading
Function overloading is a feature of object-oriented programming where two or
more functions can have the same name but different parameters. When a function
name is overloaded with different jobs it is called Function Overloading. In Function
Overloading “Function” name should be the same and the arguments should be
different. Function overloading can be considered as an example of
a polymorphism feature in C++.

Advantages of function overloading are as follows:


• The main advantage of function overloading is that it improves code readability
and allows code reusability.
• The use of function overloading is to save memory space, consistency, and
readability.
• It speeds up the execution of the program
• Code maintenance also becomes easy.
• Function overloading brings flexibility to code.
• The function can perform different operations and hence it eliminates the use of
different function names for the same kind of operations.

Disadvantage of function overloading are as follows:


• Function declarations that differ only in the return type cannot be overloaded
• Member function declarations with the same name and the same parameter
types cannot be overloaded if any of them is a static member function
declaration.
• The main disadvantage is that it requires the compiler to perform name
mangling on the function name to include information about the argument types.
Default Arguments
A default argument is a value provided in a function declaration that is
automatically assigned by the compiler if the calling function doesn’t provide a
value for the argument. In case any value is passed, the default value is
overridden.
Advantages of Default Arguments:
• Default arguments are useful when we want to increase the capabilities of an
existing function as we can do it just by adding another default argument to the
function.
• It helps in reducing the size of a program.
• It provides a simple and effective programming approach.
• Default arguments improve the consistency of a program.

Disadvantages of Default Arguments:


• It increases the execution time as the compiler needs to replace the omitted
arguments by their default values in the function call.

Key Points:
• Default arguments are different from constant arguments as constant
arguments can’t be changed whereas default arguments can be overwritten if
required.
• Default arguments are overwritten when the calling function provides values for
them. For example, calling the function sum(10, 15, 25, 30) overwrites the
values of z and w to 25 and 30 respectively.
Friend function

If a function is defined as a friend function in C++, then the protected and private data
of a class can be accessed using the function.

By using the keyword friend compiler knows the given function is a friend function.

For accessing the data, the declaration of a friend function should be done inside the
body of a class starting with the keyword friend.

Declaration of friend function in C++


1. class class_name
2. {
3. friend data_type function_name(class_name); // syntax of friend function.
4. };

Features of Friend Functions

• A friend function is a special function in C++ that in spite of not being a member
function of a class has the privilege to access the private and protected
data of a class.
• A friend function is a non-member function or ordinary function of a class, which
is declared as a friend using the keyword “friend” inside the class. By declaring
a function as a friend, all the access permissions are given to the function.
• The keyword “friend” is placed only in the function declaration of the friend
function and not in the function definition or call.
• A friend function is called like an ordinary function. It cannot be called using the
object name and dot operator. However, it may accept the object as an
argument whose value it wants to access.
• A friend function can be declared in any section of the class i.e. public or private
or protected.

Advantages of Friend Functions


• A friend function is able to access members without the need of inheriting
the class.
• The friend function acts as a bridge between two classes by accessing
their private data.
• It can be used to increase the versatility of overloaded operators.
• It can be declared either in the public or private or protected part of the
class.

Disadvantages of Friend Functions


• Friend functions have access to private members of a class from outside
the class which violates the law of data hiding.
• Friend functions cannot do any run-time polymorphism in their members.

You might also like