You are on page 1of 86

C++ if...else and Nested if...

else
The if, if...else and nested if...else statement are used to make one-time decisions in C++
Programming, that is, to execute some code/s and ignore some code/s depending upon the test
condition. Without decision making, the program runs in similar way every time. Decision making is an
important feature of every programming language using C++ programming. Before you learn decision
making, you should have basic understanding of relational operators.

C++ if Statement
The if statement checks whether the test condition is true or not. If the test condition is true, it
executes the code/s inside the body of if statement. But it the test condition is false, it skips the
code/s inside the body of if statement.

Working of if Statement

The if keyword is followed by test condition inside parenthesis ( ). If the test condition is true,
the codes inside curly bracket is executed but if test condition is false, the codes inside curly
bracket { } is skipped and control of program goes just below the body of if as shown in figure
above.

Flowchart of if
Example 1: C++ if Statement

C++ Program to print integer entered by user only if that number is positive.

#include <iostream>
using namespace std;

int main() {
int number;
cout<< "Enter an integer: ";
cin>> number;

if ( number > 0) { // Checking whether an integer is positive or not.


cout << "You entered a positive integer: "<<number<<endl;
}

cout<<"This statement is always executed because it's outside if


statement.";
return 0;

Output 1

Enter an integer: 5
You entered a positive number: 5
This statement is always executed because it's outside if statement.

Output 2

Enter a number: -5
This statement is always executed because it's outside if statement.

C++ if...else
The if...else executes body of if when the test expression is true and executes the body of
else if test expression is false.

Working of if...else Statement


The if statement checks whether the test expression is true or not. If the test condition is true, it
executes the code/s inside the body of if statement. But it the test condition is false, it executes
the code/s inside the body of else.

Flowchart of if...else

Example 2: C++ if...else Statement

C++ Program to check whether integer entered by user is positive or negative (Considering
0 as positive)

#include <iostream>
using namespace std;

int main() {
int number;
cout<< "Enter an integer: ";
cin>> number;

if ( number >= 0) {
cout << "You entered a positive integer: "<<number<<endl;
}

else {
cout<<"You entered a negative integer: "<<number<<endl;
}

cout<<"This statement is always executed because it's outside if...else


statement.";
return 0;

}
Output
Enter an integer: -4
You entered a negative integer: -4
This statement is always executed because it's outside if...else statement.
C++ Nested if...else
Nested if...else are used if there are more than one test expression.

Syntax of Nested if...else


if (test expression1){
statement/s to be executed if test expression1 is true;
}
else if(test expression2) {
statement/s to be executed if test expression1 is false and 2 is
true;
}
else if (test expression 3) {
statement/s to be executed if text expression1 and 2 are false and 3
is true;
}
.
.
.
else {
statements to be executed if all test expressions are false;
}

The nested if...else statement has more than one test expression. If the first test expression is
true, it executes the code inside the braces{ } just below it. But if the first test expression is false,
it checks the second test expression. If the second test expression is true, if executes the code
inside the braces{ } just below it. This process continues. If all the test expression are false,
code/s inside else is executed and the control of program jumps below the nested if...else

Example 3: C++ Nested if...else Statement

C++ Program to check whether the integer entered by user is positive, negative or zero.

#include <iostream>
using namespace std;

int main() {
int number;
cout<< "Enter an integer: ";
cin>> number;

if ( number > 0) {
cout << "You entered a positive integer: "<<number<<endl;
}
else if (number < 0){
cout<<"You entered a negative integer: "<<number<<endl;
}
else {
cout<<"You entered 0."<<endl;
}

cout<<"This statement is always executed because it's outside nested


if..else statement.";
return 0;
}

Output

Enter an integer: 0
You entered 0.
This statement is always executed because it's outside nested if..else
statement.

Conditional/Ternary Operator ?:
Conditional operators are the peculiar case of if...else statement in C++ Programming.
Consider this if..else statement:

if ( a < b ) {
a = b;
}
else {
a = -b;
}

The above code can be written using conditional operator as:

a = (a < b) ? b : -b;

Both codes above check whether a is less than b or not. If a is less than b, value of b is assigned
to a if not, -b is assigned to a.

C++ for Loop

In computer programming, loop cause a certain piece of program to be executed a certain


number of times.  Consider these scenarios:

 You want to execute some code/s certain number of time.


 You want to execute some code/s certain number of times depending upon input from user.

These types of task can be solved in programming using loops.

There are 3 types of loops in C++ Programming:

 for Loop
 while Loop
 do...while Loop

C++ for Loop Syntax


for(initialization statement; test expression; update statement) {
code/s to be executed;
}
How for loop works in C++ Programming?

The initialization statement is executed only once at the beginning of the for loop. Then the test
expression is checked by the program. If the test expression is false, for loop is terminated. But if
test expression is true then the code/s inside body of for loop is executed and then update
expression is updated. This process repeats until test expression is false.

Flowchart of for Loop in C++

Example 1: C++ for Loop

C++ Program to find factorial of a number (Note: Factorial of positive integer n =


1*2*3*...*n)

#include <iostream>
using namespace std;

int main() {
int i, n, factorial = 1;

cout<<"Enter a positive integer: ";


cin>>n;

for (i = 1; i <= n; ++i) {


factorial *= i; // factorial = factorial * i;
}

cout<< "Factorial of "<<n<<" = "<<factorial;


return 0;
}

Output

Enter a positive integer: 5


Factorial of 5 = 120
In this program, user is asked to enter a positive integer which is stored in variable n (supposed
user entered 5). Here is the working of for loop in this program:

1. Initially, i = 1, test expression is true, factorial becomes 1.


2. Variable i is updated to 2, test expression is true, factorial becomes 2.
3. Variable i is updated to 3, test expression is true, factorial becomes 6.
4. Variable i is updated to 4, test expression is true, factorial becomes 24.
5. Variable i is updated to 5, test expression is true, factorial becomes 120.
6. Variable i is updated to 6, test expression is false, for loop is terminated.

In the above program you can see that, variable i is not used outside for loop. In such case, it is
better to define variable at the time of initialization statement.

for (int i = 0; i <= n, ++i){


... .. ...
}

In the above C++ code, i is local to for loop, that is, you cannot use it outside for loop but
makes program more readable.

C++ while and do...while Loop

In computer programming, loop cause a certain piece of program to be executed a certain


number of times. Consider these scenarios:

 You want to execute some code/s certain number of time.


 You want to execute some code/s certain number of times depending upon input from user.

These types of task can be solved in programming using loops.

There are 3 types of loops in C++ Programming:

 for Loop
 while Loop
 do...while Loop

C++ while Loop


Syntax of while Loop
while (test expression) {
statement/s to be executed.
}

How while loop works in C++ Programming?

The while loop checks whether the test expression is true or not. If it is true, code/s inside the
body of while loop is executed,that is, code/s inside the braces { } are executed. Then again the
test expression is checked whether test expression is true or not. This process continues until the
test expression becomes false.
Flowchart of while Loop in C++

Example 1: C++ while Loop

C++ program to find factorial of a positive integer entered by user. (Factorial of n =


1*2*3...*n)

#include <iostream>
using namespace std;

int main() {
int number, i = 1, factorial = 1;
cout<< "Enter a positive integer: ";
cin >> number;

while ( i <= number) {


factorial *= i; //factorial = factorial * i;
++i;
}

cout<<"Factorial of "<<number<<" = "<<factorial;


return 0;
}

Output

Enter a positive integer: 4


Factorial of 4 = 24

In this program, user is asked to enter a positive integer which is stored in variable number
(supposed user entered 4). Here is the working of while loop in this program:

1. Initially, i = 1, test expression i <= number is true, factorial becomes 1.


2. Variable i is updated to 2, test expression is true, factorial becomes 2.
3. Variable i is updated to 3, test expression is true, factorial becomes 6.
4. Variable i is updated to 4, test expression is true, factorial becomes 24.
5. Variable i is updated to 5, test expression is false and while loop is terminated.

C++ do...while Loop


The do...while Loop is similar to while loop with one very important difference. In while loop,
check expression is checked at first before body of loop but in case of do...while loop, body of
loop is executed first then only test expression is checked. That's why the body of do...while loop
is executed at least once.

Syntax of do...while Loop


do {
statement/s;
}
while (test expression);

How do...while loop works?

The statement/s inside body of loop is executed at least once, that is, the statement/s inside
braces { } is executed at least once. Then the test expression is checked. If the test expression is
true, the body of loop is executed. This process continues until the test expression becomes false.
Since the body of loop is placed before the test expression in do...while loop, the body of
loop is executed at least once.

Example 2: do...while Loop


C++ program to add numbers entered by user until user enters 0.
#include <iostream>
using namespace std;

int main() {
float number, sum = 0.0;

do {
cout<<"Enter a number: ";
cin>>number;
sum += number;
}
while(number != 0.0);
cout<<"Total sum = "<<sum;

return 0;
}
Output
Enter a number: 4.5
Enter a number: 2.34
Enter a number: 5.63
Enter a number: 6.34
Enter a number: 4.53
Enter a number: 5
Enter a number: 0
Total sum = 28.34
C++ break and continue Statement
There are two statements (break; and continue;) built in C++ programming to alter the normal
flow of program.

Loops are used to perform repetitive task until test expression is false but sometimes it is
desirable to skip some statement/s inside loop or terminate the loop immediately with checking
test condition. On these type of scenarios, continue; statement and break; statement is used
respectively. The break; statement is also used to terminate switch statement.

C++ break Statement


The break; statement terminates the loop(for, while and do..while loop) and switch statement
immediately when it appears.

Syntax of break
break;

In real practice, break statement is almost always used inside the body of conditional
statement(if...else) inside the loop.

Working of break Statement


Example 1: C++ break

C++ program to add all number entered by user until user enters 0.

// C++ Program to demonstrate working of break statement

#include <iostream>
using namespace std;
int main() {
float number, sum = 0.0;

while (true) { // test expression is always true


cout<<"Enter a number: ";
cin>>number;

if (number != 0.0) {
sum += number;
}
else {
break; // terminating the loop if number equals to 0.0
}

}
cout<<"Sum = "<<sum;
return 0;
}

Output

Enter a number: 4
Enter a number: 3.4
Enter a number: 6.7
Enter a number: -4.5
Enter a number: 0
Sum = 9.6

In this C++ program, the test expression is always true. The user is asked to enter a number
which is stored in variable number. If the user enters any number other than 0, that number is
added to sum and stored to it and again user is asked to enter another number. When user enters
0, the test expression inside if statement is false and body of else is executed which terminates
the loop. Finally, the sum is displayed.

C++ continue Statement


It is sometimes necessary to skip some statement/s inside the loop. In that case, continue;
statement is used in C++ programming.

Syntax of continue
continue;

In practice, continue; statement is almost always used inside conditional statement.


Working of continue Statement

Example 2: C++ continue

C++ program to display integer from 1 to 10 except 5 and 9.

// C++ Program to demonstrate working of continue statement

#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; ++i) {
if ( i == 6 || i == 9) {
continue;
}
cout<<i<<"\t";
}
return 0;
}

Output

1 2 3 4 7 8 10

In above program, when i is equal to 6 or 9, execution of statement cout<<i<<"\t"; is skipped


inside the loop using continue; statement.
C++ switch Statement

Consider a situation in which, only one block of code needs to be executed among many blocks.
This type of situation can be handled using nested if...else statement but, the better way of
handling this type of problem is using switch...case statement.

Syntax of switch
switch (n) {
case constant1:
code/s to be executed if n equals to constant1;
break;
case constant2:
code/s to be executed if n equals to constant2;
break;
.
.
.
default:
code/s to be executed if n doesn't match to any cases;
}

The value of n is either an integer or a character in above syntax. If the value of n matches
constant in case, the relevant codes are executed and control moves out of the switch statement.
If the n doesn't matches any of the constant in case, then the default statement is executed and
control moves out of switch statement.

Flowchart of switch Statement

Example 1: C++ switch Statement


/* C++ program to demonstrate working of switch Statement */
/* C++ program to built simple calculator using switch Statement */
#include <iostream>
using namespace std;
int main() {
char o;
float num1,num2;
cout<<"Select an operator either + or - or * or / \n";
cin>>o;
cout<<"Enter two operands: ";
cin>>num1>>num2;

switch(o) {
case '+':
cout<<num1<<" + "<<num2<<" = "<<num1+num2;
break;
case '-':
cout<<num1<<" - "<<num2<<" = "<<num1-num2;
break;
case '*':
cout<<num1<<" * "<<num2<<" = "<<num1*num2;
break;
case '/':
cout<<num1<<" / "<<num2<<" = "<<num1/num2;
break;
default:

/* If operator is other than +, -, * or /, error message is shown


*/
printf("Error! operator is not correct");
break;
}

return 0;
}

Output

Select an operator either + or - or * or /


-
Enter two operands: 2.3
4.5
2.3 - 4.5 = -2.2

The break statement at the end of each case cause switch statement to exit. If break statement
is not used, all statements below that case statement are also executed.

C++ goto Statement

In C++ programming, goto statement is used for altering the normal sequence of program
execution by transferring control to some other part of the program.

Syntax of goto Statement


goto label;
... .. ...
... .. ...
... .. ...
label:
statement;
... .. ...

In syntax above, label is an identifier. When goto label; is encountered, the control of
program jumps to label: and executes the code below it.

Example 1: goto Statement


/* C++ program to demonstrate the working of goto statement. */
/* This program calculates the average of numbers entered by user. */
/* If user enters negative number, it ignores that number and
calculates the average of number entered before it.*/

# include <iostream>
using namespace std;
int main() {
float num, average, sum = 0.0;
int i, n;
cout<<"Maximum number of inputs: ";
cin>>n;

for(i=1; i <= n; ++i) {


cout<<"Enter n"<<i<<": ";
cin>>num;

if(num < 0.0) {


goto jump; /* Control of the program moves to jump; */
}
sum += num;
}

jump:
average=sum/(i-1);
cout<<"\nAverage = "<<average;
return 0;
}

Output

Maximum number of inputs: 10


Enter n1: 2.3
Enter n2: 5.6
Enter n3: -5.6

Average = 3.95
You can write any C++ program with use of goto statement and it is generally considered good
idea not to use goto statement.

Reason to Avoid goto Statement

The goto statement gives power to jump to any part of program but, makes the logic of the
program complex and tangled. In modern programming, goto statement is considered a harmful
construct and a bad programming practice.

The goto statement can be replaced in most of C++ program with the use of break and continue
statements.

C++ Functions

In programming, function refers to a segment that groups code to perform a specific task.
Depending on whether a function is predefined or created by programmer; there are two types of
function:

1. Library Function
2. User-defined Function

Library Function
Library functions are the built-in function in C++ programming. Programmer can use library
function by invoking function directly; they don't need to write it themselves.

Example 1: Library Function

# include <iostream>
#include <cmath>

using namespace std;

int main() {
double number, squareRoot;
cout<<"Enter a number: ";
cin>>number;

/* sqrt() is a library function to calculate square root */


squareRoot = sqrt(number);
cout<<"Square root of "<<number<<" = "<<squareRoot;
return 0;
}

Output

Enter a number: 26
Square root of 26 = 5.09902
In example above, sqrt() library function is invoked to calculate the square root of a number.
Notice code #include <cmath> in the above program. Here, cmath is a header file. The
function definition of sqrt()(body of that function) is written in that file. You can use all
functions defined in cmath when you include the content of file cmath in this program using
#include <cmath> .

Every valid C++ program has at least one function, that is, main() function.

User-defined Function
C++ allows programmer to define their own function. A user-defined function groups code to
perform a specific task and that group of code is given a name(identifier). When that function is
invoked from any part of program, it all executes the codes defined in the body of function.

How user-defined function works in C Programming?

Consider the figure above. When a program begins running, the system calls the main()
function, that is, the system starts executing codes from main() function. When control of
program reaches to function_name() inside main(), the control of program moves to void
function_name(), all codes inside void function_name() is executed and control of program
moves to code right after function_name() inside main() as shown in figure above.

Example 1: Function

C++ program to add two integers. Make a function add() to add integers and display sum
in main() function.

# include <iostream>
using namespace std;

int add(int, int); //Function prototype(declaration)

int main() {
int num1, num2, sum;
cout<<"Enters two numbers to add: ";
cin>>num1>>num2;
sum = add(num1,num2); //Function call
cout<<"Sum = "<<sum;
return 0;
}

int add(int a,int b) { //Function declarator


int add;
add = a+b;
return add; //Return statement
}

Output

Enters two integers: 8


-4
Sum = 4

Function prototype(declaration)

If an user-defined function is defined after main() function, compiler will show error. It is
because compiler is unaware of user-defined function, types of argument passed to function and
return type.

In C++, function prototype is a declaration of function without function body to give compiler
information about user-defined function. Function prototype in above example:

int add(int, int);

You can see that, there is no body of function in prototype. Also there are only return type of
arguments but no arguments. You can also declare function prototype as below but it's not
necessary to write arguments.

int add(int a, int b);

Note: It is not necessary to define prototype if user-defined function exists before main()
function.

Function Call

To execute the codes of function body, the user-defined function needs to be invoked(called). In
the above program, add(num1,num2); inside main() function calls the user-defined function. In
the above program, user-defined function returns an integer which is stored in variable add.

Function Definition

The function itself is referred as function definition. Function definition in the above program:

/* Function definition */

int add(int a,int b) { // Function declarator


int add;
add = a+b;
return add; // Return statement
}

When the function is called, control is transferred to first statement of function body. Then, other
statements in function body are executed sequentially. When all codes inside function definition
is executed, control of program moves to the calling program.

Passing Arguments to Function

In programming, argument(parameter) refers to data this is passed to function(function


definition) while calling function.

In above example, two variables, num1 and num2 are passed to function during function call.
These arguments are known as actual arguments. The value of num1 and num2 are initialized to
variables a and b respectively. These arguments a and b are called formal arguments. This is
demonstrated in figure below:

Notes on passing arguments

 The numbers of actual arguments and formals argument should be same. (Exception: Function
Overloading)
 The type of first actual argument should match the type of first formal argument. Similarly, type
of second actual argument should match the type of second formal argument and so on.
 You may call function without passing any argument. The number(s) of argument passed to a
function depends on how programmer want to solve the problem.
 In above program, both arguments are of int type. But it's not necessary to have both
arguments of same type.
Return Statement

A function can return single value to the calling program using return statement. In the above
program, the value of add is returned from user-defined function to the calling program using
statement below:

return add;

The figure below demonstrates the working of return statement.

In the above program, the value of add inside user-defined function is returned to the calling
function. The value is then stored to a variable sum. Notice that, the variable returned, that is,
add is of type int and also sum is of int type. Also notice that, the return type of a function is
defined in function declarator int add(int a,int b). The int before add(int a,int b)
means that function should return a value of type int. If no value is returned to the calling
function then, void should be used.

C++ User-defined Function Types

For better understanding of arguments and return in functions, user-defined functions can be
categorised as:

 Function with no argument and no return value


 Function with no argument but return value
 Function with argument but no return value
 Function with argument and return value

Consider a situation in which you have to check prime number. This problem is solved below by
making user-defined function in 4 different ways as mentioned above.
Function with no argument and no return value
# include <iostream>
using namespace std;

void prime();

int main() {
prime(); // No argument is passed to prime().
return 0;
}

// Return type of function is void because value is not returned.


void prime() {

int num, i, flag = 0;


printf("Enter a positive integer enter to check: ");
cin>>num;
for(i = 2; i <= num/2; ++i){
if(num%i == 0) {
flag=1;
break;
}
}
if (flag == 1) {
cout<<num<<" is not a prime number.";
}
else {
cout<<num<<" is a prime number.";
}
}

Function with no arguments but return value


#include <iostream>
using namespace std;

int prime();

int main() {
int num, i, flag = 0;
num = prime(); /* No argument is passed to prime() */
for (i = 2; i <= num/2; ++i) {
if (num%i == 0) {
flag = 1;
break;
}
}
if (flag == 1) {
cout<<num<<" is not a prime number.";
}
else {
cout<<num<<" is a prime number.";
}
return 0;
}
// Return type of function is int
int prime() {
int n;
printf("Enter a positive integer to check: ");
cin>>n;
return n;
}

Function with argument but no return value


#include <iostream>
using namespace std;

void prime(int n);

int main() {
int num;
cout<<"Enter a positive integer to check: ";
cin>>num;

prime(num); // Argument num is passed to function.


return 0;
}

// There is no return value to calling function. Hence, return type of


function is void. */
void prime(int n) {
int i, flag = 0;
for (i = 2; i <= n/2; ++i) {
if (n%i == 0) {
flag = 1;
break;
}
}
if (flag == 1) {
cout<<n<<" is not a prime number.";
}
else {
cout<<n<<" is a prime number.";
}
}

Function with arguments and return value.


#include <iostream>
using namespace std;

int prime(int n);

int main() {
int num, flag = 0;
cout<<"Enter positive enter to check: ";
cin>>num;
flag = prime(num); /* Argument num is passed to check() function. */
if(flag == 1)
cout<<num<<" is not a prime number.";
else
cout<<num<<" is a prime number.";
return 0;
}

/* This function returns integer value. */


int prime(int n){
int i;
for(i = 2; i <= n/2; ++i){
if(n%i == 0)
return 1;
}
return 0;
}

All four programs above gives the same output and all are technically correct program. There is
no hard and fast rule on which method should be chosen. The particular method is chosen
depending upon the situation and how a programmer want to solve that problem.

C++ Function Overloading

In C++ programming, two functions can have same identifier(name) if either number of
arguments or type of arguments passed to functions are different. These types of functions
having similar name are called overloaded functions.

/* Example of function overloading */

int test() { }
int test(int a){ }
int test(double a){ }
int test(int a, double b){ }

All 4 functions mentioned above are overloaded function. It should be noticed that, the return
type of all 4 functions is same,i.e, int. Overloaded function may or may not have different
return type but it should have different argument(either type of argument or numbers of
argument passed). Two functions shown below are not overloaded functions because they only
have same number of arguments and arguments in both functions are of type int.

/* Both functions has same number of argument and same type of argument*/
/* Hence, functions mentioned below are not overloaded functions. */
/* Compiler shows error in this case. */

int test(int a){ }


double test(int b){ }

Example 1: Function Overloading


/*Calling overloaded function test() with different argument/s.*/

#include <iostream>
using namespace std;
void test(int);
void test(float);
void test(int, float);
int main() {
int a = 5;
float b = 5.5;

test(a);
test(b);
test(a, b);

return 0;
}

void test(int var) {


cout<<"Integer number: "<<var<<endl;
}

void test(float var){


cout<<"Float number: "<<var<<endl;
}

void test(int var1, float var2) {


cout<<"Integer number: "<<var1;
cout<<" And float number:"<<var2;
}

Output

Integer number: 5
Float number: 5.5
Integer number: 5 And float number: 5.5

In above example, function test() is called with integer argument at first. Then, function
test() is called with floating point argument and finally it is called using two arguments of type
int and float. Although the return type of all these functions is same, that is, void, it's not
mandatory to have same return type for all overloaded functions. This can be demonstrated by
example below.

Example 2: Function Overloading


/* C++ Program to return absolute value of variable types
integer and float using function overloading */

#include <iostream>
using namespace std;

int absolute(int);
float absolute(float);
int main() {
int a = -5;
float b = 5.5;

cout<<"Absolute value of "<<a<<" = "<<absolute(a)<<endl;


cout<<"Absolute value of "<<b<<" = "<<absolute(b);
return 0;
}

int absolute(int var) {


if (var < 0)
var = -var;
return var;
}

float absolute(float var){


if (var < 0.0)
var = -var;
return var;
}

Output

Absolute value of -5 = 5
Absolute value of 5.5 = 5.5

In above example, two functions absolute() are overloaded. Both take single argument but one
takes integer type argument and other takes floating point type argument. Function absolute()
calculates the absolute value of argument passed and returns it.

C++ Default Argument

In C++ programming, you can provide default values for function parameters. The idea behind
default argument is very simple. If a function is called by passing argument/s, those arguments
are used by the function. But if all argument/s are not passed while invoking a function then, the
default value passed to arguments are used. Default value/s are passed to argument/s in function
prototype. Working of default argument is demonstrated in the figure below:
Example: Default Argument

/* C++ Program to demonstrate working of default argument */

#include <iostream>
using namespace std;

void display(char = '*', int = 1);

int main() {
cout<<"No argument passed:\n";
display();

cout<<"\n\nFirst argument passed:\n";


display('#');

cout<<"\n\nBoth argument passed:\n";


display('$', 5);

return 0;
}

void display(char c, int n){


for(int i = 1; i <=n; ++i) {
cout<<c;
}
cout<<endl;
}

Output

No argument passed:
*

First argument passed:


#

Both argument passed:


$$$$$

In the above program, you can see default value passed to arguments(in function prototype). At
first, display() function is called without passing any arguments. In this case, default()
function used both default arguments. Then, the function is called using only first argument. In
this case, function does not use first default value passed. Function uses the actual parameter
passed as first argument and takes default value(second value in function prototype) as it's
second argument. When display() is invoked passing both arguments, default arguments are
not used.

Note: The missing argument must be the last argument of the list, that is, if you are passing
only one argument in the above function, it should be the first argument.

C++ Storage Class

Every variable in C++ has a type which specifies the type of data that can be stored in a variable.
For example: int, float, char etc. Also variables and objects in C++ have another feature
called storage class. Storage class specifiers control two different properties: storage duration
(determines how long a variable can exist) and scope (determines which part of the program can
access it). The variables can be divided into 4 ways depending upon the storage duration and
scope of variables.

 Local variable
 Global variable
 Static local variable
 Register Variable
 Thread Local Storage
Local Variable
A variable defined inside a function(defined inside function body between braces) is a local
variable. Local variables are created when the function containing local variable is called and
destroyed when that function returns. Local variables can only be accessed from inside a
function in which it exists. Consider this example:

#include <iostream>
using namespace std;

void test();

int main() {
int var = 5; // local variable to main()
test();
var1 = 9; // illegal: var1 not visible inside main()
}

void test() {
int var1; // local variable to test()
var1 = 6;
cout<<var; // illegal: var not visible inside test()
}

The variable var cannot be used inside test() and var1 cannot be used inside main() function.

Keyword auto could also be used for defining local variables (it was optional but not necessary)
before as: auto int var; but, after C++11 auto has different meaning and should not be used
for defining local variables as variables defined inside a function is a local variable by default.

Global Variable
If a variable is defined outside any function, then that variable is called a global variable. Any
part of program after global variable declaration can access global variable. If a global variable is
defined at the beginning of the listing, global variable is visible to all functions. Consider this
example:

/* In this example, global variable can be accessed by all functions because


it is defined at the top of the listing.*/

#include <iostream>
using namespace std;
int c = 12;

void test();

int main() {
++;c
cout<<c<<endl; //Output: 13
test();
return 0;
}
void test() {
++c;
cout<<c; //Output: 14
}

In the above program, c is a global variable. This variable is visible to both functions in the
above program.

The memory for global variable is set when program starts and exist until program ends.

Static Local variable

Keyword static is used for specifying static variable. For example:

... .. ...
int main() {
static float a;
... .. ...
}

A static local variable exist only inside a function in which it is declared(similar to local
variable) but the lifetime of static variable starts when the function containing static variable is
called and ends when the program ends. The main difference between local variable and static
variable is that, the value of static variable persist until the program ends. Consider this example:

#include <iostream>
using namespace std;

void test() {
static int var = 0; // var is a static variable;
++var;
cout<<var<<endl;
}
int main() {

test();
test();
return 0;
}

Output

1
2

In the above program, test() function is invoked 3 times. During first call, variable var is
declared as static variable and initialized to 0. Then 1 is added to var which is displayed in the
screen. When the function test() returns, variable var still exist because it is a static variable.
During second function call, no new variable var is created. Only var is increased by 1 and then
displayed to the screen.

Output of above program if var was not specified as static variable


1
1

Register Variable
Keyword register is used for specifying register variables. Register variables are similar to
automatic variable and exists inside that particular function only. If a program encounters
register variable, it stores that variable in processor's register rather than memory if available.
Processor's register is much more faster than memory. This keyword was deprecated in C++11
and should not be used.

Thread Local Storage


Thread-local storage is a mechanism by which variables are allocated such that there is one
instance of the variable per extant thread. Keyword thread_local is used for this purpose.
Learn more about thread local storage.

C++ Recursion

In many programming languages including C++, it is possible to call a function from a same
function. This function is known as recursive function and this programming technique is known
as recursion. 

To understand recursion, you should have knowledge of two important aspects:

 In recursion, a function calls itself but you shouldn't assume these two functions are same
function. They are different functions although they have same name.
 Local variables: Local variables are variables defined inside a function and has scope
only inside that function. In recursion, a function call itself but these two functions are
different functions (You can imagine these functions are function1 and function 2. The
local variables inside function1 and function2 are also different and can only be accessed
within that function.

Consider this example to find factorial of a number using recursion.

Example 1: C++ Recursion


#include <iostream>
using namespace std;

int factorial(int);

int main() {
int n;
cout<<"Enter a number to find factorial: ";
cin>>n;
cout<<"Factorial of "<<n<<" = "<<factorial(n);
return 0;
}
int factorial(int n) {
if (n>1) {
return n*factorial(n-1);
}
else {
return 1;
}
}

Output

Enter a number to find factorial: 4


Factorial of 4 = 24

Explanation: How recursion works?

Suppose user enters 4 which is passed to function factorial(). Here are the steps involved:
 In first factorial() function, test expression inside if statement is true. The statement
return num*factorial(num-1); is executed, which calls second factorial()
function and argument passed is num-1 which is 3.
 In second factorial() function, test expression inside if statement is true. The
statement return num*factorial(num-1); is executed, which calls third factorial()
function and argument passed is num-1 which is 2.
 In third factorial() function, test expression inside if statement is true. The statement
return num*factorial(num-1); is executed, which calls fourth factorial() function
and argument passed is num-1 which is 1.
 The fourth factorial() function, test expression inside if statement is false. The
statement return 1; is executed, which returns 1 to third factorial() function.
 The thrid factorial() function returns 2 to second factorial() function.
 The second factorial() function returns 6 to first factorial() function.
 Finally, first factorial() function returns 24 to the main() function and is displayed.

C++ Return by Reference

In C++ Programming, you can pass values by reference but also you can return a value by
reference.  To understand this feature, you should have knowledge of global variables. If a
variable is defined outside every function, then that variable is called a global variable. Any part
of program after global variable declaration can access global variable. Learn more about global
variables. Consider this example:

Example 1: Return by Reference


#include <iostream>
using namespace std;
int n;
int& test();

int main() {
test() = 5;
cout<<n;
return 0;
}

int& test() {
return n;
}

Output

Explanation

In program above, the return type of function test() is int&. Hence this function returns by
reference. The return statement is return n; but unlike return by value. This statement doesn't
return value of n, instead it returns variable n itself.
Then the variable n is assigned to the left side of code test() = 5; and value of n is displayed.

Important Things to Care While Returning by Reference.


int& test() {
int n = 2;
return n;
}

 Ordinary function returns value but this function doesn't. Hence, you can't return constant from
this function.
 int& test() {
 return 2;
}

 You can't return a local variable from this function.

C++ Arrays

In programming, one of the frequently arising problem is to handle similar types of data.
Consider this situation: You have to store marks of more than one student depending upon the
input from user. These types of problem can be handled C++ programming(almost all
programming language have arrays) using arrays.

An array is a sequence of variable that can store value of one particular data type. For example:
15 int type value, 105 float type value etc.

Defining Arrays
type array_name[size];

Consider this code.

int test[85];

The above code creates an array which can hold 85 elements of int type.

Array Elements
The maximum number of elements an array can hold depends upon the size of an array. Consider
this code below:

int age[5];

This array can hold 5 integer elements.


Notice that the first element of an array is age[0] not age[1]. This array has 5 elements and
notice fifth is age[4] not age[5]. C++ programmer should always keep this is mind as it may
differ from other programming languages.

Array Initialization
Array can be initialized at the time of declaration. For example:

float test[5] = {12, 3, 4, -3, 9};

It is not necessary to write the size of an array during array declaration.

float test[] = {12, 3, 4, -3, 9};

I prefer writing size of array during array declaration because it quickly gives the information on
size of an array while help me in debugging code.

Example 1: C++ Array


C++ Program to store 5 numbers entered by user in an array and display first and last number
only.

#include <iostream>
using namespace std;

int main() {
int n[5];
cout<<"Enter 5 numbers: ";
/* Storing 5 number entered by user in an array using for loop. */
for (int i = 0; i < 5; ++i) {
cin>>n[i];
}

cout<<"First number: "<<n[0]<<endl; // first element of an array is n[0]


cout<<"Last number: "<<n[4]; // last element of an array is
n[SIZE_OF_ARRAY - 1]
return 0;
}

Output

Enter 5 numbers: 4
-3
5
2
0
First number: 4
Last number: 0

C++ Multidimensional Arrays

In arrays chapter, you learned about one dimensional array, that is, single variables specifies
array. C++ allows programmer to create array of an array known as multidimensional arrays.
Consider this example:

int x[3][4];

Here, x is a two dimensional array. This array can hold 12 elements. You can think this array as
table with 3 row and each row has 4 column.

Three dimensional also array works in similar way. For example:

float x[2][4][3];

This array x can hold 24 elements. You can think this example as: Each 2 elements can hold 4
elements, which makes 8 elements and each 8 elements can hold 3 elements. Hence, total
number of elements this array can hold is 24.

Multidimensional Array Initialisation


You can initialise a multidimensional array in more than one way. Consider this examples to
initialise two dimensional array.

int test[2][3] = {2, 4, -5, 9, 0, 9};

Better way to initialise this array with same array elements as above.
int test[2][3] = { {2, 4, 5}, {9, 0 0}};

Initialisation of three dimensional array


int test[2][3][4] = {3, 4, 2, 3, 0, -3, 9, 11, 23, 12, 23,
2, 13, 4, 56, 3, 5, 9, 3, 5, 5, 1, 4, 9};

Better way to initialise this array with same elements as above.

int test[2][3][4] = {
{ {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} },
{ {13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9} }
};

Example 1: Two Dimensional Array

C++ Program to display all elements of an initialised two dimensional array.

#include <iostream>
using namespace std;

int main() {
int test[3][2] = {
{2, -5},
{4, 0},
{9, 1}
};
for(int i = 0; i < 3; ++i) {
for(int j = 0; j < 2; ++j) {
cout<< "test["<< i << "][" << ;j << "] = " << test[i][j]<<endl;
}
}
return 0;
}
test[0][0] = 2
test[0][1] = -5
test[1][0] = 4
test[1][1] = 0
test[2][0] = 9
test[2][1] = 1

Example 2: Two Dimensional Array


C++ Program to store temperature of two different cities for a week and display it.

#include <iostream>
using namespace std;
const int CITY = 2;
const int WEEK = 7;

int main() {
int temperature[CITY][WEEK];
cout<<"Enter all temperature for a week of first city and then second
city. \n";
for (int i = 0; i < CITY; ++i) {
for(int j = 0; j < WEEK; ++j) {
cout<<"City "<<i+1<<", Day "<<j+1<<" : ";
cin>>temperature[i][j];
}
}
cout<<"\n\nDisplaying Values:\n";
for (int i = 0; i < CITY; ++i) {
for(int j = 0; j < WEEK; ++j) {
cout<<"City "<<i+1<<", Day "<<j+1<<" = "<< temperature[i]
[j]<<endl;
}
}
return 0;
}
Enter all temperature for a week of first city and then second city.
City 1, Day 1 : 32
City 1, Day 2 : 33
City 1, Day 3 : 32
City 1, Day 4 : 34
City 1, Day 5 : 35
City 1, Day 6 : 36
City 1, Day 7 : 38
City 2, Day 1 : 23
City 2, Day 2 : 24
City 2, Day 3 : 26
City 2, Day 4 : 22
City 2, Day 5 : 29
City 2, Day 6 : 27
City 2, Day 7 : 23

Displaying Values:
City 1, Day 1 = 32
City 1, Day 2 = 33
City 1, Day 3 = 32
City 1, Day 4 = 34
City 1, Day 5 = 35
City 1, Day 6 = 36
City 1, Day 7 = 38
City 2, Day 1 = 23
City 2, Day 2 = 24
City 2, Day 3 = 26
City 2, Day 4 = 22
City 2, Day 5 = 29
City 2, Day 6 = 27
City 2, Day 7 = 23

Example 3: Three Dimensional Array

C++ Program to Store value entered by user in three dimensional array and display it.

#include <iostream>
using namespace std;

int main() {
int test[2][3][2]; // this array can store 12 elements
cout<<"Enter 12 values: \n";
for(int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for(int k = 0; k < 2; ++k ) {
cin>>test[i][j][k];
}
}
}
cout<<"\nDisplaying Value stored:"<<endl;
/* Displaying the values with proper index. */
for(int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for(int k = 0; k < 2; ++k ) {
cout<< "test["<<i<<"]["<<j<<"]["<<k<<"] = "<< test[i][j]
[k]<<endl;
}
}
}

return 0;
}

Output

Enter 12 values:
1
2
3
4
5
6
7
8
9
10
11
12

Displaying Value stored:


test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12

As the number of dimension increases, the complexity also increases tremendously although the
concept is quite similar.

Passing Array to a Function in C++ Programming

Arrays can be passed to a function as an argument. Consider this example to pass one-
dimensional array to a function:
Example 1: Passing One-dimensional Array to a Function
C++ Program to display marks of 5 students by passing one-dimensional array to a
function.

#include <iostream>
using namespace std;
void display(int marks[5]);

int main() {
int marks[5] = {88, 76, 90, 61, 69};
display(marks);
return 0;
}

void display(int m[5]) {


cout<<"Displaying marks: "<<endl;
for (int i = 0; i <5; ++i) {
cout<<"Student "<<i+1<<": "<<m[i]<<endl;
}
}

Output

Displaying marks:
Student 1: 88
Student 2: 76
Student 3: 90
Student 4: 61
Student 5: 69

When an array is passed as an argument to a function, only the name of an array is used as
argument.

display(marks);

Also notice the difference while passing array as an argument rather than variable.

void display(int m[5]);

The argument used marks in the above code represents the memory address of first element of
array marks[5]. And the formal argument int m[5] in function declaration decays to int* m;.
That's why, although the function is manipulated in the user-defined function with different array
name m[5], the original array is manipulated. The C++ programming language handles passing
array to a function in this way to save memory and time.

Note: You need to have understanding of pointers to understand passing array to a function.
Learn more: Call by reference

Passing Multidimensional Array to a Function


Multidimensional array can be passed in similar way as one-dimensional array. Consider this
example to pass two dimensional array to a function:

Example 2: Passing Multidimensional Array to a Function


C++ Program to display the elements of two dimensional array by passing it to a function.

#include <iostream>
using namespace std;
void display(int n[3][2]);

int main() {
int num[3][2] = {
{3, 4},
{9, 5},
{7, 1}

};
display(num);
return 0;
}
void display(int n[3][2]) {

cout<<"Displaying Values: "<<endl;


for(int i = 0; i < 3; ++ i) {
for(int j = 0; j < 2; ++j) {
cout<<n[i][j]<<" ";
}
}
}

Output

Displaying Values:
3 4 9 5 7 1

Multidimensional array with dimension more than 2 can be passed in similar way as two
dimensional array.

C++ Strings

There are two types of strings commonly use in C++ programming language:

 Strings that are objects of string class (The Standard C++ Library string class)
 C-strings (C-style Strings)

C-strings
In C programming, only one type of string is available and this is also supported in C++
programming. Hence it's called C-strings. C-strings are the arrays of type char terminated with
null character, that is, \0 (ASCII value of null character is 0). Consider this example:
char str[] = "C++";

In the above code, str is a string and it holds 4 character. Although, "C++" has 3 character, the
null character \0 is added to the end of the string automatically.

Other ways of defining the string:

char str[4] = "C++";

char str[] = {'C','+','+','\0'};

char str[4] = {'C','+','+','\0'};

Like arrays, it is not necessary to use all the space allocated for the string. For example:

char str[100] = "C++";

Example 1: C++ String


C++ program to display a string entered by user.

#include <iostream>
using namespace std;

int main() {
char str[100];
cout<<"Enter a string: ";
cin>>str;
cout<<"You entered: "<<str<<endl;
cout<<"\nEnter another string: ";
cin>>str;
cout<<"You entered: "<<str<<endl;
return 0;
}

Output

Enter a string: C++


You entered: C++

Enter another string: Programming is fun.


You entered: Programming
Notice that, in second example only "programming" is displayed instead of "Programming is
fun". It is because The extraction operator >> considers a space has a terminating character.

Example 2: C++ String


C++ program to read and display an entire line entered by user.

#include <iostream>
using namespace std;

int main() {
char str[100];
cout<<"Enter a string: ";
cin.get(str, 100);
cout<<"You entered: "<<str<<endl;
return 0;
}

Output

Enter a string: Programming is fun.


You entered: Programming is fun.

To read the text containing blank space, cin.get function can be used. This function takes two
arguments. First argument is the name of the string(address of first element of string) and second
argument is the maximum size of the array.

Passing String to a Function


Strings are passed to a function in a similar way arrays are passed to a function.

#include <iostream>
using namespace std;
void display(char s[]);

int main() {
char str[100];
cout<<"Enter a string: ";
cin.get(str, 100);
display(str);
return 0;
}

void display(char s[]) {


cout<<"You entered: "<<s;
}

Output

Enter a string: Programming is fun.


You entered: Programming is fun.
C++ Structure

Structure is the collection of variables of different types under a single name for better
visualisation of problem. Arrays is also collection of data but arrays can hold data of only one
type whereas structure can hold data of one or more types.

How to define a structure in C++ programming?


The struct keyword defines a structure type followed by an identifier(name of the structure).
Then inside the curly braces, you can declare one or more members (declare variables inside
curly braces) of that structure. For example:

struct person {
char name[50];
int age;
float salary;
};

Here a structure person is defined which has three members: name, age and salary.

When a structure is created, no memory is allocated. The structure definition is only the blueprint
for the creating of variables. You can imagine it as a datatype. When you define an integer as
below:

int foo;

The int specifies that, variable foo can hold integer element only. Similarly, structure definition
only specifies that, what property a structure variable holds when it is defined.

How to define a structure variable?


Once you declare a structure person as above. You can define a structure variable as:

person bill;

Here, a structure variable bill is defined which is of type structure person. When structure
variable is defined, then only the required memory is allocated by the compiler. Considering you
have either 32-bit or 64-bit system, the memory of float is 4 bytes, memory of int is 4 bytes and
memory of char is 1 byte. Hence, 58 bytes of memory is allocated for structure variable bill.

How to access members of a structure?


The members of structure variable is accessed using dot operator. Suppose, you want to access
age of structure variable bill and assign it 50 to it. You can perform this task by using following
code below:

bill.age = 50;
Example 1: C++ Structure
C++ Program to assign data to members of a structure variable and display it.

#include <iostream>
using namespace std;

struct person {
char name[50];
int age;
float salary;
};

int main() {

person p1;

cout << "Enter Full name: ";


cin.get(p1.name, 50);
cout << "Enter age: ";
cin >> p1.age;
cout << "Enter salary: ";
cin >> p1.salary;

cout << "\nDisplaying Information." << endl;


cout << "Name: " << p1.name << endl;
cout <<"Age: " << p1.age << endl;
cout << "Salary: " << p1.salary;

return 0;
}

Output

Enter Full name: Magdalena Dankova


Enter age: 27
Enter salary: 1024.4

Displaying Information.
Name: Magdalena Dankova
Age: 27
Salary: 1024.4

Here a structure person is declared which has three members. Inside main() function, a structure
variable p1 is defined. Then, the user is asked to enter information and data entered by user is
displayed.

C++ Structure and Function

Structure variables can be passed to a function and returned from a function in similar way as
normal arguments:

Passing structure to function in C++


A structure variable can be passed to a function in similar way as normal argument. Consider this
example:

Example 1: C++ Structure and Function


#include <iostream>
using namespace std;

struct person {
char name[50];
int age;
float salary;
};

void displayData(person); // Function declaration

int main() {

person p;

cout << "Enter Full name: ";


cin.get(p.name, 50);
cout << "Enter age: ";
cin >> p.age;
cout << "Enter salary: ";
cin >> p.salary;

displayData(p); // Function call with structure variable as arugment

return 0;
}

void displayData(person p1) {

cout << "\nDisplaying Information." << endl;


cout << "Name: " << p1.name << endl;
cout <<"Age: " << p1.age << endl;
cout << "Salary: " << p1.salary;

Output

Enter Full name: Bill Jobs


Enter age: 55
Enter salary: 34233.4

Displaying Information.
Name: Bill Jobs
Age: 55
Salary: 34233.4

In this program, user is asked to enter the data for the members of a structure variable inside
main() function. Then that structure variable to passed to a function using code.

displayData(p);
The return type of displayData() is void and one argument of type structure person is passed.
The function prototype also should match the function definition. Then the members of structure
p1 is displayed from this function.

Returning structure from function in C++


#include <iostream>
using namespace std;

struct person {
char name[50];
int age;
float salary;
};

person getData(person);
void displayData(person);

int main() {

person p;

p = getData(p);
displayData(p);

return 0;
}

person getData(person p1) {

cout << "Enter Full name: ";


cin.get(p1.name, 50);
cout << "Enter age: ";
cin >> p1.age;
cout << "Enter salary: ";
cin >> p1.salary;
return p1;

void displayData(person p1) {

cout << "\nDisplaying Information." << endl;


cout << "Name: " << p1.name << endl;
cout <<"Age: " << p1.age << endl;
cout << "Salary: " << p1.salary;

The output of this program is same as program above.

In this program, the structure variable p of type structure person is defined under main()
function. The structure variable p is passed to getData() function which takes input from user
and that value is stored in member function of structure variable p1 which is then returned to
main function.
p = getData(p);

Note: The value of all members of a structure variable can be assigned to another structure using
assignment operator = if both structure variables are of same type. You don't need to manually
assign each members.

Then the structure variable p is passed to displayData() function, which displays the
information.

C++ Pointers to Structure

A pointer variable can be created not only for native types like (int, float, double etc.) but
they can also be created for user defined types like structure. For example:

#include <iostream>
using namespace std;

struct temp {
int i;
float f;
};

int main() {
temp *ptr;
return 0;
}

This program creates a pointer ptr of type structure temp.

Example 1: Pointers to Structure


#include <iostream>
using namespace std;

struct Distance {
int feet;
float inch;
};

int main() {
Distance *ptr, d;

ptr = &d;

cout << "Enter feet: ";


cin >> (*ptr).feet;
cout << "Enter inch: ";
cin >> (*ptr).inch;

cout << "Displaying information." << endl;


cout << "Distance = " << (*ptr).feet << " feet " << (*ptr).inch << "
inches";

return 0;
}

Output

Enter feet: 4
Enter inch: 3.5
Displaying information.
Distance = 4 feet 3.5 inches

In this program, a pointer variable ptr and normal variable d of type structure Distance is
defined. The address of variable d is stored to pointer variable, that is, ptr is pointing to variable
d. Then the member function of variable d is accessed using pointer.

Note: Since pointer ptr is pointing to variable d in this program, (*ptr).inch and d.inch is
exact same cell. Similarly, (*ptr).feet and d.feet is exact same cell.

The syntax to access member function using pointer is ugly and there is alternative notation ->
which is more common.

ptr->feet is same as (*ptr).feet


ptr->inch is same as (*ptr).inch

C++ Enumeration

An enumeration is a user-defined type whose value is restricted to one of several explicitly


named constants(enumerators). Enumeration are defined using keyword: enum.

enum seasons { spring, summer, autumn, winter };

This code is a enum declaration. After declaration, you can define variable of type seasons. And
this variable of type seasons can only have one of those 4 values. For example:

C++ program to define enumeration type and assign value to variable of that type.

#include <iostream>
using namespace std;

enum seasons { spring, summer, autumn, winter };

int main() {

seasons s;
s = autumn; // Correct
s = rainy; // Error
return 0;
}

In this program, an enum type seasons is declared with 4 enumerators (spring, summer, autumn,
winter). Then, inside main() function, a variable s of type seasons is defined. This variable s can
only store any one of four values (spring, summer, autumn, winter).
By default, the value of first enumerator is 0, second is 1 and so in. In this program, spring is
equal to 0, summer is equal to 1 and autumn is 2 and winter is 3.

One very important thing to remember is that, spring, summer etc are not variables. They are
treated as integers by compiler. Hence, once enumerators are defined, their value can't be
changed in program.

Example 1: C++ Enumeration


#include <iostream>
using namespace std;

enum seasons { spring, summer, autumn, winter };

int main() {

seasons s;

s = spring;
cout >> "spring = " >> s >> endl;

s = summer;
cout >> "summer = " >> s >> endl;

s = autumn;
cout >> "autumn = " >> s >> endl;

s = winter;
cout >> "winter = " >> s >> endl;

return 0;
}

Output

spring = 0
summer = 1
autumn = 2
winter = 3

You can change the default value during enumeration declaration(after declaration, you cannot
change it) and give them another value. Consider this example:

Example 2: C++ Enumeration


#include <iostream>
using namespace std;

enum seasons { spring = 34, summer = 4, autumn = 9, winter = 32};

int main() {

seasons s;

s = summer;
cout << "summer = " << s << endl;

return 0;
}

Output

summer = 4

In this program, the enumerations are given the different integer value than default value.

C++ Class
- A class is the collection of related data and function under a single name.
- A C++ program can have any number of classes.
- When related data and functions are kept under a class, it helps to visualize the complex
problem efficiently and effectively.

A Class is a blueprint for objects

- When a class is defined, no memory is allocated. You can imagine like a datatype.

int var;

- The above code specifies var is a variable of type integer; int is used for specifying variable var is of
integer type.
- Similarly, class are also just the specification for objects and object bears the property of that class.

Defining the Class in C++

- Class is defined in C++ programming using keyword class followed by identifier(name of


class).

- Body of class is defined inside curly brackets an terminated by semicolon at the end in
similar way as structure.

class class_name
{
// some data
// some functions
};
Example of Class in C++
class temp
{
private:
int data1;
float data2;
public:
void func1()
{ data1=2; }
float func2(){
data2=3.5;
retrun data;
}
};

Explanation

- As mentioned, definition of class starts with keyword class followed by name of class(temp)
in this case. The body of that class is inside the curly brackets and terminated by semicolon at
the end.

- There are two keywords: private and public mentioned inside the body of class.

Keywords: private and public

- Keyword private makes data and functions private and keyword public makes data and
functions public.

- Private data and functions are accessible inside that class only whereas, public data and
functions are accessible both inside and outside the class.

- This feature in OOP is known as data hiding.

- If programmer mistakenly tries to access private data outside the class, compiler shows error
which prevents the misuse of data. Generally,

- data are private and functions are public.

C++ Objects

- When class is defined, only specification for the object is defined.

- Object has same relationship to class as variable has with the data type.

- Objects can be defined in similar way as structure is defined.


Syntax to Define Object in C++
class_name variable name;

- For the above defined class temp, objects for that class can be defined as:

temp obj1,obj2;

- Here, two objects (obj1 and obj2) of temp class are defined.

Data member and Member functions

- The data within the class is known as data member.

- The function defined within the class is known as member function.

- These two technical terms are frequently used in explaining OOP.

- In the above class temp, data1 and data2 are data members and func1() and func2() are
member functions.

Accessing Data Members and Member functions

- Data members and member functions can be accessed in similar way the member of structure
is accessed using member operator (.).

- For the class and object defined above, func1() for object obj2 can be called using code:

obj2.func1();

- Similary, the data member can be accessed as:

object_name.data_memeber;

Note: You cannot access the data member of the above class temp because both data members
are private so it cannot be accessed outside that class.

Example to Explain Working of Object and Class in C++ Programming

/* Program to illustrate working of Objects and Class in C++ Programming */


#include <iostream>
using namespace std;
class temp
{
private:
int data1;
float data2;
public:
void int_data(int d){
data1=d;
cout<<"Number: "<<data1;
}
float float_data(){
cout<<"\nEnter data: ";
cin>>data2;
return data2;
}
};
int main(){
temp obj1, obj2;
obj1.int_data(12);
cout<<"You entered "<<obj2.float_data();
return 0;
}

Output:

Number: 12
Enter data: 12.43
You entered: 12.43

Explanation of Program

In this program, two data members data1 and data2 and two member function int_data() and
float_data() are defined under temp class. Two objects obj1 and obj2 of that class are
declared. Function int_data() for the obj1 is executed using code obj1.int_data(12);,
which sets 12 to the data1 of object obj1. Then, function float_data() for the object obj2 is
executed which takes data from user; stores it in data2 of obj2 and returns it to the calling
function.

Note: In this program, data2 for object obj1 and data1 for object obj2 is not used and contains
garbage value.

Defining Member Function Outside the Class

A large program may contain many member functions. For the clarity of the code, member
functions can be defined outside the class. To do so, member function should be declared inside
the class(function prototype should be inside the class). Then, the function definition can be
defined using scope resolution operator ::. Learn more about defining member function outside
the class.

C++ Constructors

Constructors are the special type of member function that initialises the object automatically
when it is created Compiler identifies that the given member function is a constructor by its
name and return type. Constructor has same name as that of class and it does not have any return
type.

..... ... .....


class temporary
{
private:
int x;
float y;
public:
temporary(): x(5), y(5.5) /* Constructor */
{
/* Body of constructor */
}
.... ... ....
}
int main()
{
Temporary t1;
.... ... ....
}

Working of Constructor

In the above pseudo code, temporary() is a constructor. When the object of class temporary is
created, constructor is called and x is initialized to 5 and y is initialized to 5.5 automatically.

You can also initialise data member inside the constructor's function body as below. But, this
method is not preferred.

temporary(){
x=5;
y=5.5;
}
/* This method is not preferred. /*

Use of Constructor in C++


Suppose you are working on 100's of objects and the default value of a data member is 0.
Initialising all objects manually will be very tedious. Instead, you can define a constructor which
initialises that data member to 0. Then all you have to do is define object and constructor will
initialise object automatically. These types of situation arises frequently while handling array of
objects. Also, if you want to execute some codes immediately after object is created, you can
place that code inside the body of constructor.

Constructor Example
/*Source Code to demonstrate the working of constructor in C++ Programming */
/* This program calculates the area of a rectangle and displays it. */
#include <iostream>
using namespace std;
class Area
{
private:
int length;
int breadth;

public:
Area(): length(5), breadth(2){ } /* Constructor */
void GetLength()
{
cout<<"Enter length and breadth respectively: ";
cin>>length>>breadth;
}
int AreaCalculation() { return (length*breadth); }
void DisplayArea(int temp)
{
cout<<"Area: "<<temp;
}
};
int main()
{
Area A1,A2;
int temp;
A1.GetLength();
temp=A1.AreaCalculation();
A1.DisplayArea(temp);
cout<<endl<<"Default Area when value is not taken from user"<<endl;
temp=A2.AreaCalculation();
A2.DisplayArea(temp);
return 0;
}

Explanation

In this program, a class of name Area is created to calculate the area of a rectangle. There are
two data members length and breadth. A constructor is defined which initialises length to 5 and
breadth to 2. And, we have three additional member functions GetLength(),
AreaCalculation() and DisplayArea() to get length from user, calculate the area and
display the area respectively.

When, objects A1 and A2 are created then, the length and breadth of both objects are initialized to
5 and 2 respectively because of the constructor. Then the member function GetLength() is
invoked which takes the value of length and breadth from user for object A1. Then, the area for
the object A1 is calculated and stored in variable temp by calling AreaCalculation() function.
And finally, the area of object A1 is displayed. For object A2, no data is asked from the user. So,
the value of length will be 5 and breadth will be 2. Then, the area for A2 is calculated and
displayed which is 10.

Output

Enter length and breadth respectively: 6


7
Area: 42
Default Area when value is not taken from user
Area: 10
Constructor Overloading
Constructor can be overloaded in similar way as function overloading. Overloaded constructors
have same name(name of the class) but different number of argument passed. Depending upon
the number and type of argument passed, specific constructor is called. Since, constructor are
called when object is created. Argument to the constructor also should be passed while creating
object. Here is the modification of above program to demonstrate the working of overloaded
constructors.

/* Source Code to demonstrate the working of overloaded constructors */


#include <iostream>
using namespace std;
class Area
{
private:
int length;
int breadth;

public:
Area(): length(5), breadth(2){ } // Constructor without no
argument
Area(int l, int b): length(l), breadth(b){ } // Constructor with two
argument
void GetLength()
{
cout<<"Enter length and breadth respectively: ";
cin>>length>>breadth;
}
int AreaCalculation() { return (length*breadth); }
void DisplayArea(int temp)
{
cout<<"Area: "<<temp<<endl;
}
};
int main()
{
Area A1,A2(2,1);
int temp;
cout<<"Default Area when no argument is passed."<<endl;
temp=A1.AreaCalculation();
A1.DisplayArea(temp);
cout<<"Area when (2,1) is passed as argument."<<endl;
temp=A2.AreaCalculation();
A2.DisplayArea(temp);
return 0;
}

Explanation of Overloaded Constructors

For object A1, no argument is passed. Thus, the constructor with no argument is invoked which
initialises length to 5 and breadth to 2. Hence, the area of object A1 will be 10. For object A2, 2
and 1 is passed as argument. Thus, the constructor with two argument is called which initialises
length to l(2 in this case) and breadth to b(1 in this case.). Hence the area of object A2 will be 2.

Output
Default Area when no argument is passed.
Area: 10
Area when (2,1) is passed as argument.
Area: 2

Default Copy Constructor


A object can be initialized with another object of same type. Let us suppose the above program.
If you want to initialise a object A3 so that it contains same value as A2. Then, this can be
performed as:

....
int main() {
Area A1,A2(2,1);
Area A3(A2); /* Copies the content of A2 to A3 */
OR,
Area A3=A2; /* Copies the content of A2 to A3 */
}

You might think, you may need some constructor to perform this task. But, no additional
constructor is needed. It is because this constructor is already built into all classes.

Passing and Returning Object from Function in C++ Programming

In C++ programming, objects can be passed to function in similar way as variables and
structures.

Procedure to Pass Object to Function

Example to Pass Object to Function


C++ program to add two complex numbers by passing objects to function.
#include <iostream>
using namespace std;
class Complex
{
private:
int real;
int imag;
public:
Complex(): real(0), imag(0) { }
void Read()
{
cout<<"Enter real and imaginary number respectively:"<<endl;
cin>>real>>imag;
}
void Add(Complex comp1,Complex comp2)
{
real=comp1.real+comp2.real;
/* Here, real represents the real data of object c3 because this function is
called using code c3.add(c1,c2); */
imag=comp1.imag+comp2.imag;
/* Here, imag represents the imag data of object c3 because this function is
called using code c3.add(c1,c2); */
}
void Display()
{
cout<<"Sum="<<real<<"+"<<imag<<"i";
}
};
int main()
{
Complex c1,c2,c3;
c1.Read();
c2.Read();
c3.Add(c1,c2);
c3.Display();
return 0;
}

Output

Enter real and imaginary number respectively:


12
3
Enter real and imaginary number respectively:
2
6
Sum=14+9i

Returning Object from Function


The syntax and procedure to return object is similar to that of returning structure from function.
Example to Return Object from Function
This program is the modification of above program displays exactly same output as above. But,
in this program, object is return from function to perform this task.

#include <iostream>
using namespace std;
class Complex
{
private:
int real;
int imag;
public:
Complex(): real(0), imag(0) { }
void Read()
{
cout<<"Enter real and imaginary number respectively:"<<endl;
cin>>real>>imag;
}
Complex Add(Complex comp2)
{
Complex temp;
temp.real=real+comp2.real;
/* Here, real represents the real data of object c1 because this function is
called using code c1.Add(c2) */
temp.imag=imag+comp2.imag;
/* Here, imag represents the imag data of object c1 because this function is
called using code c1.Add(c2) */
return temp;
}
void Display()
{
cout<<"Sum="<<real<<"+"<<imag<<"i";
}
};
int main()
{
Complex c1,c2,c3;
c1.Read();
c2.Read();
c3=c1.Add(c2);
c3.Display();
return 0;
}

C++ Operator Overloading

The meaning of operators are already defined and fixed for basic types like: int, float, double etc
in C++ language. For example: If you want to add two integers then, + operator is used. But, for
user-defined types(like: objects), you can define the meaning of operator, i.e, you can redefine
the way that operator works. For example: If there are two objects of a class that contain string as
its data member, you can use + operator to concatenate two strings. Suppose, instead of strings if
that class contains integer data member, then you can use + operator to add integers. This feature
in C++ programming that allows programmer to redefine the meaning of operator when they
operate on class objects is known as operator overloading.

Why Operator overloading is used in C++ programming?


You can write any C++ program without the knowledge of operator overloading. But, operator
operating are profoundly used by programmer to make a program clearer. For example: you can
replace the code like: calculation = add(mult(a,b),div(a,b)); with calculation =
a*b+a/b; which is more readable and easy to understand.

How to overload operators in C++ programming?


To overload a operator, a operator function is defined inside a class as:

The return type comes first which is followed by keyword operator, followed by operator
sign,i.e., the operator you want to overload like: +, <, ++ etc. and finally the arguments is passed.
Then, inside the body of you want perform the task you want when this operator function is
called.
This operator function is called when, the operator(sign) operates on the object of that class
class_name.

Example of operator overloading in C++ Programming

/* Simple example to demonstrate the working of operator overloading*/


#include <iostream>
using namespace std;
class temp
{
private:
int count;
public:
temp():count(5){ }
void operator ++() {
count=count+1;
}
void Display() { cout<<"Count: "<<count; }
};
int main()
{
temp t;
++t; /* operator function void operator ++() is called */
t.Display();
return 0;
}

Output

Count: 6

Explanation

In this program, a operator function void operator ++ () is defined(inside class temp), which
is invoked when ++ operator operates on the object of type temp. This function will increase the
value of count by 1.

Things to remember while using Operator overloading in C++ language

1. Operator overloading cannot be used to change the way operator works on built-in types.
Operator overloading only allows to redefine the meaning of operator for user-defined types.
2. There are two operators assignment operator(=) and address operator(&) which does not need
to be overloaded. Because these two operators are already overloaded in C++ library. For
example: If obj1 and obj2 are two objects of same class then, you can use code obj1=obj2;
without overloading = operator. This code will copy the contents object of obj2 to obj1.
Similarly, you can use address operator directly without overloading which will return the
address of object in memory.
3. Operator overloading cannot change the precedence of operators and associativity of operators.
But, if you want to change the order of evaluation, parenthesis should be used.
4. Not all operators in C++ language can be overloaded. The operators that cannot be overloaded
in C++ are ::(scope resolution), .(member selection), .*(member selection through pointer to
function) and ?:(ternary operator).

Following best practice while using operator overloading

Operator overloading allows programmer to define operator the way they want but, there is a
pitfall if operator overloading is not used properly. In above example, you have seen ++ operator
operates on object to increase the value of count by 1. But, the value is increased by 1 because,
we have used the code:

void operator ++() {


count=count+1;
}

If the code below was used instead, then the value of count will be decreased by 100 if ++
operates on object.

void operator ++() {


count=count-100;
}

But, it does not make any sense to decrease count by 100 when ++ operator is used. Instead of
making code readable this makes code obscure and confusing. And, it is the job of the
programmer to use operator overloading properly and in consistent manner.

Again, the above example is increase count by 1 is not complete. This program is incomplete in
sense that, you cannot use code like:

t1=++t

It is because the return type of operator function is void. It is generally better to make operator
work in similar way it works with basic types if possible.

Here, are the examples of operator overloading on different types of operators in C++ language
in best possible ways:

 Increment and Decrement Operator Overloading


 Overloading of binary operator - to subtract complex number

C++ Pointers

Pointers are the powerful feature of C++ programming which differs it from other popular
programming languages like: Java, Visual Basic etc.

To understand pointers, you should have the knowledge of address in computer memory.
Computer memory is broken down into bytes and each byte has its own address. For example: In
1KB memory, there are 1024 bytes and each byte is given an address (0 - 1023).
The Address-of Operator &
The & operator can find address occupied by a variable. If var is a variable then, &var gives the
address of that variable.

Example 1: Address-of Operator


#include <iostream>
using namespace std;

int main() {
int var1 = 3;
int var2 = 24;
int var3 = 17;
cout<<&var1<<endl;
cout<<&var2<<endl;
cout<<&var3<<endl;

Output

0x7fff5fbff8ac
0x7fff5fbff8a8
0x7fff5fbff8a4

The 0x in the beginning represents the address is in hexadecimal form. (You may not get the
same result on your system.). Notice that first address differs from second by 4-bytes and second
address differs from third by 4-bytes. It is because the size of integer(variable of type int) is 4
bytes in 64-bit system.

Pointers Variables
Now you know about address in computer memory, it's time to learn about pointers.

Consider a normal variable as in above example, these variables holds data. But pointer variables
or simply pointers are the special types of variable that holds memory address instead of data.

How to declare a pointer?


int *p;
OR,
int* p;

The statement above defines a pointer variable p. The pointer p holds the memory address. The
asterisk is a dereference operator which means pointer to. Here pointer p is a pointer to int,
that is, it is pointing an integer.

Note: In above statement p is a pointer variable that holds address not *p. The *pis an
expression. The content(value) of the memory address pointer p holds is given by expression *p.
Example 2: C++ Pointers
C++ Program to demonstrate the working of pointer.

#include <iostream>
using namespace std;
int main() {
int *pc, c;

c = 5;
cout<< "Address of c (&c): " << &c << endl;
cout<< "Value of c (c): " << c << endl << endl;

pc = &c; // Pointer pc holds the memory address of variable c


cout<< "Address that pointer pc holds (pc): "<< pc << endl;
cout<< "Content of the address pointer pc holds (*pc): " << *pc << endl <<
endl;

c = 11; // The content inside memory address &c is changed from 5 to


11.
cout << "Address pointer pc holds (pc): " << pc << endl;
cout << "Content of the address pointer pc holds (*pc): " << *pc << endl
<< endl;

*pc = 2;
cout<< "Address of c (&c): "<< &c <<endl;
cout<<"Value of c (c): "<< c<<endl<< endl;

return 0;
}

Output

Address of c (&c): 0x7fff5fbff80c


Value of c (c): 5

Address that pointer pc holds (pc): 0x7fff5fbff80c


Content of the address pointer pc holds (*pc): 5

Address pointer pc holds (pc): 0x7fff5fbff80c


Content of the address pointer pc holds (*pc): 11

Address of c (&c): 0x7fff5fbff80c


Value of c (c): 2
Explanation of program

 When c = 5; the value 5 is stored in the address of variable c.


 When pc = &c; the pointer pc holds the address of c and the expression *pc contains the
value of that address which is 5 in this case.
 When c = 11; the address that pointer pc holds is unchanged. But the expression *pc is
changed because now the address &c (which is same as pc) contains 11.
 When *pc = 2; the content in the address pc(which is equal to &c) is changed from 11 to 2.
Since the pointer pc and variable c has address, value of c is changed to 2.

C++ Pointers and Arrays

Pointers are the variables that hold address. Pointers can point at cells of an array not only single
variable. Consider this example:

int* ptr;
int a[5];
ptr = &a[2]; // &a[2] is the address of third element of a[5].
Suppose, pointer needs to point to the fourth element of an array, that is, hold address of fourth
array element in above case. Since ptr points to the third element in the above example, ptr + 1
points to the fourth element. You may think that, ptr + 1 may hold the address of byte next to
ptr. But it's not correct. It is because pointer ptr is a pointer to int and size of int is fixed for a
operating system (size of int is 4 byte of 64-bit operating system). Hence, the address between
ptr and ptr + 1 differs by 4 bytes. If pointer ptr was pointer to char then, the address between
ptr and ptr + 1 would have differed by 1 byte since size of a character is 1 byte.

Example 1: C++ Pointers and Arrays


C++ Program to display address of elements of an array using both array and pointers

#include <iostream>
using namespace std;

int main() {
float a[5];
float *ptr;

cout << "Displaying address using arrays: "<<endl;


for (int i = 0; i < 5; ++i) {
cout << "&a[" << i << "] = " << &a[i] <<endl;
}

ptr = a; // ptr = &a[0]


cout<<"\nDisplaying address using pointers: "<< endl;
for (int i = 0; i < 5; ++i) {
cout << "ptr + " << i << " = "<<ptr+i <<endl;
}

return 0;
}

Output

Displaying address using arrays:


&a[0] = 0x7fff5fbff880
&a[1] = 0x7fff5fbff884
&a[2] = 0x7fff5fbff888
&a[3] = 0x7fff5fbff88c
&a[4] = 0x7fff5fbff890

Displaying address using pointers:


ptr + 0 = 0x7fff5fbff880
ptr + 1 = 0x7fff5fbff884
ptr + 2 = 0x7fff5fbff888
ptr + 3 = 0x7fff5fbff88c
ptr + 4 = 0x7fff5fbff890

In the above program, different pointer is used for displaying the address of array elements. But,
array elements can be accessed using pointer notation (by using same array name). For example:

int p[3];

&p[0] is equivalent to p
&p[1] is equivalent to p+1
&p[2] is equivalen to p+2

Example 2: Pointer and Arrays


C++ Program to display address of array elements using pointer notation.

#include <iostream>
using namespace std;

int main() {
float a[5];

cout<<"Displaying address using pointers notation: "<< endl;


for (int i = 0; i < 5; ++i) {
cout << a+i <<endl;
}

return 0;
}

Output

Displaying address using pointers notation:


0x7fff5fbff8a0
0x7fff5fbff8a4
0x7fff5fbff8a8
0x7fff5fbff8ac
0x7fff5fbff8b0

You know that, pointer ptr holds the address and expression *ptr gives the content in that
address. Similarly, *(ptr + 1) gives the content in address ptr + 1. Consider this code below:

int p[5] = {3, 4, 5, 5, 3};

 &p[0] is equal to p and *p is equal to p[0]


 &p[1] is equal to p+1 and *(p+1) is equal to p[1]
 &p[2] is equal to p+2 and *(p+2) is equal to p[2]
 &p[i] is equal to p+i and *(p+i) is equal to p[i]

Example 3: C++ Pointer and Array


C++ Program to insert and display data entered by using pointer notation.

#include <iostream>
using namespace std;

int main() {
float a[5];

// Inserting data using pointer notation


cout << "Enter 5 numbers: ";
for (int i = 0; i < 5; ++i) {
cin >> *(a+i) ;
}

// Displaying data using pointer notation


cout << "Displaying data: " << endl;
for (int i = 0; i < 5; ++i) {
cout << *(a+i) << endl ;
}

return 0;
}

Output

Enter 5 numbers: 2.5


3.5
4.5
5
2
Displaying data:
2.5
3.5
4.5
5
2

C++ Pointers and Functions

Passing Argument by Reference


In function chapter, you learned about passing arguments to a function. This is pass by value
because actual value is passed. There is another way of passing argument in which actual value
is not passed, only the reference to that value is passed. Consider this example:

#include <iostream>
using namespace std;

int main() {
void swap(int&, int&); // Function prototype

int a = 1, b = 2;
cout << "Before swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;

swap(a, b);

cout << "\nAfter swapping" << endl;


cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}

void swap(int& n1, int& n2) {


int temp;
temp = n1;
n1 = n2;
n2 = temp;
}

Output

Before swapping
a = 1
b = 2

After swapping
a = 2
b = 1

In main(), two integer variables are defined. And those integers are passed to a function swap()
by reference. Compiler can identify this is pass by reference because function definition is void
swap(int& n1, int& n2) (notice the & sign after data type). Here, n1 and n2 are the different
names given to the argument passed, that is n1 and a is exact same variable (not only their value
is same but both name refer to one single variable). Similarly, n2 and b is exact same variable.

There is another way of doing this same exact task using pointers. Consider this example:

#include <iostream>
using namespace std;

int main() {
void swap(int*, int*); // Function prototype

int a = 1, b = 2;
cout << "Before swaping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;

swap(&a, &b);

cout << "\nAfter swaping" << endl;


cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}

void swap(int* n1, int* n2) {


int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}

The output of this example is same as before. In this case, the address of variable is passed
during function call rather than variable itself.

swap(&a, &b); // &a is address of a and &b is address of b


Since the address is passed instead of value, dereference operator must be used to access the
value stored in that address.

void swap(int* n1, int* n2) {


... .. ...
}

The *n1 and *n2 gives the value stored at address n1 and n2 respectively.

Since n1 contains the address of a, anything done to *n1 changes the value of a in main()
function as well. Similarly, b will have same value as *n2.

C++ Memory Management: new and delete

Arrays can be used to store multiple homogenous data but there are serious drawbacks of using
arrays. Programmer should allocate the memory of an array when they declare it but most of
time, the exact memory needed cannot be determined until runtime. The best thing to do in this
situation is to declare the array with maximum possible memory required (declare array with
maximum possible size expected) but this wastes memory. 

To avoid wastage of memory, you can dynamically allocate the memory required during runtime
using new and delete operator.

Example 1: C++ Memory Management


C++ Program to store GPA of n number of students and display it where n is the number
of students entered by user.

#include <iostream>
#include <cstring>
using namespace std;

int main() {
int n;
cout << "Enter total number of students: ";
cin >> n;
float* ptr;

ptr = new float[n]; // memory allocation for n number of floats

cout << "Enter GPA of students." <<endl;


for (int i = 0; i < n; ++i) {
cout << "Student" << i+1 << ": ";
cin >> *(ptr + i);
}
cout << "\nDisplaying GPA of students." << endl;
for (int i = 0; i < n; ++i) {
cout << "Student" << i+1 << " :" << *(ptr + i) << endl;
}

delete [] ptr; // ptr memory is released


return 0;
}

Output

Enter total number of students: 4


Enter GPA of students.
Student1: 3.6
Student2: 3.1
Student3: 3.9
Student4: 2.9

Displaying GPA of students.


Student1 :3.6
Student2 :3.1
Student3 :3.9
Student4 :2.9

In this program, only memory required to store n(entered by user) number of floating-point data
is declared dynamically.

The new Operator


ptr = new float[n];

This expression in the above program returns a pointer to a section of memory just large enough
to hold the n number of floating-point data.

The delete Operator


Once the memory is allocated using new operator, it should released to the operating system. If
the program uses large amount of memory using new, system may crash because there will be no
memory available for operating system. The following expression returns memory to the
operating system.

delete [] ptr;

The brackets [] indicates that, array is deleted. If you need to delete a single object then, you
don't need to use brackets.

delete ptr;

Example 2: C++ Memory Management


Object-oriented approach to handle above program in C++.

#include <iostream>
using namespace std;
class Test {
private:
int n;
float *ptr;
public:

Test() {
cout << "Enter total number of students: ";
cin >> n;

ptr = new float[n];

cout << "Enter GPA of students." <<endl;


for (int i = 0; i < n; ++i) {
cout << "Student" << i+1 << ": ";
cin >> *(ptr + i);
}
}

~Test() {
delete[] ptr;
}

void Display() {
cout << "\nDisplaying GPA of students." << endl;
for (int i = 0; i < n; ++i) {
cout << "Student" << i+1 << " :" << *(ptr + i) << endl;
}
}

};
int main() {
Test s;
s.Display();
return 0;
}

The output of this program is same as above program. When the object s is created, the
constructor is called which allocates the memory for n floating-point data.

When the object is destroyed, that is, object goes out of scope then, destructor is automatically
called.

~Test() {
delete[] ptr;
}

This destructor executes delete[] ptr; and returns memory to the operating system.

C++ Inheritance

Inheritance is one of the key feature of object-oriented programming including C++ which
allows user to create a new class(derived class) from a existing class(base class).  The derived
class inherits all feature from a base class and it can have additional features of its own.
Concept of Inheritance in OOP
Suppose, you want to calculate either area, perimeter or diagonal length of a rectangle by taking
data(length and breadth) from user. You can create three different objects( Area, Perimeter and
Diagonal) and asks user to enter length and breadth in each object and calculate corresponding
data. But, the better approach would be to create a additional object Rectangle to store value of
length and breadth from user and derive objects Area, Perimeter and Diagonal from Rectangle
base class. It is because, all three objects Area, Perimeter and diagonal are related to object
Rectangle and you don't need to ask user the input data from these three derived objects as this
feature is included in base class.

Implementation of Inheritance in C++ Programming


class Rectangle
{
... .. ...
};

class Area : public Rectangle


{
... .. ...
};

class Perimeter : public Rectangle


{
.... .. ...
};

In the above example, class Rectangle is a base class and classes Area and Perimeter are the
derived from Rectangle. The derived class appears with the declaration of class followed by a
colon, the keyword public and the name of base class from which it is derived.

Since, Area and Perimeter are derived from Rectangle, all data member and member function of
base class Rectangle can be accessible from derived class.

Note: Keywords private and protected can be used in place of public while defining derived
class(will be discussed later).

Source Code to Implement Inheritance in C++


Programming
This example calculates the area and perimeter a rectangle using the concept of inheritance.

/* C++ Program to calculate the area and perimeter of rectangles using concept
of inheritance. */

#include <iostream>
using namespace std;
class Rectangle
{
protected:
float length, breadth;
public:
Rectangle(): length(0.0), breadth(0.0)
{
cout<<"Enter length: ";
cin>>length;
cout<<"Enter breadth: ";
cin>>breadth;
}

};

/* Area class is derived from base class Rectangle. */


class Area : public Rectangle
{
public:
float calc()
{
return length*breadth;
}

};

/* Perimeter class is derived from base class Rectangle. */


class Perimeter : public Rectangle
{
public:
float calc()
{
return 2*(length+breadth);
}
};

int main()
{
cout<<"Enter data for first rectangle to find area.\n";
Area a;
cout<<"Area = "<<a.calc()<<" square meter\n\n";

cout<<"Enter data for second rectangle to find perimeter.\n";


Perimeter p;
cout<<"\nPerimeter = "<<p.calc()<<" meter";
return 0;
}

Output

Enter data for first rectangle to find area.


Enter length: 5
Enter breadth: 4
Area = 20 square meter

Enter data for second rectangle to find perimeter.


Enter length: 3
Enter breadth: 2
Area = 10 meter

Explanation of Program

In this program, classes Area and Perimeter are derived from class Rectangle. Thus, the object of
derived class can access the public members of Rectangle. In this program, when objects of class
Area and Perimeter are created, constructor in base class is automatically called. If there was
public member function in base class then, those functions also would have been accessible for
objects a and p.

Keyword protected

In this program, length and breadth in the base class are protected data members. These data
members are accessible from the derived class but, not accessible from outside it. This maintains
the feature of data hiding in C++ programming. If you defined length and breadth as private
members then, those two data are not accessible to derived class and if defined as public
members, it can be accessible from both derived class and from main( ) function.
Accessbility private protected public

Accessible from own class ? yes yes yes

Accessible from dervied class ? no yes yes

Accessible outside dervied class ? no no yes

Member Function Overriding in Inheritance

Suppose, base class and derived class have member functions with same name and arguments. If
you create an object of derived class and write code to access that member function then, the
member function in derived class is only invoked, i.e., the member function of derived class
overrides the member function of base class.

Public, Protected and Private Inheritance in C++ Programming

You can declare a derived class from a base class with different access control, i.e., public
inheritance, protected inheritance or private inheritance.

class base
{
.... ... ....
};

class derived : access_specifier base


{
.... ... ....
};

/* Note: Either keyword public, protected or private is used in place of


access_specifier. */

Things to remember while Using Public, Protected and


Private Inheritance

1. Protected and public members(data and function) of a base class are accessible from a derived
class(for all three: public, protected and private inheritance).
2. Objects of derived class with private and protected inheritance cannot access any data member
of a base class.
3. Objects of derived class with public inheritance can access only public member of a base class.
Summary of Public, Protected and Private Inheritance
Accessibility in Public Inheritance
Accessibility private protected public

Accessible from own class? yes yes yes

Accessible from dervied class? no yes yes

Accessible outside dervied class? no no yes

Accessibility in Protected Inheritance


Accessibility private protected public

Accessible from own class? yes yes yes

Accessible from dervied class? no yes yes


Accessibility private protected public

Accessible outside dervied class? no no no

Accessibility in Private Inheritance


Accessibility private protected public

Accessible from own class? yes yes yes

Accessible from dervied class? no yes yes

Accessible outside dervied class? no no no

C++ Function Overriding

If base class and derived class have member functions with same name and arguments. If you
create an object of derived class and write code to access that member function then, the member
function in derived class is only invoked, i.e., the member function of derived class overrides the
member function of base class. This feature in C++ programming is known as function
overriding.
Accessing the Overridden Function in Base Class From Derived Class

To access the overridden function of base class from derived class, scope resolution operator ::.
For example: If you want to access get_data() function of base class from derived class in
above example then, the following statement is used in derived class.

A::get_data; // Calling get_data() of class A.

It is because, if the name of class is not specified, the compiler thinks get_data() function is
calling itself.

C++ Multilevel Inheritance and Multiple Inheritance

Levels of Inheritance
In C++ programming, a class be can derived from a derived class which is known as multilevel
inhertiance. For example:

class A
{ .... ... .... };
class B : public A
{ .... ... .... };
class C : public B
{ .... ... .... };

In this example, class B is derived from class A and class C is derived from derived class B.

Example to Demonstrate the Multilevel Inheritance


#include <iostream>
using namespace std;

class A
{
public:
void display()
{
cout<<"Base class content.";
}
};

class B : public A
{

};

class C : public B
{

};

int main()
{
C c;
c.display();
return 0;
}

Output

Base class content.

Explanation of Program

In this program, class B is derived from A and C is derived from B. An object of class C is
defined in main( ) function. When the display( ) function is called, display( ) in class A is
executed because there is no display( ) function in C and B. The program first looks for display(
) in class C first but, can't find it. Then, looks in B because C is derived from B. Again it can't
find it. And finally looks it in A and executes the codes inside that function.

If there was display( ) function in C too, then it would have override display( ) in A because of
member function overriding.

Multiple Inheritance in C++


In C++ programming, a class can be derived from more than one parents. For example: A class
Rectangle is derived from base classes Area and Circle.

Source Code to Implement Multiple Inheritance in C++


Programming
This program calculates the area and perimeter of an rectangle but, to perform this program,
multiple inheritance is used.

#include <iostream>
using namespace std;
class Area
{
public:
float area_calc(float l,float b)
{
return l*b;
}
};

class Perimeter
{
public:
float peri_calc(float l,float b)
{
return 2*(l+b);
}
};

/* Rectangle class is derived from classes Area and Perimeter. */


class Rectangle : private Area, private Perimeter
{
private:
float length, breadth;
public:
Rectangle() : length(0.0), breadth(0.0) { }
void get_data( )
{
cout<<"Enter length: ";
cin>>length;
cout<<"Enter breadth: ";
cin>>breadth;
}

float area_calc()
{
/* Calls area_calc() of class Area and returns it. */

return Area::area_calc(length,breadth);
}

float peri_calc()
{
/* Calls peri_calc() function of class Perimeter and returns it. */

return Perimeter::peri_calc(length,breadth);
}
};

int main()
{
Rectangle r;
r.get_data();
cout<<"Area = "<<r.area_calc();
cout<<"\nPerimeter = "<<r.peri_calc();
return 0;
}

Output

Enter length: 5.1


Enter breadth: 2.3
Area = 11.73
Perimeter = 14.8

Note: This program is intended to give you idea on how multiple inheritance works rather than
the condition in which multiple inheritance is used.

Ambiguity in Multiple Inheritance

Multiple inheritance may be helpful in certain cases but, sometimes odd sort of problem
encounters while using multiple inheritance. For example: Two base classes have functions with
same name which is not overridden in derived class and if you write code to access that function
using object of derived class, compiler shows error because, it cannot determine which function
to call. Here is a code for this type of ambiguity in multiple inheritance

class base1
{
public:
void some_function( )
{ .... ... .... }
};
class base2
{
void some_function( )
{ .... ... .... }
};
class derived : public base1, public base2
{

};

int main()
{
derived obj;

/* Error because compiler can't figure out which function to call either
same_function( ) of base1 or base2 .*/
obj.same_function( )
}

But, this problem can be solved easily using scope resolution function to specify which function
to class either base1 or base2

int main()
{
obj.base1::same_function( ); /* Function of class base1 is called. */
obj.base2::same_function( ); /* Function of class base2 is called. */
}

C++ friend Function and friend Classes

One of the important concept of OOP is data hiding, i.e., a nonmember function cannot access an
object's private or protected data. But, sometimes this restriction may force programmer to write
long and complex codes. So, there is mechanism built in C++ programming to access private or
protected data from non-member function which is  friend function and friend class.

friend Function in C++


If a function is defined as a friend function then, the private and protected data of class can be
accessed from that function. The complier knows a given function is a friend function by its
keyword friend. The declaration of friend function should be made inside the body of class (can
be anywhere inside class either in private or public section) starting with keyword friend.

class class_name
{
...... .... ........
friend return_type function_name(argument/s);
...... .... ........
}

Now, you can define friend function of that name and that function can access the private and
protected data of that function. No keywords in used in function definition of friend function.
Example to Demonstrate working of friend Function

/* C++ program to demonstrate the working of friend function.*/


#include <iostream>
using namespace std;
class Distance
{
private:
int meter;
public:
Distance(): meter(0){ }
friend int func(Distance); //friend function
};
int func(Distance d) //function definition
{
d.meter=5; //accessing private data from non-member function
return d.meter;
}
int main()
{
Distance D;
cout<<"Distace: "<<func(D);
return 0;
}

Output

Distance: 5

Here, friend function func() is declared inside Distance class. So, the private data can be
accessed from this function.

Though this example gives you what idea about the concept of friend function, this program
doesn't give you idea about when friend function is helpful.

Suppose, you need to operate on objects of two different class then,friend function can be very
helpful. You can operate on two objects of different class without using friend function but, you
program will be long, complex and hard to understand.
Example to operate on Objects of two Different class using friend Function

#include <iostream>
using namespace std;
class B; // forward declaration
class A {
private:
int data;
public:
A(): data(12){ }
friend int func(A , B); //friend function Declaration
};
class B {
private:
int data;
public:
B(): data(1){ }
friend int func(A , B); //friend function Declaration
};
int func(A d1,B d2)
/*Function func() is the friend function of both classes A and B. So, the
private data of both class can be accessed from this function.*/
{
return (d1.data+d2.data);
}
int main()
{
A a;
B b;
cout<<"Data: "<<func(a,b);
return 0;
}

In this program, classes A and B has declared func() as a friend function. Thus, this function
can access private data of both class. In this program, two objects of two different class A and B
are passed as an argument to friend function. Thus, this function can access private and protected
data of both class. Here, func() function adds private data of two objects and returns it to main
function.

To work this program properly, a forward declaration of a class should be made as in above
example(forward declaration of class B is made). It is because class B is referenced from class A
using code: friend int func(A , B);. So, class A should be declared before class B to work
properly.

friend Class in C++ Programming


Similarly like, friend function. A class can be made a friend of another class using keyword
friend. For example:

........ ..... ........


class A{
friend class B; // class B is a friend class
..... ..... .....
}
class B{
..... ..... .....
}

When a class is made a friend class, all the member functions of that class becomes friend
function. In this program, all member functions of class B will be friend function of class A.
Thus, any member function of class B can access the private and protected data of class A.

If B is declared friend class of A then, all member functions of class B can access private data
and protected data of class A but, member functions of class A cannot private and protected data
of class B. Remember, friendship relation in C++ is granted not taken.

You might also like