FT C++ PDF
FT C++ PDF
to
C++
By Team Digit
Credits
The People Behind This Book
EDITORIAL
Robert Sovereign-Smith Assistant Editor
Santanu Mukherjee, Supratim Bose, Nilay Agambagis, Bhaskar Sur Writers
November 2008
Free with Digit. Not to be sold separately. If you have paid separately for this book,
please e-mail the editor at [email protected] along with details of location of
purchase, for appropriate action.
FAST TRACK 3
CONTENTS
Chapter 5 Functions 61
5.1 Main Function 61
5.2 Function Prototyping 62
5.3 Call By Reference 66
5.4 Return By Reference 68
5.5 Inline Functions 68
5.6 Function Overloading 69
4 FAST TRACK
CONTENTS
FAST TRACK 5
OBJECT ORIENTED
C++ PROGRAMMING I
Object Oriented
Programming
O
bject Oriented Programming (OOP) is a programming
concept, involving objects and their interactions to
design applications and various computer programs.
The highlights included within this programming technique
are encapsulation, modularity, polymorphism, and inheritance.
This concept was not conventionally used in mainstream soft-
ware development and predominantly came into practice in the
early ’90s. These days, most programming languages support
OOP. The main reason for this is the need to remove the flaws
encountered in the typical procedural approach used in archaic
programming through the computing ages.
OOP originates way back to the sixties. Over the years, as the
hardware and software evolved, quality was often compromised.
Analysts and designers were soon looking for ways to address
this problem. OOP focuses on data instead of processes, with
programs composed of self-sufficient modules (objects) that con-
tain all the information needed for manipulation.
FAST TRACK 7
OBJECT ORIENTED
I PROGRAMMING C++
● Classes
● Objects
● Dynamic Binding
● Message passing
Classes
Classes are used to implement the concept of Abstract Data
Types (ADT). A class is a combination of both properties and
methods used to manipulate properties. In fact, a class is a blue-
print describing the nature of the data structure. For example,
consider the case of the class ‘student’. There are some common
properties shared by all students, such as name, roll, class,
address, and marks. Similarly, there might be some methods
used to manipulate these properties. However, the values of
these properties can differ depending in the student. If we want
to use the class ‘student’, then we need to create instances of
this class, also known as objects. Classes are user-defined data
types and behave like a built-in programming language.
Objects
Objects are the basic runtime entities in an object oriented sys-
tem. In fact, it is the instance of a class. An object can be a per-
son, place, bank account or even a table of data that the pro-
8 FAST TRACK
OBJECT ORIENTED
C++ PROGRAMMING I
Dynamic Binding
The term binding refers to linking a procedure call to the code
that needs to be executed as a response to this call. Similarly,
‘Dynamic Binding’ or late binding refers to the code that
remains unknown until the procedure is called during run
time. Dynamic binding is also associated with polymorphism
and inheritance. For example, let us consider a procedure called
‘calculation’ declared in a class. Some classes may inherit that
class. The definitions (code) associated with the procedure ‘cal-
culation’ are written such that they perform different opera-
tions in each derived class. For example, in one class, the code is
written for addition, while in another class for subtraction, and
so on and so forth. For objects of different classes, the procedure
will provide different results and will be unknown till the exe-
cution is complete.
Message Passing
Message passing is the process by which one object sends data to
another, or asks the other object to invoke a method. This con-
cept is also known as interfacing in some programming lan-
guages. In an object-oriented language, objects communicate
with each other by sending and receiving various types of infor-
mation. The message for an object is related to the request for
execution of a procedure, and thus invokes a function in the
receiving object, thereby generating the desired result.
FAST TRACK 9
OBJECT ORIENTED
I PROGRAMMING C++
1.3 Inheritance
10 FAST TRACK
OBJECT ORIENTED
C++ PROGRAMMING I
1.4 Polymorphism
FAST TRACK 11
OBJECT ORIENTED
I PROGRAMMING C++
12 FAST TRACK
C++
BEGINNING WITH C++ II
FAST TRACK 13
II BEGINNING WITH C++
C++
{
cout<<” let us learn a wonderful language”;
14 FAST TRACK
C++
BEGINNING WITH C++ II
return 0;
}
The output of the program is as follows:
a //. They always terminate at the end of the line. The comment
‘//’ is a comment symbol. In C++, comments always starts with
have a main() function, and the actual execution of any C++ pro-
the most important line in the program. Every C++ program must
gram starts from this point. This function is called by the system
and returns a value to the system if required. In the above exam-
FAST TRACK 15
II BEGINNING WITH C++
C++
● Jump Statements: Mainly used for two purposes, either for trans-
ferring control to another location to execute a particular func-
tion, or returning control from a function.
# include <iostream.h>
int main()
{
float x, y;
float sum, ave;
float x,y,sum,ave;
numbers via the keyboard. Next the values of the variables x any y
used to get bytes from input stream class) then accepts two valid
are added and stored in variable ‘sum’. The variable ‘ave’ is used to
FAST TRACK 17
II BEGINNING WITH C++
C++
// classes example
#include <iostream.h>
class Rect {
int x, y;
public:
void setting_values (int,int);
int area () {return (x*y);}
};
int main () {
Rect rec;
rec.setting_values (7,8);
cout << “area: “ << rec.area();
return 0;
}
area: 56
tion. First a class named Rect is declared, with two variables (of
operator is to define a class member from outside the class defini-
type integer) also declared within it. These two variables are x and
y, respectively. The function area() has been defined within the
definition of the class ‘Rect’. Further, the setting_values
method has only its prototype declared within the class but is
actually defined outside of it.
the type int within the setting_values method are passed. The
values are then stored within x and y in the method declaration
part as shown above.
values (7,8) are passed. Then the method area() is called using
FAST TRACK 19
C++
BASICS OF C++ III
Basics Of C++
3.1 Program Structure
The following is a program that displays ‘Hello World’:
#include <iostream.h>
int main ()
{
cout << “Hello World!”;
return 0;
}
Hello World!
FAST TRACK 21
III BASICS OF C++
C++
the short notes to the source code meant for programmers for
future reference.
#include <iostream.h>
int main ()
22 FAST TRACK
C++
BASICS OF C++ III
the string “Hello World”. Don’t miss out on the semi colon that
‘iostream.h’ library file. Once executed, this statement displays
indicates the end of the statement. Missing out on this semi colon
is the most common error committed by programmers.
return 0;
The closing brace indicates the end of the body of the main
function, and the end of the program.
#include <iostream.h>
int main ()
{
cout << “Hello World! “;
cout << “I am Learning Basic Structure of C++”;
return 0;
}
FAST TRACK 23
III BASICS OF C++
C++
3.2 Variables
type variable_list;
int i,j,l;
short int si;
unsigned int ui;
double balance, profit, loss;
// declaration of a variable
#include <iostream.h>
int main ()
{
24 FAST TRACK
C++
BASICS OF C++ III
// declaring variables:
int x, y;
int total;
// process:
x = 5;
y = 2;
x = x + 1;
total = x - y;
// print out the result:
cout << total;
// terminate the program:
return 0;
}
FAST TRACK 25
III BASICS OF C++
C++
#include<iostream.h>
int main()
{
int a;
a=10;
void show_a(void); // prototype of function
show_a
show_a();
return 0;
}
void show_a(void)
{
cout<<a;
}
void cal1(void)
{
int A;
A = 20;
}
void cal2(void)
{
int A;
A = -299;
}
Formal Parameter
We can insert Formal parameters in the function prototype as well
as in the function header of the definition. We also assign values
to the local variables using the argument while calling a function.
Example:
FAST TRACK 27
III BASICS OF C++
C++
This program uses the function is_in() that takes two argu-
ments ‘a’ and ‘b’. During the execution of the function, the values
Hence, the local variables ‘y’ and ‘x’ of the function is_in(),
for ‘a’ and ‘b’ are stored in the variables ‘y’ and ‘x’, respectively.
accept the values of the argument while calling the function. The
function returns ‘2’ if any character of ‘y’ is similar to the value of
‘x’, or else it returns ‘0’. With the values used here, the function
will return ‘2’ and is displayed as usual.
Global Variable
Global variables are created by declaring variables outside a func-
tion. Here, all expressions are independent of the blocks of code
they are inserted into. Any code can use global variables. These
variables can hold the values while executing the program. In the
following example, we can see that the variable ‘calculate’ is
declared outside all functions of the program. A global variable is
best used when declared at the start of the program.
Example:
#include <iostream.h>
void cal1(void);
void cal2(void);
int main(void)
{
calculate = 100;
cal1();
return 0;
}
void cal1(void)
{
int temp;
temp = calculate;
cal2();
28 FAST TRACK
C++
BASICS OF C++ III
.calculate is 100
FAST TRACK 29
III BASICS OF C++
C++
Char
Name Description
Declares characters or small integers.
ASCII characters can be used with this
bool
Declares longer numbers.
Declares the Boolean value. Value can be
float
either ‘true’ or ‘false’.
double
Declares floating point decimal numbers.
Declares double precision floating point
long double
numbers.
Declares long double precision floating
point numbers.
30 FAST TRACK
C++
BASICS OF C++ III
3.4 Constants
● Decimal Notation
● Octa Notation
● Hexadecimal Notation
● String Constant
Now let us look at the following back slash constants and their
meanings:
\b
Code Meaning
\f
Backspace
\n
Form feed
\r
New line
\t
Carriage return
Horizontal tab
FAST TRACK 31
III BASICS OF C++
C++
\”
\’
Double quote
\0
Single quote
\\
Null
\v
Backslash
\a
Vertical tab
\?
Alert
\N
Question mark
\xN
Octal constant (where N is an octal constant)
Hexadecimal constant (where N is a hexadecimal constant)
25 represent decimal
We can define our desired names for the commonly used con-
stants by using the ‘#define’ pre-processor directive. Let us look
at the syntax of it:
Here, the ‘NI’ and ‘NEW’ constants are defined. After defining
these constants, we can use these in the remaining code just like
any other regular constants.
#include <iostream.h>
#define NI 1.12345
32 FAST TRACK
C++
BASICS OF C++ III
int main ()
{
double r=5.0; // This variable
is created for radius
double circle;
circle = 2 * NI * r;
cout << circle;
cout << NEW;
return 0;
}
11.1234
The output of this program will be as follows:
#include <iostream.h>
#include <limits.h>
int main()
{
cout << “The minimum signed character: “ <<
SCHAR_MIN << “\n”;
cout << “The maximum signed character: “ <<
SCHAR_MAX << “\n”;
FAST TRACK 33
III BASICS OF C++
C++
library.
34 FAST TRACK
C++
BASICS OF C++ III
3.5 Operators
x=10;
In this case, ‘10’ is the integer value. The part on the left of the
Assignment Operator is the ‘lvalue’ or left value and the right
part of the Assignment Operator is the ‘rvalue’ or the right value.
Example:
int main ()
{
int x, y; // x:?, y:?
x = 10; // x:10, y:?
y = 4; // x:10, y:4
x = y; // x:4, y:4
y = 7; // x:4, y:7
FAST TRACK 35
III BASICS OF C++
C++
x:4 y:7
In the above program, two variables ‘x’ and ‘y’ are declared.
● Arithmetic operators:
There are five Arithmetical operators in C++:
+
Arithmetic Operators Function the Operators
-
addition
*
subtraction
/
multiplication
%
division
modulo
● Compound assignment :
follows: +=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=.
Symbols that are regarded as Compound assignments and are as
Example:
#include <iostream.h>
int main ()
{
int x, y=4;
x = y;
36 FAST TRACK
C++
BASICS OF C++ III
==
Operators Function of the Operator
!=
Equal to
>
Not equal to
<
Greater than
>=
Less than
<=
Greater than or equal to
Less than or equal to
● Logical operators:
There are three types of Logical Operators: ‘!’, ‘&&’ and ‘II’. We use
‘!’ in order to perform the ‘NOT’ Boolean operation. ‘&&’ (AND) and
the ‘II’ (OR) operators are used to evaluate two expressions in
order to get a single result.
FAST TRACK 37
III BASICS OF C++
C++
● Conditional operator
The symbol (?) is used as the Conditional operator. Look at the syn-
tax of the Conditional Operator:
is executed.
Example:
#include <iostream.h>
int main ()
{
int x,y,z;
x=2;
y=7;
z = (x>y) ? x : y;
cout << z;
return 0;
38 FAST TRACK
C++
BASICS OF C++ III
7
Three variables of integer type are declared in the first line of
the program above. Next, the value ‘2’ is assigned to ‘x’ and ‘7’ is
assigned to ‘y’. Further, a conditional operator is used. If the value
of ‘x’ is greater than that of ‘y’, then ‘x’ is assigned to ‘z’, else ‘y’
is assigned to ‘z’. Here, the value of ‘x’ is not greater than that of
‘y’. Therefore, the value of ‘y’ (7) is assigned to ‘z’. Finally, the
value of ‘z’ is displayed on the screen as seen above.
● Comma operator
The comma (,) is regarded as the Comma Operator and is used to
separate two expressions.
Example:
x = (y=3, y+2);
In the above line, ‘x’ and ‘y’ are two variables. Here, y=3 and
y+2 are separated by a Comma Operator.
~, <<, >>.
These are used to modify variables that can consider bit pat-
terns and can represent the values stored by them.
& AND
Operator asm equivalent Description of the Operator
| OR
Bitwise AND
^ XOR
Bitwise Inclusive OR
~ NOT
Bitwise Exclusive OR
<< SHL
Unary complement (bit inversion)
Shift Left
FAST TRACK 39
III BASICS OF C++
C++
x = sizeof (char);
Example:
● Precedence of operators:
While writing a complex expression involving multiple operands,
we may encounter difficulties in deciding the sequence of
operands in the preferred order.
+ -
indirection and reference Right-to-left
(type)
unary sign operator Right-to-left
.* ->*
type casting Right-to-left
* / %
pointer-to-member Left-to-right
+ -
multiplicative Left-to-right
<< >>
additive Left-to-right
== !=
relational Left-to-right
&
equality Left-to-right
^
bitwise AND Left-to-right
|
bitwise XOR Left-to-right
&&
bitwise OR Left-to-right
logical AND Left-to-right
40 FAST TRACK
C++
BASICS OF C++ III
||
?:
logical OR Left-to-right
= *= /= %= += -= >>= <<=
conditional Right-to-left
inserting the >> sign on the ‘cin’ stream. After the operator, a
The keyboard is the standard input device, and is handled by
variable is inserted and this variable can store the data that is later
extracted from the stream.
Example:
#include <iostream.h>
int main ()
{
int i;
FAST TRACK 41
III BASICS OF C++
C++
42 FAST TRACK
C++
CONTROL STRUCTURES IV
Control Structures
n previous chapters, we have seen that a program is a set of
4.1 Branching
if(condition)
statement;
if(n>10)
cout<<”Value of n =”<<n;
In the above code, if the value of the variable ‘n’ is greater than
10, then the value of ‘n’ will be displayed on the screen.
FAST TRACK 43
IV CONTROL STRUCTURES
C++
if(condition)
{
statement 1;
statement 2;
---------------;
statement n;
}
Here ‘n’ represents the number of statements. You can also rep-
resent this in the following way:
if(n>10)
{
cout<<”Value of n=”;
cout<<n;
}
if(condition)
statement;
else
statement;
if(a>b)
cout<<”a is greater than b”;
44 FAST TRACK
C++
CONTROL STRUCTURES IV
else
cout<<”b is greater than a”;
if(condition)
{
statement 1;
statement 2;
---------------;
statement n;
}
else
{
statement 1;
statement 2;
---------------;
statement n;
}
if(a>b)
{
cout<<”the value of a is greater than b”;
cout<<”the value is=”<<a;
}
else
{
cout<<”the value of b is greater than a”;
cout<<”the value is=”<<b;
FAST TRACK 45
IV CONTROL STRUCTURES
C++
One can also use the ‘if’ statement within another ‘if’ state-
ment or within an ‘else’ statement. This is known as ‘nested if’
concept. For example, if we want to find out the greatest out of
three numbers stored in three variables, the code will be as follows:
if(a>b)
{
if(a>c)
{
cout<<”the greatest number is=”;
cout<<a;
}
else
{
cout<<”the greatest number is=”;
cout<<c;
}
}
else
{
if(b>c)
{
cout<<”the greatest number is=”;
cout<<b;
}
else
{
cout<<”the greatest number is=”;
cout<<c;
}
}
46 FAST TRACK
C++
CONTROL STRUCTURES IV
Program 1:
The following program will accept any year i.e. an integer value
from the user, and checks whether the year is a leap year or not.
Go through the program and its explanation carefully.
#include<iostream.h>
int main()
{
int year;
cout<<”Please enter any year of you choice=>”;
cin>>year;
if(year%100==0)
{
if(year%400==0)
cout<<”You have entered “<<year<<” and this is
FAST TRACK 47
IV CONTROL STRUCTURES
C++
a leap year”;
else
cout<<”You have entered “<<year<<” and this is
not a leap year”;
}
else
{
if(year%4==0)
cout<<”You have entered “<<year<<” and this is
a leap year”;
else
cout<<”You have entered “<<year<<” and this is
not a leap year”;
}
}
In the above program, the year i.e. the integer value is accept-
ed and stored in an integer variable. The ‘if’ statement checks
whether the value is divisible by 100. If the condition returns
true, then the second ‘if’ statement checks whether the value is
divisible by 400. If this condition is also true, then the given
value i.e. the year will be a leap year and a message is displayed
with the value entered by the user. If the second ‘if’ statement
returns false, then the year will not be a leap year and a corre-
sponding message is displayed along with the value of the year
to show the result. Now if the first ‘if’ statement returns false,
i.e. if the value is not divisible by 100, then the control moves to
the ‘else’ part that checks whether the value is divisible by 400
or not by the second ‘if’ statement. If this holds true, then the
48 FAST TRACK
C++
CONTROL STRUCTURES IV
switch(expression)
statement is demonstrated below:
{
case 1:
statement 1;
statement 2;
--------------- ;
statement n;
break;
case 2:
statement 1;
statement 2;
--------------- ;
statement n;
break;
case n:
statement 1;
statement 2;
--------------- ;
statement n;
break;
default:
statement 1;
statement 2;
--------------- ;
FAST TRACK 49
IV CONTROL STRUCTURES
C++
statement n;
}
Here, ‘n’ is a positive integer. Any case from ‘1’ to ‘n’ is execut-
ed depending on the expression’s value. If there is no such value
of expression that satisfies any case, then default statement(s) are
executed. There is a slight difference in constructing blocks in an
# include<iostream.h>
int main()
{
int a;
cout<<”Enter your Choice=>”;
cin>>a;
switch(a)
{
case 1:
cout<<”You are in block 1”;
cout<<”\nyour choice is “<<a;
case 2:
cout<<” You are in block 2”;
cout<<”\nyour choice is “<<a;
break;
case 3:
cout<<” You are in block 3”;
cout<<”\nyour choice is “<<a;
break;
default:
cout<<”You are in block default”;
cout<<”\nyour choice is “<<a;
}
}
50 FAST TRACK
C++
CONTROL STRUCTURES IV
or,
Program 2:
Now we are going to find out the grade of a student on the fol-
lowing conditions:
Marks Grade
FAST TRACK 51
IV CONTROL STRUCTURES
C++
=100 A
>=80 B
>=60 C
>=40 D
>=20 E
>20 F
# include<iostream.h>
int main()
{
int a,b;
cout<<”Enter your marks=>”;
cin>>a;
b=a/20;
switch(b)
{
case 5:
cout<<”You have obtained “<<a<<” marks”;
cout<<”\nYour grade is A”;
break;
case 4:
cout<<”You have obtained “<<a<<” marks”;
cout<<”\nYour grade is B”;
break;
case 3:
cout<<”You have obtained “<<a<<” marks”;
cout<<”\nYour grade is C”;
break;
case 2:
cout<<”You have obtained “<<a<<” marks”;
cout<<”\nYour grade is D”;
break;
52 FAST TRACK
C++
CONTROL STRUCTURES IV
case 1:
cout<<”You have obtained “<<a<<” marks”;
cout<<”\nYour grade is E”;
break;
default:
cout<<”You have obtained “<<a<<” marks”;
cout<<”\nyour grade is F”;
}
}
4.2 Looping
true, the control enters the loop once again. The do-while state-
ment(s) while in the looping block. When the condition returns
FAST TRACK 53
IV CONTROL STRUCTURES
C++
do
The syntax of do-while statement is as follows:
{
statement 1;
statement 2;
-------------- ;
statement n;
} while(condition);
Here, n is a positive integer. A single statement can also be used
within a loop, and the braces are not mandatory. Now let us see
how the loop works. In an exit control loop, the body of the loop
executes at least once irrespective of the condition. After execu-
tion, the condition is checked. If it holds true, then the body of the
loop is executed again. This process continues till the condition
#include<iostream.h>
returns false. For example,
int main()
{
int roll;
char name[30];
float marks;
char ch;
do
{
cout<<”Enter your roll no.=>”;
cin>>roll;
cout<<”Enter your name=>”;
cin>>name;
cout<<”Enter your marks=>”;
cin>>marks;
cout<<”\nYour name is “<<name;
cout<<”\nYour roll no. is “<<roll;
cout<<”\nYour marks is “<<marks;
54 FAST TRACK
C++
CONTROL STRUCTURES IV
If the user enters ‘y’, then the condition holds true, and the
body of the loop is executed once more. That is, it again accepts and
displays the values of roll no., name and marks. This process con-
tinues until the user enters any character other than ‘y’ (say ‘n’).
while(condition)
{
statement 1;
FAST TRACK 55
IV CONTROL STRUCTURES
C++
statement 2;
-------------- ;
statement n;
}
In this kind of loop, first the condition is checked. If the con-
dition holds true, then the body of the loop is executed. After exe-
cution, the condition is checked and executes depending on the
return value of the condition. This process continues till the con-
dition returns false.
Program 4
Now if we want to display the first 10 integers on screen, the pro-
gram will be as follows
#include<iostream.h>
int main()
{
int x=1;
while(x<=10)
{
cout<<”\t”<<x;
x++;
}
}
1 2 3 4 5 6 7 8 9 10
The output of the above program will be
56 FAST TRACK
C++
CONTROL STRUCTURES IV
while(condition)
{
statement 1;
statement 2;
-------------- ;
if(condition)
{
statement 3;
------------ ;
continue;
}
statement 4;
------------- ;
}
FAST TRACK 57
IV CONTROL STRUCTURES
C++
Program 5
#include<iostream.h>
int main()
{
int x=1;
while(x<=10)
{
if(x==7)
{
cout<<”\n\tWe skipped a number\n”;
x=x+1;
continue;
}
cout<<”\t”<<x;
x=x+1;
}
}
1 2 3 4 5 6
We skipped a number
8 9 10
Next, the value of ‘x’ is increased by ‘1’ and reaches the ‘continue’
statement. Therefore, the remaining statements in the loop are
not executed, and the condition for the ‘while’ statement is
checked. Since the value of ‘x’ is now 8, the body of the loop is exe-
cuted, thereby displaying the numbers from 8 to 10. The number
7 is not displayed because of the ‘continue’ statement.
58 FAST TRACK
C++
CONTROL STRUCTURES IV
Program 6
#include<iostream.h>
int main()
{
int x=1;
while(x<=10)
{
if(x==6)
{
cout<<”\nExecution of loop ends here”;
break;
}
cout<<x<<”\t”;
x=x+1;
}
}
12 3 4 5
Execution of loop ends here
ment is reached, and the control leaves the loop without checking
the condition.
FAST TRACK 59
IV CONTROL STRUCTURES
C++
Program 7
The following program accepts a number from the user. If the user
enters an even number, it stops execution.
#include<iostream.h>
int main()
{
int x;
char check=’y’;
while(check==’y’)
{
cout<<”Execution will stop if you enter even
number”;
cout<<”\nEnter a number=>”;
cin>>x;
if(x%2==0)
{
cout<<”\nyou have entered an even number”;
check=’n’;
}
}
}
60 FAST TRACK
C++
CONTROL STRUCTURES IV
for(initialization;condition;increment or decre-
ment)
{
statement 1;
statement 2;
-------------- ;
statement n;
}
FAST TRACK 61
IV CONTROL STRUCTURES
C++
#include<iostream.h>
Program 8
int main()
{
int x;
for(x=1;x<=10;x++)
cout<<x<<”\t”;
}
1 2 3 4 5 6 7 8 9 10
Program 9
This program finds the factorial of a number.
#include<iostream.h>
int main()
{
int x,y,fact;
cout<<”Enter a number=>”;
cin>>x;
fact=1;
for(y=1;y<=x;y++)
{
fact=fact*y;
}
cout<<”\nFactorial of “<<x<<” is “<<fact;
}
62 FAST TRACK
C++
CONTROL STRUCTURES IV
In the above program, there are three integer variables ‘x’, ‘y’
and ‘fact’. The number entered by the user is accepted and stored
in the variable ‘x’. The program calculates the factorial of the
value of ‘x’. Assuming the user entered the value ‘3’. The variable
‘fact’ is then initialized by ‘1’. Next, the ‘for’ loop starts. Here,
the variable ‘y’ is initialized by ‘1’. As the value of ‘y’ is now less
than the value of ‘x’, the loop block is executed. Now the value of
‘fact’ is 1. The value of ‘y’ is now increased by ‘1’. The condition
is then checked to verify whether it holds true. After execution of
the body of the loop, the value of ‘fact’ will be 2, and ‘y’ is again
increased by ‘1’. The loop is executed as mentioned above. The
value of ‘fact’ will now be ‘6’, and the value of ‘y’ will be ‘4’. This
time, the condition holds false, and the statement after the loop is
executed. The output on the screen is:
Factorial of 3 is 6.
Note:
FAST TRACK 63
C++
FUNCTIONS V
Functions
5.1 Main Function
int main();
lowing prototypes. These are as follows:
int main()
{
…… statements ………………
……….statements…………
return 0;
FAST TRACK 65
V FUNCTIONS
C++
66 FAST TRACK
C++
FUNCTIONS V
Here, type is the data type specifier that specifies the type of
data returned by the function. name is the identifier that mainly
calls the function. The third and the most important factor is the
parameter. Each parameter passed, consists of a data type specifi-
er followed by an identifier. The parameter also allows arguments
to pass to that particular function when it is called at a certain
phase in the program. Parameters passed must always be separat-
ed by commas.
// function example
Program1
FAST TRACK 67
V FUNCTIONS
C++
int m;
m = add(10,9); // the function add is called in
the main method
cout << "The result is " <<m;
return 0;
}
Output: The result is 19
able called m is declared of the type int. The next line of the
Here, in the main function of the above program, first a vari-
this case, since the function add is called by the variable m in the
that called the function and also returns the value passed by it. In
#include <iostream.h>
Program2
68 FAST TRACK
C++
FUNCTIONS V
int main ()
{
int x=5, y=3, v;
v = sub(7,2);
cout << "The first result is " << v << '\n';
cout << "The second result is " << sub(7,2) <<
'\n';
cout << "The third result is " << sub(x,y) <<
'\n';
v= 4 + sub(x,y);
cout << "The fourth result is " <<v << '\n';
return 0;
}
FAST TRACK 69
V FUNCTIONS
C++
and y and the value returned by the function sub will be 2 in this
case is displayed. In the next line the function sub is again called
by the variables x and y. This time the return value is stored in the
variable v after adding 4 to it. So the value of v will be 6 and is dis-
played by the next line.
#include <iostream.h>
void duplet(int& m, int& n, int& o)
{
m*=2;
n*=2;
o*=2;
}
int main ()
{
int x=2, y=7, z=9;
70 FAST TRACK
C++
FUNCTIONS V
#include <iostream.h>
void duplet(int* m, int* n, int* o)
{
*m*=2;
*n*=2;
*o*=2;
}
int main ()
{
int x=2, y=7, z=9;
duplet (&x, &y, &z);
cout << "x=" << x << ", y=" << y << ", z="
<< z;
return 0;
}
FAST TRACK 71
V FUNCTIONS
C++
if (x<y)
return x;
else
return y;
}
... }
72 FAST TRACK
C++
FUNCTIONS V
Here, type is the data type of the inline function, while name
refers to the name of that particular inline function.
For example consider the following:
return(a*b);
}
Example 1
#include <iostream.h>
------------------------
FAST TRACK 73
V FUNCTIONS
C++
return 0;
}
Example 2
#include <iostream.h>
int vol (int); // first function,
with int as parameter type
double vol(double, int); // second function
with int and double as parameter type
long vol(long, int, int) // third function
with long,int and int as parameter
int main()
{
cout << vol(20) <<"\n";
cout << vol(3.5,6) <<"\n";
cout << vol(150l,50,45) <<"\n";
return 0;
}
74 FAST TRACK
C++
FUNCTIONS V
8000
231.525
337500
tion vol is declared and defined thrice with three different types
This is an example of an overloaded function. Here the func-
first function deals with the volume of a cube with side x. The sec-
formed, although the name of the function remains the same. The
FAST TRACK 75
C++
CLASSES AND OBJECTS VI
class class_name {
A class is declared as follows:
access_specifier_1:
member 1;
access_specifier_2:
member_2;
} object_names;
FAST TRACK 77
VI CLASSES AND OBJECTS
C++
as follows:
Class_name object_name;
class QRect
{
int m,n;
public:
void setter(int, int);
int area(void); }rect;
#include <iostream.h>
Program 1
class Calculation {
int x, y;
78 FAST TRACK
C++
CLASSES AND OBJECTS VI
public:
void set_values (int,int);
int area () {return (x*y);}
};
int main () {
Calculation r1, r2;
r1.set_values (6,7);
r2.set_values (8,8);
cout << “r1 area: “ << r1.area() << endl;
cout << “r2.area: “ << r2.area() << endl;
return 0;
}
r1 area: 42
r2.area: 64
// classes example
Program 2
#include <iostream.h>
class C1{
int x, y;
FAST TRACK 79
VI CLASSES AND OBJECTS
C++
public:
void s1(int,int);
int area () {return (x*y);}
};
void C1::s1(int a, int b) {
x = a;
y = b;
}
int main () {
C1 r5;
r5.s1(6,5);
cout << “area: “ << r5.area();
return 0;
}
area: 30
that is declared within the class definition, has only its proto-
type declared within the class itself. Similarly, the function area
80 FAST TRACK
C++
CLASSES AND OBJECTS VI
ment declaration)
{
function body
}
FAST TRACK 81
VI CLASSES AND OBJECTS
C++
#include<iostream.h>
class i1
{
int number;
float cost;
public:
void get_value(int x, float y);
void put_value (void)
{
cout<< “number :” <<number<<”\n”;
cout <<”cost:” << cost <<”\n”;
}
};
int main()
{
i1 i2;
cout <<”\n object i2 “<<”\n”;
i2.get_value(378,78.6);
i2.put_value();
i1 i3;
cout <<”\n object i3 “<<”\n”;
i3.get_value(37,8.6);
82 FAST TRACK
C++
CLASSES AND OBJECTS VI
i3.put_value();
return 0;
}
object i2
number: 378
cost :78.6
object i3
number: 37
cost:8.6
and the put_value. Within the class declaration, only the pro-
totype of the function get_value is declared. This function is
then defined outside the class and provides value to both the
FAST TRACK 83
VI CLASSES AND OBJECTS
C++
#include<iostream.h>
// A program showing nesting of member function.
class s1
{
int m,o;
public:
void i1(void);
void d1(void);
int l1(void);
};
int s1 :: l1(void)
{
if(m>= o)
return(m);
else
return(o);
}
void s1 :: i1(void)
{
cout<<”input values of m and o”<<”\n”;
cin>>m>>o;
}
void s1 :: d1(void)
{
cout << “largest value= “ <<l1()<<”\n”; // the
member function l1() is called
}
84 FAST TRACK
C++
CLASSES AND OBJECTS VI
int main()
{
s1 s2;
s2.i1();
s2.d1();
return 0;
}
largest value=78
these are i1, d1 and l1, respectively. The next part of the pro-
other public member functions are declared within the class and
gram defines these functions one after the other. The function l1
deals with an if statement that checks which is greater among
the two variables. The function i1 helps to take input values for
these variables. It is to be noted that when the function d1 is
defined, it calls the member function l1, a case of nesting of
member functions.
FAST TRACK 85
VI CLASSES AND OBJECTS
C++
class-name :: function-name
be used instead of its objects:
#include <iostream.h>
class t1
{
int x;
static int y; // This is a static member vari-
able
public:
void set(void)
{
x= ++y;
}
void show(void)
{
cout<< “object number: “ <<x <<”\n”;
}
86 FAST TRACK
C++
CLASSES AND OBJECTS VI
int t1 :: y;
int main()
{
t1 m1,m2;
m1.set();
m2.set();
t1 :: s1();
t1 m3;
m3.set();
m1.show();
m2.show();
m3.show();
return 0;
count: 2
object number: 1
object number: 2
object number: 3
FAST TRACK 87
VI CLASSES AND OBJECTS
C++
tains the count of the number of objects that is created. The show()
statement x = ++y;
function displays the code number for each object. Consider the
class MN
{
………………….
……………………..
public:
……………………..
………………………..
friend void pqr(void)
};
features as follows:
88 FAST TRACK
C++
CLASSES AND OBJECTS VI
# include <iostream.h>
class s1
{
int a;
int b;
public:
void set() { a=50; b=40;}
friend float m1(s1 s);
};
float m1(s1 s)
{
return float(s.a + s.b)/2.0;
}
int main()
{
s1 k;
k.set();
cout<<” Mean value = “ <<m1(k) <<”\n”;
return 0;
}
Mean value = 45
The output of this program is:
FAST TRACK 89
VI CLASSES AND OBJECTS
C++
# include<iostream.h>
class MN1;
class MN2
{
int x;
public:
void set(int i) {x=i;}
friend void m1(MN2,MN1);
};
class MN1
{
int a;
public:
void set(int i) {a=i;}
friend void m1(MN2,MN1);
};
void m1(MN2 m, MN1 n) // The friend function m1
is defined
{
if(m.x >= n.a)
cout << m.x;
else
cout <<n.a;
}
int main()
{
MN1 mn1;
mn1.set(15);
MN2 mn2;
90 FAST TRACK
C++
CLASSES AND OBJECTS VI
mn2.set(25);
m1(mn2,mn1);
return 0;
}
25
Here, the function m1() has arguments from both the classes
MN2 and MN1. When the function m1 is declared as a friend func-
tion in the class MN2 for the first time, the compiler does not
acknowledge the presence of the class MN1, unless we declare its
name at the beginning of the program as class MN1; This is
known as the ‘forward declaration’.
FAST TRACK 91
CONSTRUCTORS AND
C++ DESTRUCTORS VII
Constructors And
Destructors
7.1 Introduction
Member variables can be initialised while creating the objects by
using constructors. We can also destroy the objects when they are
not required using destructors.
FAST TRACK 93
CONSTRUCTORS AND
VII DESTRUCTORS C++
7.2 Constructors
class dealer
Syntax:
{
private:
int person_identity ;
float daily_sales ;
public:
dealer() //default constructor
{
person_identity = 0 ;
daily_sales = 0.00 ;
}
};
class integer
94 FAST TRACK
CONSTRUCTORS AND
C++ DESTRUCTORS VII
{
Int x, y;
Public:
Integer(void) ; //here
the constructor is declared
………
………
} ;
integer :: integer(void) //here
the constructor is defined
{
x = 0; y = 0;
}
// Naked pointers
FAST TRACK 95
CONSTRUCTORS AND
VII DESTRUCTORS C++
#include <fstream.h>
ofstream out("nudep.out");
class Rat {
public:
Rat() { cout << "Rat()" << endl; }
~Rat() { cout << "~Rat()" << endl; }
};
class Frog {
public:
void* operator new(size_t sz) {
cout << "allocating a Frog" << endl;
throw int(47);
}
void operator delete(void* p) {
cout << "deallocating a Frog" << endl;
::delete p;
}
};
class UseResources {
Rat* bp;
Frog* op;
public:
UseResources(int count = 1) {
cout << "UseResources()" << endl;
bp = new Rat[count];
op = new Frog;
}
~UseResources() {
cout << "~UseResources()" << endl;
delete []bp; // Array delete
delete op;
}
};
int main() {
try {
UseResources ur(3);
96 FAST TRACK
CONSTRUCTORS AND
C++ DESTRUCTORS VII
} catch(int) {
cout << "inside handler" << endl;
}
} ///:~
UseResources()
The output of this program is:
Rat()
Rat()
Rat()
allocating a Frog
inside handler
ished. It indicates that the Cat object was created successfully and
was not destroyed.
FAST TRACK 97
CONSTRUCTORS AND
VII DESTRUCTORS C++
#include <iostream.h>
class Square
{
private:
float span ;
float breath ;
public:
S q u a r e ( )
//this is the Default Constructor, without any argu-
ment
{ }
Square(float I, float b)
//this is the Constructor with two argument
{
span =I;
breath = b ;
}
void Insert_Ib(void)
{
cout << "\n\t Insert the span of the
Square: " ;
cin >> span ;
cout << "\t Insert
the breath of the Square: " ;
cin >> breath ;
}
void View_area(void)
{
cout << "\n\t The area of the Square = "
<< span*breath ;
}
};
//this is the end of the class definitions
void main(void)
{
98 FAST TRACK
CONSTRUCTORS AND
C++ DESTRUCTORS VII
Square q1 ;
//here the first Constructor without any argument
is invoked
cout << "\n First Square----------'\n"
;
q1.Insert_Ib() ;
q1.View_area() ;
cout << "\n\n Second Square---------
'\n" ;
Square q2 (5.6, 3.5) ;
//here the second Constructor with two
arguments is invoked
q2.View_area() ;
}
First Square---------'
Second Square-------'
The area of the Square = 19.6
FAST TRACK 99
CONSTRUCTORS AND
VII DESTRUCTORS C++
#include <iostream.h>
class Model
{
private:
int x,y;
public:
Model(int m, int n) //this is
the constructor with two argument
{
x=m;
y=n;
cout<<"\nHere the Parameterized con-
structor is working\n";
}
Model(Model &p) //copy Constructor
{
y=p.y;
x=p.x;
cout<<"\nHere the Copy constructor is
working\n";
}
void publish()
{
cout <<x<<"\n"<<y;
} //End of the
class definition
};
void main()
{
Model m1(53,63) ; //Invokes
the constructor
Model m2(m1) ;
//Invokes the copy constructor
m2.publish() ;
}
#include <iostream.h>
#include <string.h>
class S1
{
char *z1;
int l1;
public:
S1() //this is the con-
structor-1
{
l1 = 0;
z1 = new char[l1 +1];
}
S1(char *x) //constructor-2
{
l1 = strlen(x);
z1 = new char[l1 +1]; //one addi-
tional
//character
for \0
strcpy(z1, x);
}
void display(void)
{cout <<z1 << "\n";}
void include(S1 &m, S1 &n);
};
void S1 :: include(S1 &m, S1 &n)
{
l1 = m.l1 +n.l1;
delete z1;
z1 = new char[l1+1]; //dynamic
allocation
strcpy(z1, m.z1);
strcat(z1, n.z1);
};
int main()
{
char *initial = "Jack ";
S1 naming1(initial), naming2("Ram
"),naming3("Raj"),t1,t2;
t1.include(naming1,naming2);
t2.include(t1, naming3);
naming1.display();
naming2.display();
naming3.display();
t1.display();
t2.display();
return 0;
}
Jack
Ram
Raj
Jack Ram
Jack Ram Raj
#include <iostream.h>
Example:
class matrix
{
int **q; //this is the
pointer to matrix
int z1,z2; //these are the dimensions
public:
matrix(int v, int u);
void getting_element(int a, int b, int
cost)
{q[a][b]=cost;}
int & insert_element(int a, int b)
{return q[a][b];}
};
matrix :: matrix(int v, int u)
{
int a;
z1=v;
z2=u;
q= new int *[z1]; //Here the
an array pointer is created
for (a = 0;a<z1;a++)
q[a] = new int[z2]; //Here space
for each row is created
}
int main()
{
int l, p;
for(a=0;a<l;a++)
{
for(b=0;b<p;b++)
{
cin>>cost;
A.getting_element(a,b,cost);
}
}
cout<<"\n";
cout<<A.insert_element(2,3);
return 0;
}
11 22 33 44
55 66 77 88
99 111 222 333
333
7.5 Destructors
performer::~performer() {
potency = 0;
nimbleness = 0;
fitness = 0;
}
Consider the following example of both constructor and
destructor:
Example:
#include <iostream.h>
class Plant {
int tallness;
public:
Plant(int initialTallness); // a Constructor is
inserted here
~Plant(); // a Destructor appears with a tilde
sign
void growth(int years);
void copysize();
};
Plant::Plant(int initialTallness) {
tallness = initialTallness;
}
Plant::~Plant() {
cout << "inside Plant destructor" << endl;
copysize();
}
void Plant::growth(int years) {
tallness += years;
}
void Plant::copysize() {
cout << "Plant tallness is " << tallness << endl;
}
int main() {
cout << "before opening brace" << endl;
{
Plant t(12);
cout << "after Plant creation" << endl;
t.copysize();
t.growth(4);
cout << "before closing brace" << endl;
}
cout << "after closing brace" << endl;
} ///:~
#include <iostream.h>
class S1
{
private:
int m,n;
public:
S1(int x, int y) //this is the con-
structor with two arguments
{
m=x;
n=y;
cout<<"\nConstructor in work\n";
}
void print()
{
cout<<"\nThe object value of S1
class\n";
Constructor in work
The output of this program is:
Compound Data
Types
8.1 Arrays
rrays are defined as a series of elements of the same type,
If we want to store six values of the type integer, but don't want
to declare a variable with a different identifier for each of them,
we can do it by using arrays.
Integer
Here, the array Jim is of type integer that contains six inte-
int Jim[6];
name [index]
want to store the value 60 in the third element of the array Jim,
has six elements and each of those elements is of type int. If we
Jim[2] = 60;
x = Jim[2];
Jim[0] = x;
Jim[a] = 7;
b = Jim [a+2];
// arrays example
#include <iostream.h>
int Jim[] = {16, 223, 77, 401, 12}; // an array Jim is declared and
values are assigned to its elements.
int x, res=0;
int main ()
{
for ( x=0 ; x<5 ; x++ )
{
res += Jim[x]; // implies res= res+Jim[x]
}
cout << res;
return 0;
}
0 1 2 3
0
Jim
{ 1
Multidimensional arrays
A multidimensional array is an "array of arrays". This can be rep-
resented as follows:
// arrays as parameters
#include <iostream.h>
15 22 32
21 41 61 81 100
passed to the function. The for loop helps print out the array.
This parameter is included to determine the length of each array
Within the main function, two arrays are declared - first[] and
sec[] and values are assigned to their elements.
ment,
char x1[32];
1. Normal Method
(char f1[]={'I','n','d','i','a','\0'};)
2. By using string literals
(char f1[]= "India";)
type char. Out of the six characters, five are for the word "India",
In both cases, the array f1[] is declared with six elements of
while the last null character is for specifying the end of the
sequence. In the second case, by using string literals, the null
character ('\0') is automatically inserted at the end.
ple, the extraction and insertion operators cin and cout sup-
treating strings. They can also be used in procedures. For exam-
Hello, Harry
declaration of y1, then \0 will append just after the last entered
ters entered is less than the number of elements specified during
y1 H a r r y /0
8.3 Pointers
a1 = 52;
f1 = a1;
t1 = &a1;
variable t1. This is due to the presence of the address of operator &
that precedes the identifier a1. Thus a pointer may be defined as
a variable that stores the reference to another variable.
type * name;
Here, type refers to the data type of the variable that the
pointer points to. Let us take another example that is shown
below.
int * n1;
char * c1;
float * g1;
// Program 1
// Application of pointers
#include <iostream.h>
int main ()
{
int f1, s1;
int * m1;
m1 = &f1;
*m1 = 56;
m1 = &s1;
*m1 = 78;
cout << "first value is " << f1 << endl;
cout << "second value is " << s1<< endl;
return 0;
}
first value is 56
second value is 78
either f1 or s1, but receive values indirectly with the help of the
are declared. It is to be noted that values are not directly set to the
// Program 2
// Application of pointers
#include <iostream.h>
int main ()
{
int f1 = 5, s1 = 15;
int * p3, * p4;
p3 = &f1; // p3 = address of
f1
p4 = &s1; // p4 = address of
s1
*p3 = 60; // value pointed by p3 =
60
*p4 = *p1; // value pointed by p4 =
value pointed by p3
p3 = p4; // p3 = p4 (value of
pointer is copied)
*p3 = 20; // value pointed by p3
= 20
cout << "first value is " << f1 << endl;
cout << "second value is " << s1 << endl;
return 0;
}
first value is 60
second value is 20
int
int * x; // x is a pointer of type
int
x = n1; //
as follows:
that the value of the pointer x can be changed, while the pointer
will have the same properties. The only difference lies in the fact
int main ()
{
int n1[5]; // an array n1 declared of type
int
int * q; // a pointer declared of
type int
q = n1;
*q = 1;
q++;
*q = 2;
q = &n1[2];
*q = 3;
q = n1+ 3;
*q = 4;
q = n1;
*(q+4) = 5;
for (int x=0; x<5; x++)
cout << n1[x] << ", ";
return 0;
}
1,2,3,4,5
The output of this program is:
Dynamic Memory
its run time. C++ provides two effective operators — new and
Dynamic memory is the memory to be used in a program during
p1 = new type
of using this operator is as follows:
int * b;
b = new int [6];
follows:
typedef char x;
Consider the following statements:
The next important data type that is often used is unions. This
Unions
union union_name {
member_type1 member_name1;
member_type2 member_name2;
member_type3 member_name3;
.
.
} object_names;
union m1 {
char v;
int y;
float z;
} my;
Anonymous Unions
There is also a provision for declaring a union without any name.
This is known as anonymous union declarations. The members of
this union can be accessed directly by using the names of its mem-
First declaration:
bers. Consider the following two structure declarations:
struct {
char t1[15];
char a1[15];
union {
float d1;
int y1;
} p1; // name of the union
} b1;
Second declaration
struct {
char t1[15];
char a1[15];
union {
float d1;
int y1;
}; // union name is missing
} b1;
b1.p1.y1
access it by the statement:
b1.p1.d1
b1.y1
b1.d1
Enumerations enum
An enumeration is a data type that can be given a finite set of
named values, each of which has a meaningful name. It can be
declared as follows:
enum enumeration_name {
value1,
value2,
value3,
.
.
} object_names;
t1 tq;
the following expressions based on it. They are as follows:
tq = tj;
integer value can be specified explicitly for any of the constant val-
ues of an enumerated type.
Notes
......................................................................................................................
......................................................................................................................
......................................................................................................................
......................................................................................................................
......................................................................................................................
......................................................................................................................
......................................................................................................................
......................................................................................................................
......................................................................................................................
......................................................................................................................
......................................................................................................................
......................................................................................................................
......................................................................................................................
......................................................................................................................
......................................................................................................................
......................................................................................................................
......................................................................................................................
......................................................................................................................
......................................................................................................................
......................................................................................................................
......................................................................................................................
......................................................................................................................
......................................................................................................................
......................................................................................................................
......................................................................................................................
......................................................................................................................
......................................................................................................................
......................................................................................................................
......................................................................................................................
......................................................................................................................
......................................................................................................................
......................................................................................................................
......................................................................................................................
......................................................................................................................
......................................................................................................................
Notes
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
....................................................................................................................................
The scope resolution operator (::) in C++ allows the definition of member functions outside the class body, specifying which class a member function belongs to . This practice enhances code organization by separating class interface from implementation, which aids in maintaining large codebases . By defining member functions outside the class, the class declaration remains concise and clearer, making the code more readable . It also supports modularity, where the class interface is exposed while the implementation details are hidden, promoting better encapsulation .
A 'while' loop in C++ continues executing as long as a specified condition is true, with the condition checked before each iteration. The variables involved typically require manual initialization and incrementation within the loop body . In contrast, a 'for' loop integrates initialization, condition checking, and incrementation in its header, executing its body as long as the condition remains true. This structure often results in more concise and readable code when the number of iterations is known in advance .
Constructor initialization in C++ occurs simultaneously with memory allocation and is automatically invoked when creating an instance of a class, ensuring that the object is ready for use immediately upon creation. It involves setting default or specific initial values for the members directly at the time of object creation without requiring explicit reference to member functions . On the other hand, setting values within the class typically requires calling a member function to assign values after the object has been instantiated. This approach separates the object creation and initialization process and may be used to change or update the values at any point during the object's lifecycle . Constructors provide a systematic and consistent way to initialize objects, reducing the chance of errors related to uninitialized data members ."}
Including a function prototype in a C++ program is crucial for ensuring that a function is used with the correct parameters and helps describe the function interface to the compiler by detailing the argument types and return values. This practice enhances parameter type safety by allowing the compiler to check that the function is called with the correct types of arguments, thereby reducing errors related to improper use of function parameters . Function prototyping significantly aids in maintaining type safety, especially in complex programs where functions could be overloaded, as the compiler uses prototypes to select the appropriate overloaded function based on the types of arguments passed during a call .
The 'return' statement in C++ is considered optional specifically in the main() function. By default, main() returns an int, and using 'return 0;' is traditionally included to indicate successful execution, but it is not mandatory in all environments since some compilers automatically generate it. However, for other functions that specify a return type, the return statement is necessary unless the function is of type void. The return statement is typically placed as the last statement in a function to return control and a value to the function caller, and omitting it can lead to compiler warnings or errors .
Static member functions in C++ are associated with the class rather than an instance of the class, meaning they can be called without an object. They can only access static data members or other static member functions within the same class. This makes them useful for operations that are not dependent on object states but shared across all instances of the class, such as utility functions or keeping a count of instances created .
Member function prototypes within a class declare the function's signature, indicating the return type, function name, and parameter types without actual implementation. This allows the class to communicate its interface without exposing the implementation details, enabling the definition elsewhere, potentially in a separate file, which improves organization and separation of interface and implementation .
A 'break' statement immediately terminates the smallest enclosing loop or switch statement, transferring control to the statement immediately following the loop or switch. It is appropriate to use a 'break' statement in situations where a condition is met that requires terminating the loop execution prematurely, such as finding an element in a search algorithm and halting further unnecessary iterations .
A 'continue' statement is used within loops to skip the current iteration when a specified condition is met, effectively ignoring the remaining statements within that loop iteration. After reaching the 'continue' statement, control immediately jumps to the next iteration of the loop, re-evaluating the loop's condition, rather than executing further code inside the current iteration of the loop . For example, in a loop counting from 1 to 10, if a 'continue' statement is used when the variable equals 7, the loop will skip the iteration where the variable is 7 and continue with the next numbers . This ensures that only the specified portions of loop code execute for each iteration where the condition isn't met, allowing selective skipping of code blocks while maintaining the general execution flow of the loop ."}
Function prototyping in C++ is a crucial feature that ensures the proper use of functions by detailing their interface, including the type of arguments and return values. It allows the compiler to ensure that functions are called with the correct parameters and also facilitates the convenient calling of functions without requiring the full function definition at the call point . By verifying argument types and return types, function prototypes increase program reliability by preventing mismatches and potential errors during function calls . This safeguard against improper function usage contributes to the overall robustness and reliability of C++ programs.