C++ Remaining Topics
When we run a program, two major players work behind the scenes to make it happen: two
components; namely, the Linker and the Loader. This may best be described as a double act
of computing. The most important work is done by the linker; this is the output of all the
different locations with code and produces an executable file. There is then the loader function
which is the one that loads this file into memory, ready to run.
In C++, the linker and loader are two crucial components in the process of converting your
source code into an executable program. Here's a breakdown of their definition.
Linker
o A linker is a special program that combines the object files, generated by the
compiler/assembler and other pieces of code to originate an executable file that has a .exe
extension. In the object file, the linker searches and appends all libraries needed for the
execution of the file. It regulates the memory space that will hold the code from each
module. It also merges two or more separate object programs and establishes links among
them.
o Input: Object files (.o or .obj extension) produced by the compiler.
o Output: An executable file or a library file (.exe, .dll in Windows, .so in Linux).
o Function of Linker
Symbol Resolution: The linker resolves symbols in the program that are defined in
one module and referenced in another.
Code Optimization: The linker optimizes the code generated by the compiler to
reduce code size and improve program performance.
Memory Management: The linker assigns memory addresses to the code and data
sections of the program and resolves any conflicts that arise.
Library Management: The linker can link external libraries into the executable file
to provide additional functionality.
Loader
o It is special program that takes input of executable files from linker, loads it to main
memory, and prepares this code for execution by computer. Loader allocates memory
space to program. Even it settles down symbolic reference between objects. It is in charge
of loading programs and libraries in operating system. The embedded computer systems
don’t have loaders. In them, code is executed through ROM.
o Function of Loader
Loading: The loader loads the executable file into memory and allocates memory for
the program.
Relocation: The loader adjusts the program’s memory addresses to reflect its location
in memory.
Symbol Resolution: The loader resolves any unresolved external symbols that are
required by the program.
Dynamic Linking: The loader can dynamically link libraries into the program at
runtime to provide additional functionality.
Differences Between Linker and Loader
Linker Loader
The main function of Linker is to generate Whereas main objective of Loader is to
executable files. load executable files to main memory.
The linker takes input of object code And the loader takes input of executable
generated by compiler/assembler. files generated by linker.
Linking can be defined as process of Loading can be defined as process of
combining various pieces of codes and source loading executable codes to main memory
code to obtain executable code. for further execution.
Loaders are of 4 types: Absolute,
Linkers are of 2 types: Linkage Editor
Relocating, Direct Linking, Bootstrap
and Dynamic Linker.
Loader.
Another use of linker is to combine all object It helps in allocating the address to
modules. executable codes/files.
Loader is also responsible for adjusting
Linker is also responsible for arranging
references which are used within the
objects in program’s address space.
program.
Algorithm
o In mathematics, computer science, and related subjects, an algorithm is a finite sequence
of steps expressed for solving a problem. An algorithm can be defined as “a process that
performs some sequence of operations in order to solve a given problem”. Algorithms are
used for calculation, data processing, and many other fields.
o In computing, algorithms are essential because they serve as the systematic procedures
that computers require.
o A good algorithm is like using the right tool in the workshop. It does the job with the right
amount of effort.
o Let us follow an example to help us understand the concept of algorithm in a better way.
Let’s say that you have a friend arriving at the railway station, and your friend needs to
get from the railway station to your house. Here are three different ways (algorithms) that
you might give your friend for getting to your home.
The taxi/auto-rickshaw algorithm:
Go to the taxi/auto-rickshaw stand.
Get in a taxi/auto-rickshaw.
Give the driver my address.
The call-me algorithm:
When your train arrives, call my mobile phone.
Meet me outside the railway station.
The bus algorithm:
Outside the railway station, catch bus number 321.
Transfer to bus 308 near Kurla station.
Get off near Kalina University.
Walk two blocks west to my house.
o All these three algorithms accomplish the same goal, but each algorithm does it in a
different way. Each algorithm also has a different cost and a different travel time. Taking
a taxi/auto-rickshaw, for example, is the fastest way, but also the most expensive. Taking
the bus is definitely less expensive, but a whole lot slower. You choose the algorithm
based on the circumstances.
o In computer programming, there are often many different algorithms to accomplish any
given task. Each algorithm has advantages and disadvantages in different situations.
Sorting is one place where a lot of research has been done, because computers spend a lot
of time sorting lists.
o Now, let's see an example of an algorithm.
Example: Write an algorithm to print the numbers from 1 to 20.
Algorithm:
Step 1: Initialize a variable 'x' as 0.
Step 2: Increment 'x' by 1
Step 3: Print the variable 'x'.
Step 4: If 'x' is less than 20, then go back to step 2. Otherwise, go to the next step.
Step 5: Exit.
Flowchart
o A Flowchart is a type of diagram (graphical or symbolic) that represents an algorithm or
process. Each step in the process is represented by a different symbol and contains a short
description of the process step.
o The flow chart symbols are linked together with arrows showing the process flow
direction.
o A flowchart typically shows the flow of data in a process, detailing the operations/steps
in a pictorial format which is easier to understand than reading it in a textual format.
o A flowchart describes what operations (and in what sequence) are required to solve a
given problem. A flowchart can be likened to the blueprint of a building.
o As we know a designer draws a blueprint before starting construction on a building.
Similarly, a programmer prefers to draw a flowchart prior to writing a computer program.
o Flowcharts are used in analyzing, designing, documenting or managing a process or
program in various fields.
o Flowchart Symbols & Guidelines:
Flowcharts are usually drawn using some standard symbols; however, some special
symbols can also be developed when required. Some standard symbols, which are
frequently required for flowcharting many computer programs are shown.
Terminal/Terminator
The oval symbol indicates Start, Stop and Halt in a program’s logic flow. A pause/halt
is generally used in a program logic under some error conditions. Terminal is the first
and last symbols in the flowchart.
Input/Output
A parallelogram denotes any function of input/output type. Program instructions that
take input from input devices and display output on output devices are indicated with
parallelogram in a flowchart.
Action/Process
A box represents arithmetic instructions, specific action or operation that occurs as a
part of the process. All arithmetic processes such as adding, subtracting,
multiplication and division are indicated by action/process symbol.
Decision
Diamond symbol represents a decision point. Decision based operations such as
yes/no question or true/false are indicated by diamond in flowchart.
On-Page Connector/Reference
Whenever flowchart becomes complex or it spreads over more than one page, it is
useful to use connectors to avoid any confusions. connectors are used to indicate a
jump from one part of the flowchart to another without drawing long or complicated
lines. On-Page Connector is represented by a small circle.
Off-Page Connector/Reference
Whenever flowchart becomes complex or it spreads over more than one page, it is
useful to use connectors to avoid any confusions. connectors are used to indicate a
jump from one part of the flowchart to another without drawing long or complicated
lines. Off-Page Connector is represented by a pentagon.
Flow lines
Flow lines indicate the exact sequence in which instructions are executed. Arrows
represent the direction of flow of control and relationship among different symbols of
flowchart.
Rules For Creating a Flowchart
A flowchart is a graphical representation of an algorithm. It should follow some rules while
creating a flowchart
Rule 1: Flowchart opening statement must be ‘start’ keyword.
Rule 2: Flowchart ending statement must be ‘end’ keyword.
Rule 3: All symbols in the flowchart must be connected with an arrow line.
Rule 4: Each decision point should have two or more distinct outcomes.
Rule 5: Flow should generally move from top to bottom or left to right.
Example of a Flowchart
Draw a flowchart to input two numbers from the user and display the largest of two numbers.
Below is the explanation of the above flowchart:
Start: The process begins with the Start symbol, indicating the start of the
program.
Input num1: The first number, represented as num1, is entered.
Input num2: The second number, represented as num2, is entered.
Decision (num1 > num2): A decision point checks if num1 is greater than num2.
o If True, the process moves to the next step where num1 will be displayed.
o If False, the process moves to display num2.
Stop: The process ends with the Stop symbol, signaling the conclusion of the
program.
Escape Characters
o Escape characters are special characters that are difficult or impossible to express
otherwise in the source code of a program, like newline (\n) or tab (\t). All of them
are preceded by a backslash (\). Here you have a list of some of such escape codes:
o Despite their appearances, these are single characters.
o For example: '\n' '\t' "Left \t Right" "one \n two \n three" Additionally, you can
express any character by its numerical ASCII code by writing a backslash (\)
followed by the ASCII code expressed as an octal (base-8) or hexadecimal (base –
16) number.
Types of Errors
o In any programming language errors is common. If we miss any syntax like
parenthesis or semicolon then we get syntax errors. Apart from this we also get run
time errors during the execution of code. In a similar way the errors are classified
as below:
o Syntax Errors
These are also referred to as compile-time errors. These errors have occurred when
the rule of C++ writing techniques or syntax has been broken. These types of errors
are typically flagged by the compiler prior to compilation.
Example: In the below program we are getting an error because of a missing
semicolon at the end of the output statement (cout) called syntax error.
// C++ program to demonstrate a syntax error
#include <iostream>
using namespace std;
int main()
{
cout << "Geeks for geeks!" // missing semicolon
return 0;
}
o Runtime Errors
This type of error occurs while the program is running. Because this is not a
compilation error, the compilation will be completed successfully.
These errors occur due to segmentation fault when a number is divided by division
operator or modulo division operator.
Example: Let us consider an array of length 5 i.e. array[5], but during runtime, if we
try to access 10 elements i.e array[10] then we get segmentation fault errors called
runtime errors. Giving only an array length of 5.
// C++ program to demonstrate a runtime error
#include <iostream>
using namespace std;
int main()
{
int array[5];
return 0;
}
But in output trying to access more than 5 i.e. if we try to access array[10]
during runtime then we get an error.
o Logical Errors
Even if the syntax and other factors are correct, we may not get the desired results
due to logical issues. These are referred to as logical errors. We sometimes put a
semicolon after a loop, which is syntactically correct but results in one blank loop.
In that case, it will display the desired output.
Example: In the below example, the for loop iterates 5 times but the output will be
displayed only one time due to the semicolon at the end of for loop. These kinds of
errors are called logical errors.
// C++ program to demonstrate a logical error
#include <iostream>
using namespace std;
int main()
{
int j;
// Cause of Logical error
for(j=0;j<=5;j++);
{
cout << "Geeks for geeks";
}
return 0;
}
o Linked Errors
When the program is successfully compiled and attempting to link the different
object files with the main object file, errors will occur. When this error occurs, the
executable is not generated. This could be due to incorrect function prototyping, an
incorrect header file, or other factors. If main() is written as Main(), a linked error
will be generated.
Example:
// C++ program to demonstrate a linker error
#include <iostream>
using namespace std;
int Main()
{
cout << "Geeks for geeks";
return 0;
}
o Semantic Errors
This error occurs when the statements written in the program are not meaningful to
the compiler.
Example:
// C++ program to illustrate semantic error
int main()
{
int a, b, c;
a + b = c; //semantic error
}
No one shares secrets with strangers for privacy reasons. But everyone has that one friend
with whom they share most of their secrets, if not all. Friend class in C++ refers to the same
concept. Public data members and functions are accessible by every class in C++ and many
other programming languages. But the C++ friend class is special and can access even the
private data members and functions of other classes.
Friend Class
o A friend class can access private and protected members of other classes in which
it is declared as a friend. It is sometimes useful to allow a particular class to access
private and protected members of other classes. For example, a LinkedList class
may be allowed to access private members of Node.
o We can declare a friend class in C++ by using the friend keyword.
o Syntax:
friend class class_name; // declared in the base class
o Example:
// C++ Program to demonstrate the functioning of a friend class
#include <iostream>
using namespace std;
class GFG
{
private:
int private_variable;
protected:
int protected_variable;
public:
GFG()
{
private_variable = 10;
protected_variable = 99;
}
// friend class declaration
friend class F;
};
// Here, class F is declared as a friend inside class GFG. Therefore, F is a friend
of class GFG. Class F can access the private members of class GFG.
class F
{
public:
void display(GFG& t)
{
cout << "The value of Private Variable = "<< t.private_variable << endl;
cout << "The value of Protected Variable = "<< t.protected_variable;
}
};
// Driver code
int main()
{
GFG g;
F fri;
fri.display(g);
return 0;
}
Output
The value of Private Variable = 10
The value of Protected Variable = 99
Friend Function
o Like a friend class, a friend function can be granted special access to private and protected
members of a class in C++. They are not the member functions of the class but can access
and manipulate the private and protected members of that class for they are declared as
friends.
o A friend function can be: A member function of another class
o Syntax:
friend return_type function_name (arguments);
// for a global function
or
friend return_type class_name::function_name (arguments);
//for a member function of another class
o Member Function of Another Class as Friend Function
We can also declare a member function of another class as a friend function in C++. The
following example demonstrates how to use a member function of another class as a
friend function in C++:
// C++ program to create a member function of another class as a friend function
#include <iostream>
using namespace std;
class base; // forward definition needed another class in which function is declared
class anotherClass
{
public:
void memberFunction(base& obj);
};
// base class for which friend is declared
class base
{
private:
int private_variable;
protected:
int protected_variable;
public:
base()
{
private_variable = 10;
protected_variable = 99;
}
// friend function declaration
friend void anotherClass::memberFunction(base&);
};
// friend function definition
void anotherClass::memberFunction(base& obj)
{
cout << "Private Variable: " << obj.private_variable << endl;
cout << "Protected Variable: " << obj.protected_variable;
}
int main()
{
base object1;
anotherClass object2;
object2.memberFunction(object1);
return 0;
}
Output
Private Variable: 10
Protected Variable: 99
o 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.
o 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.
o 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.
o Important Points About Friend Functions and Classes
Friends should be used only for limited purposes. Too many functions or external
classes are declared as friends of a class with protected or private data access lessens
the value of encapsulation of separate classes in object-oriented programming.
Friendship is not mutual. If class A is a friend of B, then B doesn’t become a friend
of A automatically.
Friendship is not inherited.
The concept of friends is not in Java.
Pure Virtual Functions and Abstract Classes in C++
o Sometimes implementation of all functions cannot be provided in a base class because we
don’t know the implementation. Such a class is called an abstract class.
o For example, let Shape be a base class. We cannot provide the implementation of function
draw() in Shape, but we know every derived class must have an implementation of draw().
o Similarly, an Animal class doesn’t have the implementation of move() (assuming that all
animals move), but all animals must know how to move. We cannot create objects of
abstract classes.
o A pure virtual function (or abstract function) in C++ is a virtual function for which we
can have an implementation, But we must override that function in the derived class,
otherwise, the derived class will also become an abstract class. A pure virtual function is
declared by assigning 0 in the declaration.
o Example of Pure Virtual Functions
// An abstract class
class Test
// Data members of class
public:
virtual void show() = 0; // Pure Virtual Function
/* Other members */
};
o Complete Example
A pure virtual function is implemented by classes that are derived from an Abstract class.
// C++ Program to illustrate the abstract class and virtual functions
#include <iostream>
using namespace std;
class Base
{
int x; // private member variable
public:
virtual void fun() = 0; // pure virtual function
// getter function to access x
int getX()
{
return x;
}
};
// This class inherits from Base and implements fun()
class Derived : public Base
{
// private member variable
int y;
public:
// implementation of the pure virtual function
void fun()
{
cout << "fun() called";
}
};
int main(void)
{
Derived d; // creating an object of Derived class
d.fun(); // calling the fun() function of Derived class
return 0;
}
Output
fun() called
o Some Interesting Facts
A class is abstract if it has at least one pure virtual function.
We can have pointers and references of abstract class type.
If we do not override the pure virtual function in the derived class, then the derived
class also becomes an abstract class.
An abstract class can have constructors.
An abstract class in C++ can also be defined using struct keyword.
o Reference Example of above facts:
https://www.geeksforgeeks.org/pure-virtual-functions-and-abstract-classes/