Programming Paradigms Explained
Programming Paradigms Explained
Paradigm can also be termed as method to solve some problem or do some task.
Programming paradigm is an approach to solve problem using some programming language or
also we can say it is a method to solve a problem using tools and techniques that are available
to us following some approach. There are lots for programming language that are known but
all of them need to follow some strategy when they are implemented and this
methodology/strategy is paradigms. Apart from varieties of programming language there are
lots of paradigms to fulfill each and every demand.
The prime purpose of C++ programming was to add object orientation to the C
programming language, which it itself one of the most powerful programming languages.
OBJECT:
Objects are the basic run-time entities in an object-oriented system. They may represent a
person, a place, a bank account, a table of data or any item that the program has to handle. They
may also represent user-defined data such as vectors, time and lists. An Object is an instance of
a Class. When a class is defined, no memory is allocated but when it is instantiated (i.e. an
object is created) memory is allocated.
CLASS:
For Example: Consider the Class of Cars. There may be many cars with different
names and brand but all of them will share some common properties like all of them will have
4 wheels, Speed Limit, Mileage range etc. So here, Car is the class and wheels, speed limits,
mileage are their properties.
Data abstraction is one of the most essential and important features of object-oriented
programming in C++. Abstraction means displaying only essential information and hiding the
details. Data abstraction refers to providing only essential information about the data to the
outside world, hiding the background details or implementation.
Encapsulation is defined as wrapping up of data and information under a single unit. In
Object-Oriented Programming, Encapsulation is defined as binding together the data and the
functions that manipulate them.
INHERITANCE:
Inheritance is the process by which objects of one class acquire the properties of object
of another class. It supports the concept of hierarchical classification.
Sub Class: The class that inherits properties from another class is called Sub class or
Derived Class.
Super Class: The class whose properties are inherited by sub class is called Base Class or
Super class.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create
a new class and there is already a class that includes some of the code that we want, we can
derive our new class from the existing class. By doing this, we are reusing the fields and
methods of the existing class.
The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form.
A person at the same time can have different characteristic. Like a man at the same time
is a father, a husband, an employee. The same person poses different behaviour in different
situations. This is called polymorphism.
FRIEND CLASS:
A friend class can access private and protected members of other class in which it is
declared as friend. It is sometimes useful to allow a particular class to access private members
of other class.
For example, a LinkedList class may be allowed to access private members of Node.
A friend class can access both private and protected members of the class in which it has been
declared as friend.
FRIEND FUNCTION:
Like friend class, a friend function can be given a special grant to access private and
protected members. A friend function can be:
class <class_name>
Following are some important points about friend functions and classes:
1) Friends should be used only for limited purpose. Too many functions or external classes are
declared as friends of a class with protected or private data, it lessens the value of
encapsulation of separate classes in object-oriented programming.
2) Friendship is not mutual. If class A is a friend of B, then B doesn’t become a friend of A
automatically.
3) Friendship is not inherited.
4) The concept of friends is not there in Java.
MERITS:
A friend function is able to access members without the need of inheriting the class.
Friend function acts as a bridge between two classes by accessing their private data.
It can be used to increase the versatility of overloaded operator.
It can be declared either in the public or private or protected part of class.
DEMERITS:
Friend functions have access to private members of a class from outside the class which
violates the law of the data hiding.
Friend functions cannot do any run time polymorphism in its members.
VIRTUAL FUNCTION:
A virtual function is a member function which is declared within a base class and is re-
defined (overridden) by a derived class. When you refer to a derived class object using a
pointer or a reference to the base class, you can call a virtual function for that object and
execute the derived class’s version of the function.
Virtual functions ensure that the correct function is called for an object, regardless of
the type of reference (or pointer) used for function call.
They are mainly used to achieve Runtime polymorphism
Functions are declared with a virtual keyword in base class.
The resolving of function call is done at runtime.
MESSAGE PASSING:
Objects communicate with one another be sending and receiving information much the
same way as people pass messages to one another.
We can build the programs from standard working modules that communicate with one
another, rather than having to start writing the code from scratch which leads to saving of
development time and higher productivity,
OOP language allows breaking the program into the bit-sized problems that can be solved
easily (one object at a time).
The new technology promises greater programmer productivity, better quality of software
and lesser maintenance cost.
OOP systems can be easily upgraded from small to large systems.
It is possible that multiple instances of objects co-exist without any interference,
It is very easy to partition the work in a project based on objects.
It is possible to map the objects in problem domain to those in the program.
The principle of data hiding helps the programmer to build secure programs which cannot
be invaded by the code in other parts of the program.
By using inheritance, we can eliminate redundant code and extend the use of existing
classes.
Message passing techniques is used for communication between objects which makes the
interface descriptions with external systems much simpler.
The data-centered design approach enables us to capture more details of model in an
implementable form.
Data encapsulation
Data hiding and access mechanisms
Automatic initialization and clear-up of objects
Operator overloading
Languages that supports these features include C++,smalltalk, Object Pascal and Java.
APPLICATIONS OF OOP:
Real-Time System design: Real-time system inherits complexities and makes it difficult to
build them. OOP techniques make it easier to handle those complexities.
Hypertext and Hypermedia: Hypertext is similar to regular text as it can be stored,
searched, and edited easily. Hypermedia on the other hand is a superset of hypertext. OOP
also helps in laying the framework for hypertext and hypermedia.
AI Expert System: These are computer application that is developed to solve complex
problems which are far beyond the human brain. OOP helps to develop such an AI expert
System
Office automation System: These include formal as well as informal electronic systems
that primarily concerned with information sharing and communication to and from people
inside and outside the organization. OOP also help in making office automation principle.
Neural networking and parallel programming: It addresses the problem of prediction
and approximation of complex-time varying systems. OOP simplifies the entire process by
simplifying the approximation and prediction ability of the network.
Stimulation and modeling system: It is difficult to model complex systems due to varying
specifications of variables. Stimulating complex systems require modeling and
understanding interaction explicitly. OOP provides an appropriate approach for simplifying
these complex models.
Object-oriented database: The databases try to maintain a direct correspondence between
the real world and database object in order to let the object retain it identity and integrity.
Client-server system: Object-oriented client-server system provides the IT infrastructure
creating object-oriented server internet (OCSI) applications.
CIM/CAD/CAM systems: OOP can also be used in manufacturing and designing
applications as it allows people to reduce the efforts involved. For instance, it can be used
while designing blueprints and flowcharts. So it makes it possible to produce these
flowcharts and blueprint accurately.
C++ AT A GLANCE:
NOTE − A programming language is said to use static typing when type checking is performed
during compile-time as opposed to run-time.
USE OF C++:
APPLICATIONS OF C++:
C++ is a versatile language for handling very large programs. It is suitable for virtually
any programming task including development of editors, compilers, databases, communication
systems and any complex real –life application systems.
Since C++ allows us to create hierarchy-related object, we can build special object-
oriented libraries which can be used later by many programmers.
While C++ is able to map the real-world problem property, the C part of C++ gives the
language the ability to get close to the machine-level details.
C++ programs are easily maintainable and expandable. When a new feature needs to be
implemented, it is very easy to add to the existing structure of an object.
It is expected that C++ will replace C as general-purpose language in the near future.
Some of the major applications that are used in C++ by major software vendors, sellers, and
giants are-
Google: C++ is used for lots of google magic like Big table, Google file system,
Google Chromium browser, and MapReduce large cluster data processing are all
written in C++.
Mozilla: Mozilla uses a subset of C++. C++ 14 is required to build Mozilla 59,
Mozilla Firefox, and Thunderbird email chat client are both written using C++.
Microsoft: Lots of windows apps that you regularly use are written in C++, It features
tools for developing and debugging C++ code, especially code written for the DirectX,
Windows API, and .NET.
Rockstar Games: Almost all major game companies use C++ due to its right speed on
bare metal. Many major game engines are fully written in C++ and leverage its speed
and OOPs capabilities.
MongoDB: MongoDB is an open-source database, widely used as the back-end store
for web applications, as well as in large enterprises like Viacom, biotechnology giants,
and Disney.
Games and Animations: C++ is used for developing games. It simplifies the
complexity of 3-Dimensional games and helps in optimizing the resources. C++
supports the multiplayer option with networking. It is preferable because it is very fast
in runtime and is mainly used in developing the suites of a game tool. It is widely used
in building real-time, image processing, visual effects, and mobile sensor applications,
modelling which is mainly coded in C++. This software is used for animation,
environments, motion graphics, and virtual reality. These virtual reality devices are the
most popular in today’s entertainment world.
Media Access: C++ is also used for creating a media player, managing video files and
audio files, etc. An example is the Winamp Media player, which is developed in C++,
which allows users to enjoy music, access and share the videos and music files, etc.
Compilers: It is known that C++language is compiled language this is the main reason
why most of the compilers are mainly written in C++ language only. The compilers
used for compiling other languages like C#, Java, etc. are mainly written in C++ only. It
is also used in developing these languages as well as C++ is platform-independent and
able to create a variety of software.
Scanning: The applications such as film scanners or camera scanners are also
developed in the C++ language. It has been used for developing PDF technology for
print documentation, exchanging documents, publishing the documents, and archiving
the document as well.
#include <iostream>
using namespace std;
// main() is where program execution begins.
int main() {
cout << "Hello World"; // prints Hello World
return 0;}
The C++ language defines several headers, which contain information that is either
necessary or useful to your program. For this program, the header <iostream> is needed.
The line using namespace std; tells the compiler to use the std namespace. Namespaces
are a relatively recent addition to C++.
The next line '// main() is where program execution begins.' is a single-line comment
available in C++. Single-line comments begin with // and stop at the end of the line.
The line int main() is the main function where program execution begins.
The next line cout << "Hello World"; causes the message "Hello World" to be displayed
on the screen.
The next line return 0; terminates main( )function and causes it to return the value 0 to
the calling process.
To save the file, compile and run the program. Please follow the steps given below −
Make sure that g++ is in your path and that you are running it in the directory containing
file [Link].
In C++, the semicolon is a statement terminator. That is, each individual statement must
be ended with a semicolon. It indicates the end of one logical entity.
x = y;
y = y + 1;
add(x, y);
A block is a set of logically connected statements that are surrounded by opening and
closing braces. For example −
{
cout << "Hello World"; // prints Hello World
return 0;
}
C++ does not recognize the end of the line as a terminator. For this reason, it does not
matter where you put a statement in a line. For example −
x = y;
y = y + 1;
add(x, y);
is the same as
x = y; y = y + 1; add(x, y);
UNIT 2
DATA TYPES:
C++ offers the programmer a rich assortment of built-in as well as user defined data
types. Following table lists down seven basic C++ data types −
Type Keyword
Boolean Bool
Character Char
Integer Int
Floating point Float
Double floating point Double
Valueless Void
Wide character wchar_t
Several of the basic types can be modified using one or more of these type modifiers −
signed
unsigned
short
long
The following table shows the variable type, how much memory it takes to store the value in
memory, and what is maximum and minimum value which can be stored in such type of
variables.
The size of variables might be different from those shown in the above table, depending
on the compiler and the computer you are using.
Endl;
Which inserts a new-line character after every line and << operator is being used to pass
multiple values out to the screen. We are also using sizeof() operator to get size of various data
types.
TYPEDEF DECLARATIONS
Create a new name for an existing type using typedef. Following is the simple syntax to
define a new type using typedef −
For example, the following tells the compiler that feet is another name for int −
Now, the following declaration is perfectly legal and creates an integer variable called distance −
feet distance;
DERIVED DATA TYPES
The data-types that are derived from the primitive or built-in data types are referred to as
Derived Data Types. These can be of four types namely:
Syntax:
FunctionType FunctionName(parameters)
2. Array: An array is a collection of items stored at continuous memory locations. The idea of
Syntax:
DataType ArrayName[size_of_array];
Syntax:
datatype *var_name;
4. 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.
member1;
member2;
member3;
memberN;
};
Data Member: These members are normal C++ variables. We can create a structure with
variables of different data types in C++.
Member Functions: These members are normal C++ functions. Along with variables, we
can also include functions inside a structure declaration.
UNIONS IN C++:
A union is a type of structure that can be used where the amount of memory used is a key
factor.
Similarly to the structure, the union can contain different types of data types.
Each time a new variable is initialized from the union it overwrites the previous in C
language but in C++ we also don’t need this keyword and uses that memory location.
This is most useful when the type of data being passed through functions is unknown, using
a union which contains all possible data types can remedy this problem.
It is declared by using the keyword “union“.
ENUMERATED IN C++
Enum is the short name for enumeration. It is a user-defined data type. It is used to
define a list of options that can be selected. Once, enum is declared we cannot change its value,
the compiler will throw an error. Two enumerations cannot share the same names.
enum enumName{
member1;
member2;
member3;
memberN;
};
DIFFERENCE BETWEEN STRUCTURES AND UNION:
[Link] STRUCTURE UNION
1 A structure is defined with ‘struct’ A Union is defined with ‘Union’
keyword keyword.
2 All members of a structure can be The members of a union can be
manipulated simultaneously manipulated only one at a ime.
3 The size of a structure object is equal to The size of a union object is equal to the
the sum of the individual sizes of the size of largest member object.
member object.
4 Structure members are allocated distinct Union members share common memory
memory locations. space for their exclusive usage.
5 Structures are not considered as memory Unions are considered as memory
efficient in comparison to unions. efficient particularly in situations when
the members are not required to be
accessed simultaneously.
6 Structures in C++ behave just like a Unions retain their core functionality in
class. Almost everything that can be C++ with slight add-one like declaration
achieved with a class can also be done of anonymous unions.
with structures.
CHARACTER SET:
Character set is a set of valid characters that a language can recognise. A character
represents any letter, digits, or any other sign.
1. KEYWORDS:
Keywords are pre-defined or reserved words in a programming language. Each keyword
is meant to perform a specific function in a program. Since keywords are referred names for a
compiler, they can’t be used as variable names because by doing so, we are trying to assign a
new meaning to the keyword which is not allowed. You cannot redefine keywords. However,
you can specify the text to be substituted for keywords before compilation by using C/C++
preprocessor directives. C language supports 32 keywords which are given below:
Auto Double Int struct
There are certain rules that should be followed while naming c identifiers:
They must begin with a letter or underscore (_).
They must consist of only letters, digits, or underscore. No other special character is
allowed.
It should not be a keyword.
It must not contain white space.
It should be up to 31 characters long as only the first 31 characters are significant.
main: method name.
a: variable name.
3. CONSTANTS:
Constants are also like normal variables. But, the only difference is, their values can not
be modified by the program once they are defined. Constants refer to fixed values. They are
also called literals.
Constants may belong to any of the data type
SYNTAX:
const data_type variable_name; (or)
const data_type *variable_name;
Types of Constants:
4. STRINGS:
Strings are nothing but an array of characters ended with a null character (‘\0’). This null
character indicates the end of the string. Strings are always enclosed in double-quotes.
Therefore a character is enclosed with single quotes in C and C++.
5. SPECIAL SYMBOLS:
The following special symbols are used in C having some special meaning and thus, cannot
be used for some other purpose.[] () {}, ; * = #
Brackets[]: Opening and closing brackets are used as array element reference. These
indicate single and multidimensional subscripts.
Parentheses(): These special symbols are used to indicate function calls and function
parameters.
Braces{}: These opening and ending curly braces mark the start and end of a block of code
containing more than one executable statement.
Comma (, ): It is used to separate more than one statements like for separating parameters
in function calls.
Colon(:): It is an operator that essentially invokes something called an initialization list.
Semicolon(;): It is known as a statement terminator. It indicates the end of one logical
entity. That’s why each individual statement must be ended with a semicolon.
Asterisk (*): It is used to create a pointer variable and for the multiplication of variables.
Assignment operator(=): It is used to assign values and for the logical operation
validation.
Pre-processor (#): The preprocessor is a macro processor that is used automatically by the
compiler to transform your program before actual compilation.
6. OPERATORS:
Operators are symbols that trigger an action when applied to C variables and other
objects. The data items on which operators act upon are called operands.
Depending on the number of operands that an operator can act upon, operators can be
classified as follows:
Unary Operators: Those operators that require only a single operand to act upon are
known as unary [Link] Example increment and decrement operators
Binary Operators: Those operators that require two operands to act upon are called binary
operators. Binary operators are classified into :
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operator
Ternary Operator: The operator that require three operands to act upon are called ternary
operator. Conditional Operator(?) is also called ternary operator.
Syntax: (Expression1)? expression2: expression3;
VARIABLES:
VARIABLE DECLARATION:
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.
HERE,
datatype: Type of data that can be stored in this variable.
variable_name: Name given to the variable.
value: It is the initial value stored in the variable.
EXAMPLES:
float simpleInterest;
char var;
The variable declaration refers to the part where a variable is first declared or
introduced before its first use.
A variable definition is a part where the variable is assigned a memory location and a
value. Most of the time, variable declaration and definition are done together.
TYPES OF VARIABLES:
There are three types of variables based on the scope of variables in C++:
Local Variables
Instance Variables
Static Variables
1. Local Variables: A variable defined within a block or method or constructor is called a
local variable.
These variables are created when entered into the block or the function is called and
destroyed after exiting from the block or when the call returns from the function.
The scope of these variables exists only within the block in which the variable is
declared. i.e. we can access this variable only within that block.
Initialization of Local Variable is Mandatory.
2. Instance Variables: Instance variables are non-static variables and are declared in a class
outside any method, constructor or block.
As instance variables are declared in a class, these variables are created when an object
of the class is created and destroyed when the object is destroyed.
Unlike local variables, we may use access specifiers for instance variables. If we do not
specify any access specifier then the default access specifier will be used.
Initialization of Instance Variable is not Mandatory.
Instance Variable can be accessed only by creating objects.
3. Static Variables: Static variables are also known as Class variables.
These variables are declared similarly as instance variables, the difference is that static
variables are declared using the static keyword within a class outside any method
constructor or block.
Unlike instance variables, we can only have one copy of a static variable per class
irrespective of how many objects we create.
Static variables are created at the start of program execution and destroyed
automatically when execution ends.
Initialization of Static Variable is not Mandatory. Its default value is 0
If we access the static variable like the Instance variable (through an object), the
compiler will show the warning message and it won’t halt the program. The compiler
will replace the object name with the class name automatically.
If we access the static variable without the class name, the Compiler will automatically
append the class name.
Each object will have its own copy of the instance variable whereas we can only have one
copy of a static variable per class irrespective of how many objects we create.
Changes made in an instance variable using one object will not be reflected in other objects
as each object has its own copy of the instance variable. In the case of static, changes will
be reflected in other objects as static variables are common to all objects of a class.
We can access instance variables through object references and Static Variables can be
accessed directly using the class name.
}
CONTROL FLOW STATEMENTS:
Control flow or flow of control is the order in which instructions, statements and function
calls being executed or evaluated when a program is running. The control flow statements are
also called as Flow Control Statements.
In C++, Control flow statements are mainly categorized in following types –
Selection statements
Iteration statements
Jump statements
In C++, Selection statements allow you to control the flow of the program during run time on the
basis of the outcome of an expression or state of a variable. Selection statements are also referred
to as Decision making statements. Selection statements evaluate single or multiple test
expressions which results in “TRUE” or “FALSE”. The outcome of the test expression/condition
helps to determine which block of statement(s) to execute if the condition
is “TRUE” or “FALSE” otherwise.
In C++, we have following selection statements –
In C++, Iteration statements are used to execute the block of code repeatedly for a
specified number of times or until it meets a specified condition. Iteration statements are
commonly known as loops or looping statements.
In C++, we have following iteration statements available-
Jump statements are used to alter or transfer the control to other section or statements in
your program from the current section.
There is case where we want a block of code to be executed when some condition is
satisfied. In C++, we have rich set of Decision Making Statement that enable computer to decide
which block of code to be executed based on some conditional choices. Decision making
statement statements is also referred to as selection statements. Decision making statement
evaluates single or multiple test expressions which results is “TRUE” or “FALSE”. The outcome
of the test expression/condition helps to determine which block of statement(s) to execute if the
condition is “TRUE” or “FALSE” otherwise.
In C++, we have following decision making statements –
C++ if Statements
C++ if else Statements
C++ if else if Statements
C++ Nested If Statements
C++ Switch Case Statement
C++ IF STATEMENT:
If statement, allow a block of code to be executed only when a specified condition is true.
An if statement evaluates a boolean expression followed by one or more statements. The given
boolean expression results in a boolean value that can only be either true or false.
Syntax:-
if(condition){
// statements
}
Here, Condition is a Boolean expression that results in either True or False, if it results
in True then statements inside if body are executed, if it results in False then execution is skipped
from if body.
In C++, when we want to execute a block of code when if condition is true and another
block of code when if condition is false, In such a case we use if…else statement.
Syntax:-
if(condition){
// statements
} else {
// statements
Here, Condition is a Boolean expression that results in either True or False, if it results
in True then statements inside if body are executed, if it results in False then statements inside
else body are executed.
When we want to add multiple condition checks in single if else statement then by using
if else-if else statement we can easily add multiple conditions. In C++, if..else..if statement
allows us add alternative set of test conditions in if..else statement using else-if and
single else statements for if condition. In such way if..else..if statement is used to select one
among several blocks of code to be executed.
Syntax:-
if(condition1) {
// statement(s)}
else if(condition2){
// statement(s)}
else if(conditionN){
// statement(s)}
else {
// statement(s)}
if(condition2){ // statements
} else {
// statements}}
else {
if(condition3){// statements
In C++, switch case statement is simplified form of the C++ Nested if else statement , it
helps to avoid long chain of if..else if..else statements. A switch case statement evaluates an
expression against multiple cases in order to identify the block of code to be executed.
Syntax:-
switch(expression){
case value1:
// statements
break;
case value2:
// statements
break;
default:
// statements
break;
}
For loop is used, to execute block of code nth times. In C++, basic for loop is similar as it
is in C. For loop takes a variable as iterator and assign it with an initial value, and iterate through
the loop body as long as the test condition is true.
Syntax:
// loop body
}
C++ WHILE LOOP
While loop will execute a block of statement as long as a test expression is true.
Syntax:
while(condition)
// loop body
The do…while statement executes loop statements and then test the condition for next
iteration and executes next only if condition is true.
Syntax:
do{
// loop body
} while(condition);
C++ CONTINUE STATEMENT:
In C++, the continue statement gives you way to skip over the current iteration of any
loop. When a continue statement is encountered in the loop, the rest of statements in the loop
body for current iteration and returns the program execution to the very first statement in the
loop body. It does not terminates the loop rather continues with the next iteration.
In C++, break statement inside any loop gives you way to break or terminate the
execution of loop containing it, and transfers the execution to the next statement following the
loop. It is almost always used with if..else construct.
In C++, goto statement is used to alter the normal execution of a program and transfer
control to a labeled statement in the same program. In a C++ program we can have multiple goto
and label statements, the goto statement is followed by a label name. Label is an identifier, which
can be any plain text and can be set anywhere in a C++ program above or below to goto
statement. When a goto statement is encountered, compiler transfers the control to
a label: specified with goto statement and begin execution from there.
ARRAYS:
An array is a collection of items stored at contiguous memory locations. The idea is to
store multiple items of the same type together. This makes it easier to calculate the position of
each element by simply adding an offset to a base value, i.e., the memory location of the first
element of the array (generally denoted by the name of the array). The base value is index 0
and the difference between the two indexes is the offset.
ARRAY’S SIZE:
In C language, the array has a fixed size meaning once the size is given to it, it cannot be
changed i.e. you can’t shrink it nor can you expand it. The reason was that for expanding if we
change the size we can’t be sure ( it’s not possible every time) that we get the next memory
location to us for free. The shrinking will not work because the array, when declared, gets
memory statically allocated, and thus compiler is the only one that can destroy it.
TYPES OF ARRAYS:
1. One dimensional array (1-D arrays)
2. Multidimensional array
MULTIDIMENSIONAL ARRAY:
Multi-dimensional array can be termed as an array of arrays that stores homogeneous
data in tabular form. Data in multidimensional arrays are stored in row-major order.
FUNCTIONS:
Function is a group of statements that together perform a task. Every C++ program has at
least one function, which is main(), and all the most trivial programs can define additional
functions.
We can divide up your code into separate functions. How you divide up your code among
different functions is up to you, but logically the division usually is such that each function
performs a specific task.
A function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body of the function.
The C++ standard library provides numerous built-in functions that your program can
call. For example, function strcat() to concatenate two strings, function memcpy() to copy one
memory location to another location and many more functions.
DEFINING A FUNCTION:
A C++ function definition consists of a function header and a function body. Here are all the
parts of a function −
Return Type − A function may return a value. The return_type is the data type of the
value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type is the keyword void.
Function Name − This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
Parameters − A parameter is like a placeholder. When a function is invoked, you pass a
value to the parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.
Function Body − The function body contains a collection of statements that define what
the function does.
FUNCTION DECLARATIONS:
A function declaration tells the compiler about a function name and how to call the
function. The actual body of the function can be defined separately.
For the above defined function max(), following is the function declaration −
Parameter names are not important in function declaration only their type is required, so
following is also valid declaration −
Function declaration is required when you define a function in one source file and you
call that function in another file. In such case, you should declare the function at the top of the
file calling the function.
CALLING A FUNCTION:
Creating a C++ function, you give a definition of what the function has to do. To use a
function, you will have to call or invoke that function.
When a program calls a function, program control is transferred to the called function. A
called function performs defined task and when it’s return statement is executed or when its
function-ending closing brace is reached, it returns program control back to the main program.
To call a function, you simply need to pass the required parameters along with function
name, and if function returns a value, then you can store returned value.
FUNCTION ARGUMENTS:
If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are
created upon entry into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a function –
This method copies the actual value of an argument into the formal parameter of the
function. In this case, changes made to the parameter inside the function have no effect
on the argument.
2 Call by Pointer
This method copies the address of an argument into the formal parameter. Inside the
function, the address is used to access the actual argument used in the call. This means
that changes made to the parameter affect the argument.
3 Call by Reference
This method copies the reference of an argument into the formal parameter. Inside the
function, the reference is used to access the actual argument used in the call. This means
that changes made to the parameter affect the argument.
By default, C++ uses call by value to pass arguments. In general, this means that code
within a function cannot alter the arguments used to call the function and above mentioned
example while calling max() function used the same method.
When you define a function, you can specify a default value for each of the last
parameters. This value will be used if the corresponding argument is left blank when calling to
the function.
This is done by using the assignment operator and assigning values for the arguments in
the function definition. If a value for that parameter is not passed when the function is called, the
default given value is used, but if a value is specified, this default value is ignored and the passed
value is used instead. Consider the following example −
INLINE FUNCTION:
Inline function is one of the important feature of C++. 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 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 execution time of small
function is less than the switching time.
C++ provides an inline functions to reduce the function call overhead. 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 inline function call. This
substitution is performed by the C++ compiler at compile time. Inline function may increase
efficiency if it is small.
// function code
Remember, inlining is only a request to the compiler, not a command. Compiler can
ignore the request for inlining. Compiler may not perform inlining in such circumstances like:
1) If a function contains a loop. (for, while, do-while)
2) If a function contains static variables.
3) If a function is recursive.
4) If a function return type is other than void, and the return statement doesn’t exist in function
body.
5) If a function contains switch or goto statement.
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 size of the binary
executable file. Thrashing in memory causes performance of computer to degrade.
UNIT 3
A Class is a user defined data-type which has data members and member functions.
Data members are the data variables and member functions are the functions used to
manipulate these variables and together these data members and member functions defines
the properties and behavior of the objects in a Class.
In the above example of class Car, the data member will be speed limit, mileage etc and
member functions can be apply brakes, increase speed etc.
DECLARING OBJECTS:
When a class is defined, only the specification for the object is defined; no memory or
storage is allocated. To use the data and access functions defined in the class, you need to
create objects.
Syntax:
ClassName ObjectName;
Accessing data members and member functions: The data members and member
functions of class can be accessed using the dot(‘.’) operator with the object. For example if
the name of object is obj and you want to access the member function with the
name printName() then you will have to write [Link]() .
ACCESSING DATA MEMBERS:
The public data members are also accessed in the same way given however the private
data members are not allowed to be accessed directly by the object. Accessing a data
member depends solely on the access control of that data member.
This access control is given by Access modifiers in C++. There are three access
modifiers: public, private and protected.
#include <bits/stdc++.h>
class Geeks
{ // Access specifier
public:
// Data Members
string geekname;
// Member Functions()
void printname()
{
};
int main() {
Geeks obj1;
[Link] = "Abhi";
[Link]();
return 0;
#include <bits/stdc++.h>
class Geeks
public:
string geekname;
int id;
void printname();
// printid is defined inside class definition
void printid()
};
void Geeks::printname()
int main() {
Geeks obj1;
[Link] = "xyz";
[Link]=15;
// call printname()
[Link]();
// call printid()
[Link]();
return 0;
Note that all the member functions defined inside the class definition are by
default inline, but you can also make any non-class function inline by using keyword inline
with them. Inline functions are actual functions, which are copied everywhere during
compilation, like pre-processor macro, so the overhead of function calling is reduced.
Note: Declaring a friend function is a way to give private access to a non-member function.
DATA HIDING:
FRIEND CLASS:
A friend class can access private and protected members of other class in which it is
declared as friend. It is sometimes useful to allow a particular class to access private members
of other class.
For example, a LinkedList class may be allowed to access private members of Node.
A friend class can access both private and protected members of the class in which it has been
declared as friend.
FRIEND FUNCTION:
Like friend class, a friend function can be given a special grant to access private and
protected members. A friend function can be:
a) A member of another class
b) A global function
A friend function is a special function in C++ which in-spite of not being member function
of a class has privilege to access 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.
When friend function is called neither name of object nor dot operator is used. However it
may accept the object as argument whose value it want to access.
Friend function can be declared in any section of the class i.e. public or private or
protected.
Syntax :
class <class_name>
Following are some important points about friend functions and classes:
1) Friends should be used only for limited purpose. Too many functions or external classes are
declared as friends of a class with protected or private data, it lessens the value of
encapsulation of separate classes in object-oriented programming.
2) Friendship is not mutual. If class A is a friend of B, then B doesn’t become a friend of A
automatically.
3) Friendship is not inherited.
4) The concept of friends is not there in Java.
MERITS:
A friend function is able to access members without the need of inheriting the class.
Friend function acts as a bridge between two classes by accessing their private data.
It can be used to increase the versatility of overloaded operator.
It can be declared either in the public or private or protected part of class.
DEMERITS:
Friend functions have access to private members of a class from outside the class which
violates the law of the data hiding.
Friend functions cannot do any run time polymorphism in its members.
CONSTRUCTORS:
Constructor is a member function of class, whose name is same as the class.
Constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object that is why it is known as constructors.
Constructor does not have a return value, hence they do not have a return type.
PROTOTYPE OF CONSTRUCTORS:
<class-name> (list-of-parameters);
<class-name> (list-of-parameters)
// constructor definition
// constructor definition}
CHARACTERISTICS OF CONSTRUCTOR:
• The name of the constructor is same as its class name.
• Constructors are mostly declared in the public section of the class though it can be declared
in the private section of the class.
• Constructors do not return values; hence they do not have a return type.
• A constructor gets called automatically when we create the object of the class.
• Constructors can be overloaded.
• Constructor can not be declared virtual.
TYPES OF CONSTRUCTORS:
Default Constructors: Default constructor is the constructor which doesn’t take any argument.
It has no parameters.
It is also called a zero argument constructor.
Note: Even if we do not define any constructor explicitly, the compiler will automatically
provide a default constructor implicitly
When an object is declared in a parameterized constructor, the initial values have to be passed
as arguments to the constructor function. The normal way of object declaration may not work.
The constructors can be called explicitly or implicitly.
1. It is used to initialize the various data elements of different objects with different values
when they are created.
2. It is used to overload constructors.
Copy Constructor: A copy constructor is a member function which initializes an object using
another object of the same class.
Whenever we define one or more non-default constructors ( with parameters ) for a class, a
default constructor( without parameters ) should also be explicitly defined as the compiler will
not provide a default constructor in this case. However, it is not necessary but it’s considered
to be the best practice to always define a default constructor.
Sample(Sample &t)
{
id=[Link];
}
DESTRUCTOR:
Destructor is also a special member function like constructor. Destructor destroys the
class objects created by constructor. Destructor has the same name as their class name
preceded by a tiled (~) symbol. It is not possible to define more than one destructor. The
destructor is only one way to destroy the object create by constructor. Hence destructor can-not
be overloaded. Destructor neither requires any argument nor returns any value. It is
automatically called when object goes out of scope. Destructor release memory space
occupied by the objects created by constructor. In destructor, objects are destroyed in the
reverse of an object creation.
CHARACTERISTICS OF A DESTRUCTOR:-
1. Destructor is invoked automatically by the compiler when its corresponding constructor
goes out of scope and releases the memory space that is no longer requires by the program.
2. Destructor neither requires any argument nor returns any value therefore it cannot be
overloaded.
3. Destructor cannot be declared as static and const;
4. Destructor should be declared in the public section of the program.
5. Destructor is called in the reverse order of its constructor invocation.
CONSTRCTOR OVERLOADING:
In C++, We can have more than one constructor in a class with same name, as long as each has
a different list of arguments. This concept is known as Constructor Overloading and is quite
similar to function overloading.
Overloaded constructors essentially have the same name (exact name of the class) and
differ by number and type of arguments.
A constructor is called depending upon the number and type of arguments passed.
While creating the object, arguments must be passed to let compiler know, which
constructor needs to be called.
If we inherit a class from another class and create an object of the derived class, it is
clear that the default constructor of the derived class will be invoked but before that the default
constructor of all of the base classes will be invoke, i.e the order of invocation is that the base
class’s default constructor will be invoked first and then the derived class’s default constructor
will be invoked.
when a class is inherited , the data members and member functions of base class comes
automatically in derived class based on the access specifier but the definition of these members
exists in base class only. So when we create an object of derived class, all of the members of
derived class must be initialized but the inherited members in derived class can only be
initialized by the base class’s constructor as the definition of these members exists in base class
only. This is why the constructor of base class is called first to initialize all the inherited
members.