CPP Module 1 New
CPP Module 1 New
Unit 1: (10 hrs.) Principles of Object Oriented Programming, Beginning with C++ Procedure
Oriented Programming-Object Oriented Programming-Basic concepts of object-oriented
programming- Benefits of OOP- Applications of OOP-A simple C++program-Structure of C++
program C++ data types- Symbolic constants- Reference by variables-Operators in C++- Operator
precedence Control structures- Function in C++ - The main function, Function prototyping- Call by
reference- Return by reference- Inline function- Default arguments- Function overloading.
Procedure-Oriented Programming
In the procedure oriented approach, the problem is viewed as the sequence of things to be
done such as reading, calculating and printing such as cobol, fortran and c. The primary
focus is on functions. The technique of hierarchical decomposition has been used to specify
the tasks to be completed for solving a problem
Procedure oriented programming basically consists of writing a list of instructions for the
computer to follow, and organizing these instructions into groups known as functions
In a multi-function program, many important data items are placed as global so that they
may be accessed by all the functions. Each function may have its own local data
1
1. Unrestricted Access (for Global variables)
Global data are more vulnerable to an inadvertent change by a function. In a large
program it is very difficult to identify what data is used by which function. In case we
need to revise an external data structure, we also need to revise all functions that access
the data. This provides an opportunity for bugs to creep in.
Another serious drawback with the procedural approach is that we do not model
real world problems very well. This is because functions are action-oriented and do not
really corresponding to the element of the problem.
2
• Programs are divided into what are known as objects.
• Data structures are designed such that they characterize the objects.
• Functions that operate on the data of an object are ties together in the data structure.
• Data is hidden and cannot be accessed by external function.
• Objects may communicate with each other through function.
• New data and functions can be easily added whenever necessary.
• Follows bottom up approach in program design.
Basic Concepts of Object Oriented Programming
1. Objects
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.
Programming problem is analyzed in term of objects and the nature of communication
between them. Program objects should be chosen such that they match closely with the
real-world objects. Objects take up space in the memory and have an associated address
like a record in Pascal, or a structure in c.
When a program is executed, the objects interact by sending messages to one
another. For example, if “customer” and “account” are to object in a program, then the
customer object may send a message to the count object requesting for the bank balance.
Each object contain data, and code to manipulate data. Objects can interact without having
to know details of each other’s data or code. It is a sufficient to know the type of message
accepted, and the type of response returned by the objects.
2. Classes
3
Objects contain data, and code to manipulate that data. The entire set of data and
code of an object can be made a user-defined data type with the help of class. In fact,
objects are variables of the type class. Once a class has been defined, we can create any
number of objects belonging to that class. Each object is associated with the data of type
class with which they are created. A class is thus a collection of objects similar types. For
examples, Mango, Apple and orange members of class fruit. Classes are user-defined that
types and behave like the built-in types of a programming language. The syntax used to
create an object is not different then the syntax used to create an integer object in C. If fruit
has been defines as a class, then the statement Fruit Mango;
Will create an object mango belonging to the class fruit.
Since the classes use the concept of data abstraction, they are known as Abstract
Data Types (ADT).
4. Inheritance
Inheritance is the process by which objects of one class acquired the properties of
objects of another classes. It supports the concept of hierarchical classification. For
example, the bird, ‘robin’ is a part of class ‘flying bird’ which is again a part of the class
‘bird’. The principal behind this sort of division is that each derived class shares common
characteristics with the class from which it is derived as illustrated
In OOP, the concept of inheritance provides the idea of reusability. This means that we can
add additional features to an existing class without modifying it. This is possible by deriving
4
a new class from the existing one. The new class will have the combined feature of both the
classes. The real appeal and power of the inheritance mechanism is that it allows the
programmer to reuse a class i.e almost, but not exactly, what he wants, and to tailor the
class in such a way that it does not introduced any undesirable side-effects into the rest of
classes.
5. Polymorphism
Polymorphism is another important OOP concept. Polymorphism, a Greek term,
means the ability to take more than on form. An operation may exhibit different behavior is
different instances. The behavior depends upon the types of data used in the operation. For
example, consider the operation of addition. For two numbers, the operation will generate a
sum. If the operands are strings, then the operation would produce a third string by
concatenation. The process of making an operator to exhibit different behaviors in different
instances is known as operator overloading.
Also a single function name can be used to handle different number and different
types of argument. This is something similar to a particular word having several different
meanings depending upon the context. Using a single function name to perform different
type of task is known as function overloading.
Polymorphism plays an important role in allowing objects having different internal
structures to share the same external interface. This means that a general class of
operations may be accessed in the same manner even though specific action associated
with each operation may differ. Polymorphism is extensively used in implementing
inheritance.
6. Dynamic Binding
Binding refers to the linking of a procedure call to the code to be executed in
response to the call. Dynamic binding means that the code associated with a given
procedure call is not known until the time of the call at run time. It is associated with
polymorphism and inheritance. A function call associated with a polymorphic reference
depends on the dynamic type of that reference.
7. Message Passing
An object-oriented program consists of a set of objects that communicate with each other.
The process of programming in an object-oriented language, involves the following basic
steps:
1. Creating classes that define object and their behavior,
2. Creating objects from class definitions, and
3. Establishing communication among objects.
Objects communicate with one another by sending and receiving information much the
same way as people pass messages to one another. The concept of message passing makes
it easier to talk about building systems that directly model or simulate their real-world
counterparts.
A Message for an object is a request for execution of a procedure, and therefore will invoke
a function (procedure) in the receiving object that generates the desired results. Message
5
passing involves specifying the name of object, the name of the function (message) and the
information to be sent. Example: Employee. Salary (name);
Here Employee is the Object,Salary is the message and Name is the information
Object has a life cycle. They can be created and destroyed. Communication with an
object is feasible as long as it is alive.
Benefits of OOP
1. Through inheritance, we can eliminate redundant code extend the use of existing
Classes.
2. The principle of data hiding helps the programmer to build secure program that can
not be invaded by code in other parts of a programs.
3. It is possible to have multiple instances of an object to co-exist without any
interference.
4. It is possible to map object in the problem domain to those in the program.
5. It is easy to partition the work in a project based on objects.
6. The data-centered design approach enables us to capture more detail of a model can
implemental form.
7. Object-oriented system can be easily upgraded from small to large system.
8. Message passing techniques for communication between objects makes to interface
descriptions with external systems much simpler.
9. Software complexity can be easily managed
Applications of OOP
The promising areas of application of OOP include:
1. Real-time system
2. Simulation and modeling
3. Object-oriented data bases
4. Hypertext, Hypermedia, and expertext
5. AI and expert systems
6. Neural networks and parallel programming
7. Decision support and office automation systems
8. CIM/CAM/CAD systems
Introduction of C++
C++ is an object-oriented programming language. It was developed by Bjarne
Stroustrup at AT&T Bell Laboratories in Murray Hill, New Jersey, USA, in the early 1980’s.
Stroustrup, an admirer of Simula67 and a strong supporter of C, wanted to combine the best
of both the languages and create a more powerful language that could support object-
oriented programming features and still retain the power and elegance of C. The result was
C++. Therefore, C++ is an extension of C with a major addition of the class construct feature
of Simula67. Since the class was a major addition to the original C language, Stroustrup
initially called the new language ‘C with classes’. However, later in 1983, the name was
changed to C++. The idea of C++ comes from the C increment operator ++, thereby
suggesting that C++ is an augmented version of C.
6
C+ + is a superset of C. Almost all c programs are also C++ programs. However, there
are a few minor differences that will prevent a c program to run under C++ complier. We
shall see these differences later as and when they are encountered.
The most important facilities that C++ adds on to C are classes, inheritance, function
overloading and operator overloading. These features enable creating of abstract data
types, inherit properties from existing data types and support polymorphism, thereby
making C++ a truly object-oriented language.
Application 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 applications systems.
• Since C++ allow us to create hierarchy related objects, 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 properly, the C part of C++ gives the
language the ability to get closed 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 a general-purpose language in the near future.
Comments
C++ introduces a new comment symbol // (double slash). Comment start with a double slash
symbol and terminate at the end of the line. A comment may start anywhere in the line, and
whatever follows till the end of the line is ignored. Note that there is no closing symbol.
The double slash comment is basically a single line comment.
The C comment symbols /*,*/ are still valid and are more suitable for multiline
comments.
supports single line and multi-line comments.
All characters available inside any comment are ignored by C++ compiler.
Block comments start with /* and end with */
Line comments start with //,extending to the end of the line
eg:-
// This is a single line comment
/* C++ comments can also
* span multiple lines
*/
Header Files
The #include directive instructs the compiler to include the contents of the file
enclosed within angular brackets into the source file.
a header file sometimes known as an include file.
Header files almost always have a .h extension.
The purpose of a header file is to hold declarations for other files or functions to
use.
Examples :- iostream.h, conio.h , string.h, stdio.h, etc….
iostream. h - input output stream. iostream.h is used for input output functions .
( cout , cin) .
7
conio. h - concatenated input output . conio.h includes the declarations of getch,
getc, putc, clrscr, etc.
string. h - used for string handling functions such as strcpy, strlen strrev, strcpy etc….
OOPs approach is based on the concept of client-server model. The class definition including
the member functions constitute the server that provides services to the main program
known as client. The client uses the server through the public interface of the class.
int main ()
• This line corresponds to the beginning of the definition of the main function.
8
• The main function is the point by where all C++ programs start their execution,
independently of its location within the source code.
• It does not matter whether there are other functions with other names defined
before or after it – the instructions contained within this function's definition will
always be the first ones to be executed in any C++ program. For that same reason, it
is essential that all C++ programs have a main function.
• The word main is followed in the code by a pair of parenthesis (()). That is because it
is a function declaration:
• Right after these parentheses we can find the body of the main function
enclosed in braces ({}). What is contained within these braces is what the
function does when it is executed.
Output operator
The statement cout causes the string in quotation marks to be displayed on the
screen. This statement introduces two new C++ features, cout and <<. The identifier
cout(pronounced as C out) is a predefined object that represents the standard output
stream in C++. Here, the standard output stream represents the screen. It is also
possible to redirect the output to other output devices. The operator << is called the
insertion or put to operator.
example:- cout<<”C++ is better than C.”;
Input Operator
The statement cin >> number1;
>> is an input statement and causes the program to wait for the user to type in a number.
The number keyed in is placed in the variable number1. The identifier cin (pronounced ‘C
in’) is a predefined object in C++ that corresponds to the standard input stream. Here, this
stream represents the keyboard.
The operator >> is known as extraction or get from operator. It extracts (or takes) the value
from the keyboard and assigns it to the variable on its right. This corresponds to a familiar
scanf() operation. Like <<, the operator >> can also be overloaded.
9
Cascading of I/O Operators
Tokens
The smallest individual units in a program are known as tokens.
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Operators and special characters
1. Keywords
Keywords are the reserved words used in C++. We cannot use the keywords as variables.
Eg :- public, while, void, friend, if, int …etc.
2.Identifiers (variables)
A variable is used to store values in the program.A valid identifier is a sequence of one
or more letters, digits or underscore characters (_).
eg :- int A, B, C ;
Initialization of variables
There are two ways to initialize variables in C++:
type identifier = initial_value ;
For example:
int a = 0;
10
type identifier (initial_value) ;
For example:
int a (0);
This way to initialize variables, known as constructor initialization, is done by enclosing
the initial value between parentheses (()):
3. Constants
Constants have fixed value. Constants, like variables, contain data type.
Defining Constants:
There are two simple ways in C++ to define constants:
Using #define preprocessor.
Using const keyword.
4. Strings
Strings in C++ are classified as Character String and String Class
Actually, you do not place the null character at the end of a string constant. The C++
compiler automatically places the '\0' at the end of the string when it initializes the array.
C++ supports a wide range of functions that manipulate null-terminated strings:
Function & Purpose
strcpy(s1, s2);
Copies string s2 into string s1.
11
strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
strlen(s1);
Returns the length of string s1.
strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.
strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.
4.2 String Class
The standard C++ library provides a string class type that supports all the operations
mentioned above, additionally much more functionality.
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
Arithmetic Operators:
12
equal or not, if values are not equal
then condition becomes true.
Checks if the value of left operand is
> greater than the value of right operand, (A > B) is not true.
if yes then condition becomes true.
Checks if the value of left operand is
< less than the value of right operand, if (A < B) is true.
yes then condition becomes true.
Checks if the value of left operand is
greater than or equal to the value of
>= (A >= B) is not true.
right operand, if yes then condition
becomes true.
Checks if the value of left operand is
less than or equal to the value of right
<= (A <= B) is true.
operand, if yes then condition becomes
true.
Logical Operators:
Bitwise operator works on bits and perform bit by bit operation. The truth tables for
&, |, and ^ are as follows:
13
number of bits specified by the right
operand.
Binary Right Shift Operator. The left
operands value is moved right by the
>> A >> 2 will give 15 which is 0000 1111
number of bits specified by the right
operand.
Assignment Operators:
Operator Description
sizeof operator returns the size of a variable. For example
Sizeof
sizeof(a), where a is integer, will return 4.
Conditional operator. If Condition is true ? then it returns value
Condition ? X : Y
X : otherwise value Y
14
Comma operator causes a sequence of operations to be
, performed. The value of the entire comma expression is the
value of the last expression of the comma-separated list.
Member operators are used to reference individual members of
. (dot) and -> (arrow)
classes, structures, and unions.
Casting operators convert one data type to another. For
Cast
example, int(2.2000) would return 2.
Pointer operator & returns the address of an variable. For
&
example &a; will give actual address of the variable.
Pointer operator * is pointer to a variable. For example *var;
*
will pointer to a variable var.
Operators Precedence in C++:
A scope is a region of the program and there are three places where variables can be
declared:
1. Inside a function or a block which is called local variables,
2. In the definition of function parameters which is called formal parameters.
3. Outside of all functions(in the main body of the source code) which is called global
variables.
Local Variables:
Variables that are declared inside a function or block are local variables. They can be used
only by statements that are inside that function or block of code. Local variables are not
known to functions outside their own. Following is the example using local variables:
15
#include <iostream.h>
int main ()
{
// Local variable declaration:
int a, b;
int c;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
}
Global Variables:
Global variables are defined outside of all the functions, usually on top of the program. The
global variables will hold their value throughout the lifetime of your program.A global
variable can be accessed by any function. That is, a global variable is available for use
throughout your entire program after its declaration. Following is the example using global
and local variables:
#include <iostream>
// Global variable declaration:
int g;
int main ()
{
// Local variable declaration:
int a, b;
// actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
}
Global variables can be referred from anywhere in the code, even inside functions,
whenever it is after its declaration.
The scope of local variables is limited to the block enclosed in braces ({}) where they
are declared
Initializing Local and Global Variables:
When a local variable is defined, it is not initalised by the system, you must initalise it
yourself. Global variables are initalised automatically by the system when you define them
16
1. Built-in Data Types
17
bool
wchar_t
2.1 Functions
A function is a group of statements that together perform a task. Every C++ program has at
least one function which is main(), and can define additional functions.
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.
A function is known with various names like a method or a sub-routine or a procedure etc.
Defining a Function:
The general form of a C++ function definition is as follows:
return_type function_name( parameter list )
{
body of the 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
18
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Calling a Function:
While 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 its 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. For example:
#include <iostream.h>
// function declaration
int max(int num1, int num2);
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
int ret;
return 0;
}
return result;
19
}
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:
Call Type Description
This method copies the actual value of an argument into the
formal parameter of the function. In this case, changes made to
Call by value
the parameter inside the function have no effect on the
argument.
This method copies the address of an argument into the formal
parameter. Inside the function, the address is used to access the
Call by pointer
actual argument used in the call. This means that changes made
to the parameter affect the argument.
This method copies the reference of an argument into the
formal parameter. Inside the function, the reference is used to
Call by reference
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.
Benefits:-
1. top-down - structured programming
2. to reduce length of the program
3. reusability
4. function over-loading
Arrays
C++ provides a data structure, the array, which stores a fixed-size sequential collection
of elements of the same type. An array is used to store a collection of data, but it is
often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99,
you declare one array variable such as numbers and use numbers[0], numbers[1],
and ..., numbers[99] to represent individual variables. A specific element in an array is
accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to
the first element and the highest address to the last element.
Declaring Arrays:
To declare an array in C++, the programmer specifies the type of the elements and the
number of elements required by an array as follows:
20
This is called a single-dimension array. The arraySize must be an integer constant
greater than zero and type can be any valid C++ data type. For example, to declare a 10-
element array called balance of type double, use this statement:
double balance[10];
Initializing Arrays:
You can initialize C++ array elements either one by one or using a single statement as
follows:
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
The number of values between braces { } can not be larger than the number of elements
that we declare for the array between square brackets [ ]. Following is an example to
assign a single element of the array:
If you omit the size of the array, an array just big enough to hold the initialization is
created. Therefore, if you write:
double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};
You will create exactly the same array as you did in the previous example.
balance[4] = 50.0;
The above statement assigns element number 5th in the array a value of 50.0. Array
with 4th index will be 5th ie. last element because all arrays have 0 as the index of their
first element which is also called base index. Following is the pictorial representaion of
the same array we discussed above:
An element is accessed by indexing the array name. This is done by placing the index of
the element within square brackets after the name of the array. For example:
double salary = balance[9];
The above statement will take 10th element from the array and assign the value to
salary variable.
Multi Dimensional Arrays
C++ allows multidimensional arrays. Here is the general form of a multidimensional array
declaration:
type name[size1][size2]...[sizeN];
For example, the following declaration creates a three dimensional 5 . 10 . 4 integer
array:
int threedim[5][10][4];
Two-Dimensional Arrays:
The simplest form of the multidimensional array is the two-dimensional array. A two-
dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-
dimensional integer array of size x,y you would write something as follows:
type arrayName [ x ][ y ];
Where type can be any valid C++ data type and arrayName will be a valid C++ identifier.
21
A two dimensional array can be think as a table which will have x number of rows and y
number of columns. A 2-dimentional array a which contains three rows and four
columns can be shown as below:
22
The structure tag is optional and each member definition is a normal variable definition,
such as int i; or float f; or any other valid variable definition. At the end of the structure's
definition, before the final semicolon, you can specify one or more structure variables but it
is optional. Here is the way you would declare the Book structure:
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
}book;
Structure is different from an array in the sense that an array represents an aggregate of
elements of same type whereas a structure represents an aggregate of elements of arbitrary
types..
2. Union
Unions allow one same portion of memory to be accessed as different data types, since
all of them are in fact the same location in memory. Its declaration and use is similar to the
one of structures but its functionality is totally different:union union_name { member_type1
member_name1; member_type2 member_name2; member_type3 member_name3; . . }
object_names;All the elements of the union declaration occupy the same physical space in
memory. Its size is the one of the greatest element of the declaration. all of them are
referring to the same location in memory, the modification of one of the elements will affect
the value of all of them. We cannot store different values in them independent of each
other.One of the uses a union may have is to unite an elementary type with an array or
structures of smaller elements. The exact alignment and order of the members of a union in
memory is platform dependant. Therefore be aware of possible portability issues with this
type of use.
3.Class
Class in C++ is same as structure.Class is a concept of OOP. In a class declaration, we
must use the keyword Class.The class variables are known as objects.A class ends with a
semi colon. The main difference of class and structure is, we can include functions in a
class.
23
4.Enumerated Data Type:
Enumerated data type provides a way for attaching names to numbers. It can be used to assign
names to integer constants.
24
C++ resolved this problem with the use of the scope resolution operator ( :: ).The scope
resolution operator ( :: ) can be used to uncover a hidden variable.
Syntax is :- : : variable-name
This operator allows access to the global version of a variable.
Manipulators
Manipulators are operators that are used to format the data display.
Commonly used manipulators are:
endl // causes a line feed when used in an output statement
setw // to specify field width and force the data to be printed right-justified
Symbolic Constants
Two ways of creating symbolic constant in C++.
1. Using the qualifier const
2. Defining a set of integer constants using enum keyword.
Any value declared as const cannot be modified by the program in any way. In C++, we
can use const in a constant expression.
const int size = 10;
char name[size]; // This is illegal in C.
const allows us to create typed constants.
#define - to create constants that have no type information.
The named constants are just like variables except that their values cannot be changed.
C++ requires a const to be initialized.
A const in C++ defaults, it is local to the file where it is declared. To make it global the
qualifier extern is used.
extern const int total = 100;
enum { X, Y, Z };
This is equivalent to
const int X = 0;const int Y = 1;const int Z = 2;
Reference Variables
A reference variable provides an alias for a previously defined variable.For eg., if we
make the variable sum a reference to the variable total, then sum and total can be used
interchangeably to represent that variable.
data-type & reference-name = variable-name
float total = 100;
float &sum = total;
A reference variable must be initialized at the time of declaration. This establishes
the correspondence between the reference and the data object which it names.
int x ;
int *p = &x ;
25
int & m = *p ;
void f ( int & x )
{
x = x + 10;
}
int main ( )
{
int m = 10;
f (m);
}
Control Structures
1. Sequence Structure (straight line)
2. Selection Structure (branching)
3. Loop Structure (iteration or repetition)
1.Sequence Structure (straight line)
1.1 if Statement-An if statement consists of a boolean expression followed by one or
more statements
The general form is
if (expression)
statement;
26
First expression is evaluated. If the outcome is nonzero then statement is executed.
otherwise, nothing happens.
27
case '-': result = operand1 - operand2;
break;
case '*': result = operand1 * operand2;
break;
case '/': result = operand1 / operand2;
break;
default: cout << "unknown operator: " << ch << '\n';
break;
}
Note:-
nested if statements- can use one if or else if statement inside another if or else if
statement(s)
nested switch statements- can use one swicth statement inside another switch
statement(s).
28
The general form of the for statement is:
for (expression1; expression2; expression3)
statement;
First expression1 is evaluated. Each time round the loop, expression2 is
evaluated. If the outcome is nonzero then statement is executed and
expression3 is evaluated. Otherwise, the loop is terminated
Other Statements
The continue Statement- The continue statement terminates the current iteration of a
loop and instead jumps to the next iteration.
The break Statement- A break statement may appear inside a loop (while, do, or for) or
a switch statement. It causes a jump out of these constructs, and hence terminates them
The goto Statement- The goto statement provides the lowest-level of jumping. It has the
general form:
goto label;
where label is an identifier which marks the jump destination of goto. The label
should be followed by a colon and appear before a statement within the same
function as the goto statement itself.
The return Statement- The return statement enables a function to return a value to its
caller.
It has the general form:
return expression;
where expression denotes the value returned by the function. The type of this value
should match the return type of the function. For a function whose return type is
void, expression should be empty:
return;
The return type of main is always int. The return value of main is what the program
returns to the operating system when it completes its execution.
Functions
A function provides a convenient way of packaging a computational recipe, so that it can
be used as often as required. A function definition consists of two parts: interface and
body.
1. The interface of a function (also called its prototype) specifies how it may be
used. It consists of three entities:
o The function name. This is simply a unique identifier.
o The function parameters (also called its signature). This is a set of zero or
more typed identifiers used for passing values to and from the function.
o The function return type. This specifies the type of value the function
returns.
A function which returns nothing should have the return type void.
29
2. The body of a function contains the computational steps (statements) that
comprise the function.
Using a function involves ‘calling’ it. A function call consists of the function name
followed by the call operator brackets ‘()’, inside which zero or more comma-separated
arguments appear. The number of arguments should match the number of function
parameters.Each argument is an expression whose type should match the type of the
corresponding parameter in the function interface.
The general form of a C++ function definition is as follows:
return_type function_name( parameter list )
{
body of the function
}
Functions-benefits
Dividing a program into functions.
o a major principle of top-down, structured programming.
To reduce the size of the program.
Code re-use.
Function Prototyping
The prototype describes the function interface to the compiler by giving details such
as:
o The number and type of arguments
o The type of return values.
It is a template
When the function is called, the compiler uses the template to ensure that proper
arguments are passed, and the return value is treated correctly.
Function prototype is a declaration statement in the calling program.
The argument-list contains the types and names of arguments that must be passed to
the function.Each argument variable must be declared independently inside the
parentheses.
float avg ( int x, int y) ; // correct
float avg ( int x, y) ; // illegal
In a function declaration, the names of the arguments are dummy variables and
therefore they are optional.
float avg ( int , int ) ;
The variable names in the prototype just act as placeholders and, therefore, if names are
used, they do not have to match the names used in the function call or function
definition.
30
void display( ); // function with an
void display(void); // empty argument list.
Inline function
One of the major objectives of using functions in a program is to save memory space, which becomes
appreciable when a function is likely to be called many times. However, every time a function is called, it takes
a lot of extra time in executing tasks such as jumping to the calling function. When a function is small, a
substantial percentage of execution time may be spent in such overheads and sometimes maybe the time
taken for jumping to the calling function will be greater than the time taken to execute that function.
One solution to this problem is to use macro definitions, commonly known as macros. Preprocessor macros
are popular in C, but the major drawback with macros is that they are not really functions and therefore, the
usual error checking process does not occur during compilation.
C++ has a different solution to this problem. To eliminate the time of calls to small functions, C++ proposes a
new function called inline function. An inline function is a function that is expanded in line when it is invoked
thus saving time. The compiler replaces the function call with the corresponding function code that reduces
the overhead of function calls.
We should note that inlining is only a request to the compiler, not a command. The compiler can ignore and
skip the request for inlining. The compiler may not perform inlining in the following circumstances:
Syntax:
1 inline function-header
2 {
3 function-body
4 }
Example:
31
7
return ++a;
8
}
9
10
int main()
11
{
12
int a = 11;
13
cout << "The cube of 3 is: " << cube(3) << "n";
14
cout << "Incrementing a " << inc(a) << "n";
15
return 0;
16
}
17
Output:
We can use Inline function as per our needs. Some useful recommendation are mentioned below-
We must keep inline functions small, small inline functions have better efficiency and good results.
Inline functions do increase efficiency, but we should not turn all the functions inline. Because if we
make large functions inline, it may lead to code bloat and might end up decreasing the efficiency.
It is recommended to define large functions outside the definition of a class using scope resolution::
operator, because if we define such functions inside a class definition, then they might become inline
automatically and again affecting the efficiency of our code.
32
If we require address of the function in a program, the compiler cannot perform inlining on such
functions. Because for providing the address to a function, the compiler will have to allocate
storage to it. But inline functions don’t get storage, they are kept in Symbol table.
Inline functions might cause thrashing because it might increase the size of the binary executable file.
Thrashing in memory causes the performance of the computer to degrade and it also affects the
efficiency of our code.
The inline function may increase compile time overhead if someone tried to changes the code inside
the inline function then all the calling location has to be recompiled again because the compiler would
require to replace all the code once again to reflect the changes, otherwise it will continue with old
functionality without any change.
Function Overloading
Function Overloading in C++ can be defined as the process of having two or more member functions of a class
with the same name, but different in parameters. In function overloading, the function can be redefined either
by using different types of arguments or a different number of arguments according to the requirement. It is
only through these differences compiler can differentiate between the two overloaded functions.
One of the major advantages of Function overloading is that it increases the readability of the program
because we don’t need to use different names for the same action again and again.
In this way of function overloading, we define two functions with the same names but a different number of
parameters of the same type. For example, in the below-mentioned program, we have made two add()
functions to return the sum of two and three integers.
1 int main()
2 {
3 add(10, 20); // add() with 2 parameter will be called
4
5 add(10, 20, 30); //sum() with 3 parameter will be called
6
7 }
1 #include <iostream>
2
3 using namespace std;
4
33
5 int add(int a, int b)
6 {
7 cout << a+b <<endl;
8 return 0;
9 }
10
11 int add(int a, int b, int c)
12 {
13 cout << a+b+c <<endl;
14 return 0;
15 }
16
17 int main()
18 {
19
20 add(20, 40);
21
22 add(40, 20, 30);
23 }
In the above example, we overload add() function by changing its number of arguments. First, we define an
add() function with two parameters, then we overload it by again defining the add() function but this time with
three parameters.
In this method, we define two or more functions with the same name and the same number of parameters,
but the data type used for these parameters are different. For example in this program, we have three add()
function, the first one gets two integer arguments, the second one gets two float arguments and the third one
gets two double arguments.
1 #include <iostream>
2
3 using namespace std;
4 int add(int x, int y) // first definition
5 {
6 cout<< x+y << endl;
7
8 return 0;
9 }
10
11 float add(float a, float b)
12 {
13 cout << a+b << endl;
14 return 0;
15 }
16
17
18
34
double add(double x, double y)
19 {
20 cout << x+y << endl;
21 return 0;
22 }
23
24 int main()
25 {
26
27
add(20, 40);
28
29
add(23.45f, 34.5f);
30
31
32 add(40.24, 20.433);
33
}
In the above example, we define add() function three times. First using integers as parameters, second using
float as parameters and third using double as a parameter.
Thus we override the add() function twice.
We use function overloading to save the memory space, consistency, and readability of our program.
With the use function overloading concept, we can develop more than one function with the same
name
Function overloading shows the behavior of polymorphism that allows us to get different behavior,
although there will be some link using the same name of the function.
Function overloading speeds up the execution of the program.
Function overloading is used for code reusability and also to save memory.
It helps application to load the class method based on the type of parameter.
Code maintenance is easy.
Function declarations that differ only by its return type cannot be overloaded with function
overloading process.
Member function declarations with the same parameters or the same name types cannot be
overloaded if any one of them is declared as a static member function.
35
1 class XYZ{
2 static void func();
3 void func(); // error
4 };
When the compiler is unable to decide which function it should invoke first among the overloaded functions,
this situation is known as function overloading ambiguity. The compiler does not run the program if it shows
ambiguity error. Causes of Function Overloading ambiguity:
Type Conversion.
Function with default arguments.
Function with a pass by reference
Default argument
A default argument is a value provided in a function declaration that is automatically assigned by the
compiler if the caller of the function doesn’t provide a value for the argument with a default value.
Output:
25
50
80
When Function overloading is done along with default values. Then we need to make sure it will not be
ambiguous.
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 calling function provides values for them. For example, calling
of function sum(10, 15, 25, 30) overwrites the value of z and w to 25 and 30 respectively.
36
During calling of function, arguments from calling function to called function are copied from left to
right. Therefore, sum(10, 15, 25) will assign 10, 15 and 25 to x, y, and z. Therefore, the default value is
used for w only.
Once default value is used for an argument in function definition, all subsequent arguments to it must
have default value. It can also be stated as default arguments are assigned from right to left. For
example, the following function definition is invalid as subsequent argument of default variable z is not
default.
37