Professional Documents
Culture Documents
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;
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.
Flowchart of if...else
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;
}
}
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.
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
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;
}
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;
}
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.
for Loop
while Loop
do...while Loop
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.
#include <iostream>
using namespace std;
int main() {
int i, n, factorial = 1;
Output
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.
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.
for Loop
while Loop
do...while Loop
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++
#include <iostream>
using namespace std;
int main() {
int number, i = 1, factorial = 1;
cout<< "Enter a positive integer: ";
cin >> number;
Output
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:
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.
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.
Syntax of break
break;
In real practice, break statement is almost always used inside the body of conditional
statement(if...else) inside the loop.
C++ program to add all number entered by user until user enters 0.
#include <iostream>
using namespace std;
int main() {
float number, sum = 0.0;
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.
Syntax of continue
continue;
#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
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.
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:
return 0;
}
Output
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.
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.
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.
# include <iostream>
using namespace std;
int main() {
float num, average, sum = 0.0;
int i, n;
cout<<"Maximum number of inputs: ";
cin>>n;
jump:
average=sum/(i-1);
cout<<"\nAverage = "<<average;
return 0;
}
Output
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.
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.
# include <iostream>
#include <cmath>
int main() {
double number, squareRoot;
cout<<"Enter a number: ";
cin>>number;
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.
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 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;
}
Output
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:
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.
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 */
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.
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:
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;
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.
For better understanding of arguments and return in functions, user-defined functions can be
categorised as:
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;
}
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;
}
int main() {
int num;
cout<<"Enter a positive integer to check: ";
cin>>num;
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;
}
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.
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.
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. */
#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;
}
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.
#include <iostream>
using namespace std;
int absolute(int);
float absolute(float);
int main() {
int a = -5;
float b = 5.5;
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.
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
#include <iostream>
using namespace std;
int main() {
cout<<"No argument passed:\n";
display();
return 0;
}
Output
No 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.
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:
#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.
... .. ...
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.
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.
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.
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.
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
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.
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:
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.
Ordinary function returns value but this function doesn't. Hence, you can't return constant from
this function.
int& test() {
return 2;
}
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];
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];
Array Initialization
Array can be initialized at the time of declaration. For example:
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.
#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];
}
Output
Enter 5 numbers: 4
-3
5
2
0
First number: 4
Last number: 0
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.
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.
Better way to initialise this array with same array elements as above.
int test[2][3] = { {2, 4, 5}, {9, 0 0}};
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} }
};
#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
#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
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
As the number of dimension increases, the complexity also increases tremendously although the
concept is quite similar.
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;
}
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.
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
#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]) {
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.
Like arrays, it is not necessary to use all the space allocated for the string. For example:
#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
#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
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.
#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;
}
Output
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.
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.
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.
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;
return 0;
}
Output
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.
Structure variables can be passed to a function and returned from a function in similar way as
normal arguments:
struct person {
char name[50];
int age;
float salary;
};
int main() {
person p;
return 0;
}
Output
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.
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;
}
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.
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;
}
struct Distance {
int feet;
float inch;
};
int main() {
Distance *ptr, d;
ptr = &d;
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.
C++ Enumeration
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;
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.
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:
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.
- 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.
- 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.
- 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.
- If programmer mistakenly tries to access private data outside the class, compiler shows error
which prevents the misuse of data. Generally,
C++ Objects
- Object has same relationship to class as variable has with the data type.
- 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.
- In the above class temp, data1 and data2 are data members and func1() and func2() are
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();
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.
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.
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.
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. /*
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
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;
}
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
....
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.
In C++ programming, objects can be passed to function in similar way as variables and
structures.
Output
#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;
}
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.
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.
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.
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).
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:
If the code below was used instead, then the value of count will be decreased by 100 if ++
operates on object.
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:
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.
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.
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 = 2;
cout<< "Address of c (&c): "<< &c <<endl;
cout<<"Value of c (c): "<< c<<endl<< endl;
return 0;
}
Output
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.
#include <iostream>
using namespace std;
int main() {
float a[5];
float *ptr;
return 0;
}
Output
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
#include <iostream>
using namespace std;
int main() {
float a[5];
return 0;
}
Output
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:
#include <iostream>
using namespace std;
int main() {
float a[5];
return 0;
}
Output
#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);
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);
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.
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.
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.
#include <iostream>
#include <cstring>
using namespace std;
int main() {
int n;
cout << "Enter total number of students: ";
cin >> n;
float* ptr;
Output
In this program, only memory required to store n(entered by user) number of floating-point data
is declared dynamically.
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.
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;
#include <iostream>
using namespace std;
class Test {
private:
int n;
float *ptr;
public:
Test() {
cout << "Enter total number of students: ";
cin >> n;
~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.
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).
/* 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;
}
};
};
int main()
{
cout<<"Enter data for first rectangle to find area.\n";
Area a;
cout<<"Area = "<<a.calc()<<" square meter\n\n";
Output
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
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.
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
{
.... ... ....
};
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
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.
It is because, if the name of class is not specified, the compiler thinks get_data() function is
calling itself.
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.
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
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.
#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);
}
};
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
Note: This program is intended to give you idea on how multiple inheritance works rather than
the condition in which multiple inheritance is used.
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. */
}
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.
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
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.
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.