Unit-4 OOSD Note
Unit-4 OOSD Note
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.
• 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
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,
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.
•
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;
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.
Constant Variables
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.
We can only assign a value to the constant We can assign value to the
while defining it. variable anytime.
Advantages of Enums:
can communicate the intention and meaning of the values more effectively. This
makes the code easier to understand and maintain, especially when multiple
Example 1:
SATURDAY, SUNDAY; }
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:
myColor = Color.YELLOW;
3. Code Consistency: Enums promote code consistency by ensuring that the same
definition of a fixed set of values, enums help prevent typos or variations in different
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
While enums have several advantages, it’s essential to consider their potential
disadvantages as well.
Disadvantages of Enums:
limitation can be problematic when dealing with situations that require flexibility or
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
deserializing data. If an enum value is serialized and later modified (e.g., adding
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.
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.
objects.
easily. For example, if you need to represent a set of permissions or flags that
functionality.
8. Increased Memory Usage: Each enum value consumes memory, which can add
the codebase. In some cases, this can impact memory usage and performance.
9. Reduced Debugging Capabilities: Debugging code that uses enums can be more
be harder to inspect and may not provide as much contextual information during
debugging sessions.
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
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
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
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
Types of Functions
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.
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.
Return by reference
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
}
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.
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.
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.
• 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.