C++ Program: 1. Type Variable - List
C++ Program: 1. Type Variable - List
C++ Program: 1. Type Variable - List
cout << "Welcome to C++ Programming." is used to print the data "Welcome to C++
Programming." on the console.
The endl is a predefined object of ostream class. It is used to insert a new line characters and
flushes the stream. A variable is a name of memory location. It is used to store data. Its value
can be changed and it can be reused many times.
It is a way to represent memory location through symbol so that it can be easily identified.
1. type variable_list;
1. int x;
2. float y;
3. char z;
Here, x, y, z are variables and int, float, char are data types.
A keyword is a reserved word. You cannot use it as a variable name, constant name etc. A
list of 32 Keywords in C++ Language which are also available in C language are given
below.
An operator is simply a symbol that is used to perform operations. There can be many types
of operations like arithmetic, logical, bitwise etc.
There are following types of operators to perform different types of operations in C language.
o Arithmetic Operators
o Relational Operators
o Logical Operators
o Bitwise Operators
o Assignment Operator
o Unary operator
o Ternary or Conditional Operator
o Misc Operator
o C++ identifiers in a program are used to refer to the name of the variables, functions,
arrays, or other user-defined data types created by the programmer. They are the basic
requirement of any language. Every language has its own rules for naming the
identifiers.
C++ identifiers represent the essential elements in a program which are given below:
o Constants
o Variables
o Functions
o Labels
o Defined data types
Identifiers Keywords
Identifiers are the names defined by the Keywords are the reserved words whose
programmer to the basic elements of a meaning is known by the compiler.
program.
It is used to identify the name of the variable. It is used to specify the type of entity.
No special character can be used except the It cannot contain any special character.
underscore.
The starting letter of identifiers can be It can be started only with the lowercase
lowercase, uppercase or underscore. letter.
Examples are test, result, sum, power, etc. Examples are 'for', 'if', 'else', 'break', etc.
An expression can consist of one or more operands, zero or more operators to compute a
value. Every expression produces some value which is assigned to the variable with the help
of an assignment operator.
1. (a+b) - c
2. (x/y) -z
3. 4a2 - 5b +c
4. (a+b) * (x+y)
o Constant expressions
o Integral expressions
o Float expressions
o Pointer expressions
o Relational expressions
o Logical expressions
o Bitwise expressions
o Special assignment expressions
o Constant expressions
o A constant expression is an expression that consists of only constant values. It is an
expression whose value is determined at the compile-time but evaluated at the run-
time. It can be composed of integer, character, floating-point, and enumeration
constants.
There are various types of if statements in C++.
o if statement
o if-else statement
o nested if statement
o if-else-if ladder
C++ IF Statement
1. if(condition){
2. //code to be executed
3. }
The C++ if-else statement also tests the condition. It executes if block if condition is true
otherwise else block is executed.
1. if(condition){
2. //code if condition is true
3. }else{
4. //code if condition is false
5. }
The C++ if-else-if ladder statement executes one condition from multiple statements.
1. if(condition1){
2. //code to be executed if condition1 is true
3. }else if(condition2){
4. //code to be executed if condition2 is true
5. }
6. else if(condition3){
7. //code to be executed if condition3 is true
8. }
9. ...
10. else{
11. //code to be executed if all the conditions are false
12. }
The C++ switch statement executes one statement from multiple conditions. It is like if-else-
if ladder statement in C++.
1. switch(expression){
2. case value1:
3. //code to be executed;
4. break;
5. case value2:
6. //code to be executed;
7. break;
8. ......
9.
10. default:
11. //code to be executed if all cases are not matched;
12. break;
13. }
1. #include <iostream>
2. using namespace std;
3. int main () {
4. int num;
5. cout<<"Enter a number to check grade:";
6. cin>>num;
7. switch (num)
8. {
9. case 10: cout<<"It is 10"; break;
10. case 20: cout<<"It is 20"; break;
11. case 30: cout<<"It is 30"; break;
12. default: cout<<"Not 10, 20 or 30"; break;
13. }
14. }
Output:
Enter a number:
10
It is 10
The C++ for loop is used to iterate a part of the program several times. If the number of
iteration is fixed, it is recommended to use for loop than while or do-while loops.
The C++ for loop is same as C/C#. We can initialize variable, check condition and
increment/decrement value.
Flowchart:
1. #include <iostream>
2. using namespace std;
3. int main() {
4. for(int i=1;i<=10;i++){
5. cout<<i <<"\n";
6. }
7. }
In C++, we can use for loop inside another for loop, it is known as nested for loop. The inner
loop is executed fully when outer loop is executed one time. So if outer loop and inner loop
are executed 4 times, inner loop will be executed 4 times for each outer loop i.e. total 16
times.
1. #include <iostream>
2. using namespace std;
3.
4. int main () {
5. for(int i=1;i<=3;i++){
6. for(int j=1;j<=3;j++){
7. cout<<i<<" "<<j<<"\n";
8. }
9. }
10. }
n C++, while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed, it is recommended to use while loop than for loop.
1. while(condition){
2. //code to be executed
3. }
Flowchart:
C++ While Loop Example
1. #include <iostream>
2. using namespace std;
3. int main() {
4. int i=1;
5. while(i<=10)
6. {
7. cout<<i <<"\n";
8. i++;
9. }
10. }
Output:
1
2
3
4
5
6
7
8
9
10
In C++, we can use while loop inside another while loop, it is known as nested while loop.
The nested while loop is executed fully when outer loop is executed once.
Let's see a simple example of nested while loop in C++ programming language.
1. #include <iostream>
2. using namespace std;
3. int main () {
4. int i=1;
5. while(i<=3)
6. {
7. int j = 1;
8. while (j <= 3)
9. {
10. cout<<i<<" "<<j<<"\n";
11. j++;
12. }
13. i++;
14. }
15. }
Output:
11
12
13
21
22
23
31
32
33
The C++ do-while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed and you must have to execute the loop at least once, it is recommended
to use do-while loop.
The C++ do-while loop is executed at least once because condition is checked after loop
body.
1. do{
2. //code to be executed
3. }while(condition);
Flowchart:
C++ do-while Loop Example
Let's see a simple example of C++ do-while loop to print the table of 1.
1. #include <iostream>
2. using namespace std;
3. int main() {
4. int i = 1;
5. do{
6. cout<<i<<"\n";
7. i++;
8. } while (i <= 10) ;
9. }
Output:
1
2
3
4
5
6
7
8
9
10
In C++, if you use do-while loop inside another do-while loop, it is known as nested do-while
loop. The nested do-while loop is executed fully for each outer do-while loop.
Let's see a simple example of nested do-while loop in C++.
1. #include <iostream>
2. using namespace std;
3. int main() {
4. int i = 1;
5. do{
6. int j = 1;
7. do{
8. cout<<i<<"\n";
9. j++;
10. } while (j <= 3) ;
11. i++;
12. } while (i <= 3) ;
13. }
Output:
11
12
13
21
22
23
31
32
33
The C++ break is used to break loop or switch statement. It breaks the current flow of the
program at the given condition. In case of inner loop, it breaks only inner loop.
1. jump-statement;
2. break;
Flowchart:
C++ Break Statement Example
Let's see a simple example of C++ break statement which is used inside the loop.
1. #include <iostream>
2. using namespace std;
3. int main() {
4. for (int i = 1; i <= 10; i++)
5. {
6. if (i == 5)
7. {
8. break;
9. }
10. cout<<i<<"\n";
11. }
12. }
Output:
1
2
3
4
The C++ break statement breaks inner loop only if you use break statement inside the inner
loop.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. for(int i=1;i<=3;i++){
6. for(int j=1;j<=3;j++){
7. if(i==2&&j==2){
8. break;
9. }
10. cout<<i<<" "<<j<<"\n";
11. }
12. }
13. }
Output:
11
12
13
21
31
32
33
The C++ continue statement is used to continue loop. It continues the current flow of the
program and skips the remaining code at specified condition. In case of inner loop, it
continues only inner loop.
1. jump-statement;
2. continue;
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. for(int i=1;i<=10;i++){
6. if(i==5){
7. continue;
8. }
9. cout<<i<<"\n";
10. }
11. }
Output:
1
2
3
4
6
7
8
9
10
C++ Continue Statement continues inner loop only if you use continue statement inside the
inner loop.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. for(int i=1;i<=3;i++){
6. for(int j=1;j<=3;j++){
7. if(i==2&&j==2){
8. continue;
9. }
10. cout<<i<<" "<<j<<"\n";
11. }
12. }
13. }
Output:
11
12
13
21
23
31
32
33
The C++ comments are statements that are not executed by the compiler. The comments in
C++ programming can be used to provide explanation of the code, variable, method or class.
By the help of comments, you can hide the program code also.
The single line comment starts with // (double slash). Let's see an example of single line
comment in C++.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x = 11; // x is a variable
6. cout<<x<<"\n";
7. }
Output:
11
The C++ multi line comment is used to comment multiple lines of code. It is surrounded by
slash and asterisk (/∗ ..... ∗/). Let's see an example of multi line comment in C++.
1. #include <ostream>
2. using namespace std;
3. int main()
4. {
5. /* declare and
6. print variable in C++. */
7. int x = 35;
8. cout<<x<<"\n";
9. }
Output:
35
A collection of related data items stored in adjacent memory places is referred to as an array
in the C/C++ programming language or any other programming language for that matter.
Elements of an array can be accessed arbitrarily using its indices. They can be used to store a
collection of any type of primitive data type, including int, float, double, char, etc. An array
in C/C++ can also store derived data types like structures, pointers, and other data types,
which is an addition. The array representation in a picture is provided below.
o Fixed size
Let's see a simple example of C++ array, where we are going to create, initialize and traverse
array.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
6. //traversing array
7. for (int i = 0; i < 5; i++)
8. {
9. cout<<arr[i]<<"\n";
10. }
11. }
Output:
10
0
20
0
30
We can also traverse the array elements using foreach loop. It returns array element one by
one.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
6. //traversing array
7. for (int i: arr)
8. {
9. cout<<i<<"\n";
10. }
11. }
Output:
10
20
30
40
50
Each element in this kind of array is described by two indexes, the first of which denotes a
row and the second of which denotes a column.
As you can see, the components are arranged in a two-dimensional array using rows and
columns; there are I number of rows and j number of columns.
A two-dimensional array is the most basic type of multidimensional array; it also qualifies as
a multidimensional array. There are no restrictions on the array's dimensions.
1. #include <iostream>
2. using namespace std;
3. int main() {
4. // initialize an array without specifying the size
5. double numbers[] = {7, 5, 6, 12, 35, 27};
6. double sum = 0;
7. double count = 0;
8. double average;
9. cout << "The numbers are: ";
10. // print array elements
11. // use of range-based for loop
12. for (const double &n : numbers) {
13. cout << n << " ";
14. // calculate the sum
15. sum += n;
16. // count the no. of array elements
17. ++count;
18. }
19. // print the sum
20. cout << "\nTheir Sum = " << sum << endl;
21. // find the average
22. average = sum / count;
23. cout << "Their Average = " << average << endl;
24.
25. return 0;
26. }
Output:
1. #include <iostream>
2. using namespace std;
3. int main() {
4. int numbers[5] = {7, 5, 6, 12, 35};
5. cout << "The numbers are: ";
6. // Printing array elements
7. // using range-based for loop
8. for (const int &n : numbers) {
9. cout << n << " ";
10. }
11. cout << "\nThe numbers are: ";
12. // Printing array elements
13. // using traditional for loop
14. for (int i = 0; i < 5; ++i) {
15. cout << numbers[i] << " ";
16. }
17. return 0;
18. }
Output:
In C++, to reuse the array logic, we can create function. To pass array to function in C++, we
need to provide only array name.
Let's see an example of C++ function which prints the array elements.
1. #include <iostream>
2. using namespace std;
3. void printArray(int arr[5]);
4. int main()
5. {
6. int arr1[5] = { 10, 20, 30, 40, 50 };
7. int arr2[5] = { 5, 15, 25, 35, 45 };
8. printArray(arr1); //passing array to function
9. printArray(arr2);
10. }
11. void printArray(int arr[5])
12. {
13. cout << "Printing array elements:"<< endl;
14. for (int i = 0; i < 5; i++)
15. {
16. cout<<arr[i]<<"\n";
17. }
18. }
Output:
Let's see an example of C++ array which prints minimum number in an array using function.
1. #include <iostream>
2. using namespace std;
3. void printMin(int arr[5]);
4. int main()
5. {
6. int arr1[5] = { 30, 10, 20, 40, 50 };
7. int arr2[5] = { 5, 15, 25, 35, 45 };
8. printMin(arr1);//passing array to function
9. printMin(arr2);
10. }
11. void printMin(int arr[5])
12. {
13. int min = arr[0];
14. for (int i = 0; i > 5; i++)
15. {
16. if (min > arr[i])
17. {
18. min = arr[i];
19. }
20. }
21. cout<< "Minimum element is: "<< min <<"\n";
22. }
Output:
Let's see an example of C++ array which prints maximum number in an array using function.
1. #include <iostream>
2. using namespace std;
3. void printMax(int arr[5]);
4. int main()
5. {
6. int arr1[5] = { 25, 10, 54, 15, 40 };
7. int arr2[5] = { 12, 23, 44, 67, 54 };
8. printMax(arr1); //Passing array to function
9. printMax(arr2);
10. }
11. void printMax(int arr[5])
12. {
13. int max = arr[0];
14. for (int i = 0; i < 5; i++)
15. {
16. if (max < arr[i])
17. {
18. max = arr[i];
19. }
20. }
21. cout<< "Maximum element is: "<< max <<"\n";
22. }
Output:
Syntax
1. datatype *var_name;
2. int *ptr; // ptr can point to an address which holds int data
Since the data type knows how many bytes the information is held in, we associate it with a
reference. The size of the data type to which a pointer points is added when we increment a
pointer.
Advantage of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving strings,
trees etc. and used with arrays, structures and functions.
3) It makes you able to access any memory location in the computer's memory.
Usage of pointer
In c language, we can dynamically allocate memory using malloc() and calloc() functions
where pointer is used.
Pointers in c language are widely used in arrays, functions and structures. It reduces the code
and improves the performance.
Declaring a pointer
Pointer Example
Let's see the simple example of using pointers printing the address and value.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int number=30;
6. int ∗ p;
7. p=&number;//stores the address of number variable
8. cout<<"Address of number variable is:"<<&number<<endl;
9. cout<<"Address of p variable is:"<<p<<endl;
10. cout<<"Value of p variable is:"<<*p<<endl;
11. return 0;
12. }
Output:
Address of number variable is:0x7ffccc8724c4
Address of p variable is:0x7ffccc8724c4
Value of p variable is:30
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=20,b=10,∗p1=&a,∗p2=&b;
6. cout<<"Before swap: ∗p1="<<∗p1<<" ∗p2="<<∗p2<<endl;
7. ∗p1=∗p1+∗p2;
8. ∗p2=∗p1-∗p2;
9. ∗p1=∗p1-∗p2;
10. cout<<"After swap: ∗p1="<<∗p1<<" ∗p2="<<∗p2<<endl;
11. return 0;
12. }
Output:
This unique type of pointer, which is available in C++, stands in for the lack of a kind.
Pointers that point to a value that has no type are known as void pointers (and thus also an
undetermined length and undetermined dereferencing properties). This indicates that void
pointers are very flexible because they can point to any data type. This flexibility has
benefits. Direct dereference is not possible with these pointers. Before they may be
dereferenced, they must be converted into another pointer type that points to a specific data
type.
A pointer must point to a valid address, not necessarily to useful items (like for arrays). We
refer to these as incorrect pointers. Additionally, incorrect pointers are uninitialized pointers.
1. int *ptr1;
2. int arr[10];
3. int *ptr2 = arr+20;
Here, ptr1 is not initialized, making it invalid, and ptr2 is outside of the bounds of arr, making
it likewise weak. (Take note that not all build failures are caused by faulty references.)
A null pointer is not merely an incorrect address; it also points nowhere. Here are two ways
to mark a pointer as NULL:
1. int *ptr1 = 0;
2. int *ptr2 = NULL;
In C++, we have the ability to build a pointer to another pointer, which might then point to
data or another pointer. The unary operator (*) is all that is needed in the syntax for declaring
the pointer for each level of indirection.
1. char a;
2. char *b;
3. char ** c;
4. a = 'g';
5. b = &a;
6. c = &b;
Here b points to a char that stores 'g', and c points to the pointer b.
1. Call-By-Value
2. Call-By-Reference with a Pointer Argument
3. Call-By-Reference with a Reference Argument
Example
1. #include
2. using namespace std;
3. // Pass-by-Value
4. int square1(int n)
5. {cout << "address of n1 in square1(): " << &n << "\n";
6. n *= n;
7. return n;
8. }
9. // Pass-by-Reference with Pointer Arguments
10. void square2(int* n)
11. {
12. cout << "address of n2 in square2(): " << n << "\n";
13. *n *= *n;
14. }
15. // Pass-by-Reference with Reference Arguments
16. void square3(int& n)
17. {
18.
19. cout << "address of n3 in square3(): " << &n << "\n";
20. n *= n;
21. }
22. void example()
23. {
24. // Call-by-Value
25. int n1 = 8;
26. cout << "address of n1 in main(): " << &n1 << "\n";
27. cout << "Square of n1: " << square1(n1) << "\n";
28. cout << "No change in n1: " << n1 << "\n";
29.
30. // Call-by-Reference with Pointer Arguments
31. int n2 = 8;
32. cout << "address of n2 in main(): " << &n2 << "\n";
33. square2(&n2);
34. cout << "Square of n2: " << n2 << "\n";
35. cout << "Change reflected in n2: " << n2 << "\n";
36.
37. // Call-by-Reference with Reference Arguments
38. int n3 = 8;
39. cout << "address of n3 in main(): " << &n3 << "\n";
40. square3(n3);
41. cout << "Square of n3: " << n3 << "\n";
42. cout << "Change reflected in n3: " << n3 << "\n";
43. }
44. // Driver program
45. int main() { example(); }
Output
The sizeof() is an operator that evaluates the size of data type, constants, variable. It is a
compile-time operator as it returns the size of any variable or a constant at the compilation
time.
The size, which is calculated by the sizeof() operator, is the amount of RAM occupied in the
computer.
1. sizeof(data_type);
In the above syntax, the data_type can be the data type of the data, variables, constants,
unions, structures, or any other user-defined data type.
If the parameter of a sizeof() operator contains the data type of a variable, then
the sizeof() operator will return the size of the data type.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. // Determining the space in bytes occupied by each data type.
6. std::cout << "Size of integer data type : " <<sizeof(int)<< std::endl;
7. std::cout << "Size of float data type : " <<sizeof(float)<< std::endl;
8. std::cout << "Size of double data type : " <<sizeof(double)<< std::endl;
9. std::cout << "Size of char data type : " <<sizeof(char)<< std::endl;
10. return 0;
11. }
In the above program, we have evaluated the size of the in-built data types by using the
sizeof() operator. As we know that int occupies 4 bytes, float occupies 4 bytes, double
occupies 8 bytes, and char occupies 1 byte, and the same result is shown by the sizeof()
operator as we can observe in the following output.
Output
1. #include <iostream>
2. using namespace std;
3. class Base
4. {
5. int a;
6. };
7. int main()
8. {
9. Base b;
10. std::cout << "Size of class base is : "<<sizeof(b) << std::endl;
11. return 0;
12. }
In the above program, we have evaluated the size of the class, which is having a single
integer variable. The output would be 4 bytes as int variable occupies 4 bytes.
Output
If we add one more integer variable in a class, then the code would look like:
1. #include <iostream>
2. using namespace std;
3. class Base
4. {
5. int a;
6. int d;
7. };
8. int main()
9. {
10. Base b;
11. std::cout << "Size of class base is : "<<sizeof(b) << std::endl;
12. return 0;
13. }
In the above code, we have added one more integer variable. In this case, the size of the class
would be 8 bytes as int variable occupies 4 bytes, so two integer variables occupy 8 bytes.
Output
If we add a char variable in the above code, then the code would look like:
1. #include <iostream>
2.
3. using namespace std;
4.
5. class Base
6. {
7. int a;
8. int d;
9. char ch;
10. };
11. int main()
12. {
13. Base b;
14. std::cout << "Size of class base is : "<<sizeof(b) << std::endl;
15. return 0;
16. }
In the above code, the class has two integer variables, and one char variable. According to
our calculation, the size of the class would be equal to 9 bytes (int+int+char), but this is
wrong due to the concept of structure padding.
Output
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int arr[]={10,20,30,40,50};
6. std::cout << "Size of the array 'arr' is : "<<sizeof(arr) << std::endl;
7. return 0;
8. }
In the above program, we have declared an array of integer type which contains five
elements. We have evaluated the size of the array by using sizeof() operator. According to
our calculation, the size of the array should be 20 bytes as int data type occupies 4 bytes, and
array contains 5 elements, so total memory space occupied by this array is 5*4 = 20 bytes.
The same result has been shown by the sizeof() operator as we can observe in the following
output.
Output
1. #include <iostream>
2. using namespace std;
3. void fun(int arr[])
4. {
5. std::cout << "Size of array is : " <<sizeof(arr)<< std::endl;
6. }
7. int main()
8. {
9. int arr[]={10,20,30,40,50};
10. fun(arr);
11. return 0;
12. }
In the above program, we have tried to print the size of the array using the function. In this
case, we have created an array of type integer, and we pass the 'arr' to the function fun().
The fun() would return the size of the integer pointer, i.e., int*, and the size of the int* is 8
bytes in the 64-bit operating system.
Output
o When an operand is of pointer type.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int *ptr1=new int(10);
6. std::cout << "size of ptr1 : " <<sizeof(ptr1)<< std::endl;
In the above program, we have determined the size of pointers. The size of pointers would
remain same for all the data types. If the computer has 32bit operating system, then the size
of the pointer would be 4 bytes. If the computer has 64-bit operating system, then the size of
the pointer would be 8 bytes. I am running this program on 64-bit, so the output would be 8
bytes. Now, if we provide the '*' symbol to the pointer, then the output depends on the data
type, for example, *ptr1 is of integer type means the sizeof() operator will return 4 bytes as
int data type occupies 4 bytes.
Output
In the above program, we have declared two variables num1 and num2 of type int and
double, respectively. The size of the int is 4 bytes, while the size of double is 8 bytes. The
result would be the variable, which is of double type occupying 8 bytes.
Output
Array and pointers are closely related to each other. In C++, the name of an array is
considered às a pointer, i.e., the name of an array contains the address of an element. C++
considers the array name as the address of the first element. For example, if we create an
array, i.e., marks which hold the 20 values of integer type, then marks will contain the
address of first element, i.e., marks[0]. Therefore, we can say that array name (marks) is a
pointer which is holding the address of the first element of an array.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int *ptr; // integer pointer declaration
6. int marks[10]; // marks array declaration
7. std::cout << "Enter the elements of an array :" << std::endl;
8. for(int i=0;i<10;i++)
9. {
10. cin>>marks[i];
11. }
12. ptr=marks; // both marks and ptr pointing to the same element..
13. std::cout << "The value of *ptr is :" <<*ptr<< std::endl;
14. std::cout << "The value of *marks is :" <<*marks<<std::endl;
15. }
In the above code, we declare an integer pointer and an array of integer type. We assign the
address of marks to the ptr by using the statement ptr=marks; it means that both the variables
'marks' and 'ptr' point to the same element, i.e., marks[0]. When we try to print the values of
*ptr and *marks, then it comes out to be same. Hence, it is proved that the array name stores
the address of the first element of an array.
Output
Array of Pointers
An array of pointers is an array that consists of variables of pointer type, which means that
the variable is a pointer addressing to some other element. Suppose we create an array of
pointer holding 5 integer pointers; then its declaration would look like:
In the above declaration, we declare an array of pointer named as ptr, and it allocates 5
integer pointers in memory.
The element of an array of a pointer can also be initialized by assigning the address of some
other element. Let's observe this case through an example.
1. int a; // variable declaration.
2. ptr[2] = &a;
In the above code, we are assigning the address of 'a' variable to the third element of an array
'ptr'.
1. *ptr[2];
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int ptr1[5]; // integer array declaration
6. int *ptr2[5]; // integer array of pointer declaration
7. std::cout << "Enter five numbers :" << std::endl;
8. for(int i=0;i<5;i++)
9. {
10. std::cin >> ptr1[i];
11. }
12. for(int i=0;i<5;i++)
13. {
14. ptr2[i]=&ptr1[i];
15. }
16. // printing the values of ptr1 array
17. std::cout << "The values are" << std::endl;
18. for(int i=0;i<5;i++)
19. {
20. std::cout << *ptr2[i] << std::endl;
21. }
22. }
In the above code, we declare an array of integer type and an array of integer pointers. We
have defined the 'for' loop, which iterates through the elements of an array 'ptr1', and on each
iteration, the address of element of ptr1 at index 'i' gets stored in the ptr2 at index 'i'.
Output
Till now, we have learnt the array of pointers to an integer. Now, we will see how to create
the array of pointers to strings.
An array of pointer to strings is an array of character pointers that holds the address of the
first character of a string or we can say the base address of a string.
The following are the differences between an array of pointers to string and two-dimensional
array of characters:
In the above case, each element of the 'names' array is a string literal, and each string literal
would hold the base address of the first character of a string. For example, names[0] contains
the base address of "john", names[1] contains the base address of "Peter", and so on. It is not
guaranteed that all the string literals will be stored in the contiguous memory location, but the
characters of a string literal are stored in a contiguous memory location.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. char *names[5] = {"john",
6. "Peter",
7. "Marco",
8. "Devin",
9. "Ronan"};
10. for(int i=0;i<5;i++)
11. {
12. std::cout << names[i] << std::endl;
13. }
14. return 0;
15. }
In the above code, we have declared an array of char pointer holding 5 string literals, and the
first character of each string is holding the base address of the string.
Output
A void pointer is a general-purpose pointer that can hold the address of any data type, but it is
not associated with any data type.
1. void *ptr;
In C++, we cannot assign the address of a variable to the variable of a different data type.
Consider the following example:
In the above example, we declare a pointer of type integer, i.e., ptr and a float variable, i.e.,
'a'. After declaration, we try to store the address of 'a' variable in 'ptr', but this is not possible
in C++ as the variable cannot hold the address of different data types.
1. #include <iostream.h>
2. using namespace std;
3. int main()
4. {
5. int *ptr;
6. float f=10.3;
7. ptr = &f; // error
8. std::cout << "The value of *ptr is : " <<*ptr<< std::endl;
9. return 0;
10. }
In the above program, we declare a pointer of integer type and variable of float type. An
integer pointer variable cannot point to the float variable, but it can point to an only integer
variable.
Output
C++ has overcome the above problem by using the C++ void pointer as a void pointer can
hold the address of any data type.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. void *ptr; // void pointer declaration
6. int a=9; // integer variable initialization
7. ptr=&a; // storing the address of 'a' variable in a void pointer variable.
8. std::cout << &a << std::endl;
9. std::cout << ptr << std::endl;
10. return 0;
11. }
In the above program, we declare a void pointer variable and an integer variable where the
void pointer contains the address of an integer variable.
Output
Difference between void pointer in C and C++
In C, we can assign the void pointer to any other pointer type without any typecasting,
whereas in C++, we need to typecast when we assign the void pointer type to any other
pointer type.
In C,
1. #include <stdio.h>
2. int main()
3. {
4. void *ptr; // void pointer declaration
5. int *ptr1; // integer pointer declaration
6. int a =90; // integer variable initialization
7. ptr=&a; // storing the address of 'a' in ptr
8. ptr1=ptr; // assigning void pointer to integer pointer type.
9. printf("The value of *ptr1 : %d",*ptr1);
10. return 0;
11. }
In the above program, we declare two pointers 'ptr' and 'ptr1' of type void and integer,
respectively. We also declare the integer type variable, i.e., 'a'. After declaration, we assign
the address of 'a' variable to the pointer 'ptr'. Then, we assign the void pointer to the integer
pointer, i.e., ptr1 without any typecasting because in C, we do not need to typecast while
assigning the void pointer to any other type of pointer.
Output
In C++,
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. void *ptr; // void pointer declaration
6. int *ptr1; // integer pointer declaration
7. int data=10; // integer variable initialization
8. ptr=&data; // storing the address of data variable in void pointer variable
9. ptr1=(int *)ptr; // assigning void pointer to integer pointer
10. std::cout << "The value of *ptr1 is : " <<*ptr1<< std::endl;
11. return 0;
12. }
In the above program, we declare two pointer variables of type void and int type respectively.
We also create another integer type variable, i.e., 'data'. After declaration, we store the
address of variable 'data' in a void pointer variable, i.e., ptr. Now, we want to assign the void
pointer to integer pointer, in order to do this, we need to apply the cast operator, i.e., (int *) to
the void pointer variable. This cast operator tells the compiler which type of value void
pointer is holding. For casting, we have to type the data type and * in a bracket like (char *)
or (int *).
Output
As we know that pointers are used to point some variables; similarly, the function pointer is a
pointer used to point functions. It is basically used to store the address of a function. We can
call the function by using the function pointer, or we can also pass the pointer to another
function as a parameter.
They are mainly useful for event-driven applications, callbacks, and even for storing the
functions in arrays.
All the functions and machine code instructions are data. This data is a bunch of bytes, and
all these bytes have some address in RAM. The function pointer contains RAM address of the
first instruction of a function.
The above syntax is the function declaration. As functions are not simple as variables, but C+
+ is a type safe, so function pointers have return type and parameter list. In the above syntax,
we first supply the return type, and then the name of the pointer, i.e., FuncPtr which is
surrounded by the brackets and preceded by the pointer symbol, i.e., (*). After this, we have
supplied the parameter list (int,int). The above function pointer can point to any function
which takes two integer parameters and returns integer type value.
Address of a function
We can get the address of a function very easily. We just need to mention the name of the
function, we do not need to call the function.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. std::cout << "Address of a main() function is : " <<&main<< std::endl;
6. return 0;
7. }
In the above program, we are displaying the address of a main() function. To print the address
of a main() function, we have just mentioned the name of the function, there is no bracket not
parameters. Therefore, the name of the function by itself without any brackets or parameters
means the address of a function.
We can use the alternate way to print the address of a function, i.e., &main.
We can call the function with the help of a function pointer by simply using the name of the
function pointer. The syntax of calling the function through the function pointer would be
similar as we do the calling of the function normally.
1. #include <iostream>
2. using namespace std;
3. int add(int a , int b)
4. {
5. return a+b;
6. }
7. int main()
8. {
9. int (*funcptr)(int,int); // function pointer declaration
10. funcptr=add; // funcptr is pointing to the add function
11. int sum=funcptr(5,5);
12. std::cout << "value of sum is :" <<sum<< std::endl;
13. return 0;
14. }
In the above program, we declare the function pointer, i.e., int (*funcptr)(int,int) and then we
store the address of add() function in funcptr. This implies that funcptr contains the address of
add() function. Now, we can call the add() function by using funcptr. The statement
funcptr(5,5) calls the add() function, and the result of add() function gets stored in sum
variable.
Output:
Let's look at another example of function pointer.
1. #include <iostream>
2. using namespace std;
3. void printname(char *name)
4. {
5. std::cout << "Name is :" <<name<< std::endl;
6. }
7.
8. int main()
9. {
10. char s[20]; // array declaration
11. void (*ptr)(char*); // function pointer declaration
12. ptr=printname; // storing the address of printname in ptr.
13. std::cout << "Enter the name of the person: " << std::endl;
14. cin>>s;
15. cout<<s;
16. ptr(s); // calling printname() function
17. return 0;
18. }
In the above program, we define the function printname() which contains the char pointer as a
parameter. We declare the function pointer, i.e., void (*ptr)(char*). The statement
ptr=printname means that we are assigning the address of printname() function to ptr. Now,
we can call the printname() function by using the statement ptr(s).
Output:
Passing a function pointer as a parameter
1. #include <iostream>
2. using namespace std;
3. void func1()
4. {
5. cout<<"func1 is called";
6. }
7. void func2(void (*funcptr)())
8. {
9. funcptr();
10. }
11. int main()
12. {
13. func2(func1);
14. return 0;
15. }
In the above code, the func2() function takes the function pointer as a parameter. The main()
method calls the func2() function in which the address of func1() is passed. In this way, the
func2() function is calling the func1() indirectly.
Output:
The major purpose of C++ programming is to introduce the concept of object orientation to
the C programming language.
Object means a real word entity such as pen, chair, table etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and objects.
It simplifies the software development and maintenance by providing some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
Class
Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known
as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
1. Sub class - Subclass or Derived Class refers to a class that receives properties from
another class.
2. Super class - The term "Base Class" or "Super Class" refers to the class from which a
subclass inherits its properties.
3. Reusability - As a result, when we wish to create a new class, but an existing class
already contains some of the code we need, we can generate our new class from the
old class thanks to inheritance. This allows us to utilize the fields and methods of the
pre-existing class.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example:
to convince the customer differently, to draw something e.g. shape or rectangle etc.
Different situations may cause an operation to behave differently. The type of data utilized in
the operation determines the behavior.
Abstraction
Hiding internal details and showing functionality is known as abstraction. Data abstraction
is the process of exposing to the outside world only the information that is absolutely
necessary while concealing implementation or background information.For example: phone
call, we don't know the internal processing.
Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different medicines.
Dynamic Binding - In dynamic binding, a decision is made at runtime regarding the code
that will be run in response to a function call. For this, C++ supports virtual functions.
C++ Object
In C++, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc.
In other words, object is an entity that has state and behavior. Here, state means data and
behavior means functionality.
Let's see an example to create object of student class using s1 as the reference variable.
In this example, Student is the type and s1 is the reference variable that refers to the instance
of Student class.
C++ Class
In C++, class is a group of similar objects. It is a template from which objects are created. It
can have fields, methods, constructors etc.
Let's see an example of C++ class that has three fields only.
1. class Student
2. {
3. public:
4. int id; //field or data member
5. float salary; //field or data member
6. String name;//field or data member
7. }
Let's see an example of class that has two fields: id and name. It creates instance of the class,
initializes the object and prints the object value.
1. #include <iostream>
2. using namespace std;
3. class Student {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. };
8. int main() {
9. Student s1; //creating an object of Student
10. s1.id = 201;
11. s1.name = "Sonoo Jaiswal";
12. cout<<s1.id<<endl;
13. cout<<s1.name<<endl;
14. return 0;
15. }
Output:
201
Sonoo Jaiswal
Let's see another example of C++ class where we are initializing and displaying object
through method.
1. #include <iostream>
2. using namespace std;
3. class Student {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. void insert(int i, string n)
8. {
9. id = i;
10. name = n;
11. }
12. void display()
13. {
14. cout<<id<<" "<<name<<endl;
15. }
16. };
17. int main(void) {
18. Student s1; //creating an object of Student
19. Student s2; //creating an object of Student
20. s1.insert(201, "Sonoo");
21. s2.insert(202, "Nakul");
22. s1.display();
23. s2.display();
24. return 0;
25. }
Output:
201 Sonoo
202 Nakul
Let's see another example of C++ class where we are storing and displaying employee
information using method.
1. #include <iostream>
2. using namespace std;
3. class Employee {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. float salary;
8. void insert(int i, string n, float s)
9. {
10. id = i;
11. name = n;
12. salary = s;
13. }
14. void display()
15. {
16. cout<<id<<" "<<name<<" "<<salary<<endl;
17. }
18. };
19. int main(void) {
20. Employee e1; //creating an object of Employee
21. Employee e2; //creating an object of Employee
22. e1.insert(201, "Sonoo",990000);
23. e2.insert(202, "Nakul", 29000);
24. e1.display();
25. e2.display();
26. return 0;
27. }
Output:
201 Sonoo 990000
202 Nakul 29000
C++ Inheritance
In C++, inheritance is a process in which one object acquires all the properties and behaviors
of its parent object automatically. In such way, you can reuse, extend or modify the attributes
and behaviors which are defined in other class.
In C++, the class which inherits the members of another class is called derived class and the
class whose members are inherited is called base class. The derived class is the specialized
class for the base class.
Code reusability: Now you can reuse the members of your parent class. So, there is no need
to define the member again. So less code is required in the class.
Types Of Inheritance
o Single inheritance
o Multiple inheritance
o Hierarchical inheritance
o Multilevel inheritance
o Hybrid inheritance
Derived Classes
A Derived class is defined as the class derived from the base class.
The Syntax of Derived class:
Where,
visibility mode: The visibility mode specifies whether the features of the base class are
publicly inherited or privately inherited. It can be public or private.
o When the base class is privately inherited by the derived class, public members of the
base class becomes the private members of the derived class. Therefore, the public
members of the base class are not accessible by the objects of the derived class only
by the member functions of the derived class.
o When the base class is publicly inherited by the derived class, public members of the
base class also become the public members of the derived class. Therefore, the public
members of the base class are accessible by the objects of the derived class as well as
by the member functions of the base class.
Note:
Single inheritance is defined as the inheritance in which a derived class is inherited from the
only one base class.
Where 'A' is the base class, and 'B' is the derived class.
When one class inherits another class, it is known as single level inheritance. Let's see the
example of single level inheritance which inherits the fields only.
1. #include <iostream>
2. using namespace std;
3. class Account {
4. public:
5. float salary = 60000;
6. };
7. class Programmer: public Account {
8. public:
9. float bonus = 5000;
10. };
11. int main(void) {
12. Programmer p1;
13. cout<<"Salary: "<<p1.salary<<endl;
14. cout<<"Bonus: "<<p1.bonus<<endl;
15. return 0;
16. }
Output:
Salary: 60000
Bonus: 5000
In the above example, Employee is the base class and Programmer is the derived class.
Let's see another example of inheritance in C++ which inherits methods only.
1. #include <iostream>
2. using namespace std;
3. class Animal {
4. public:
5. void eat() {
6. cout<<"Eating..."<<endl;
7. }
8. };
9. class Dog: public Animal
10. {
11. public:
12. void bark(){
13. cout<<"Barking...";
14. }
15. };
16. int main(void) {
17. Dog d1;
18. d1.eat();
19. d1.bark();
20. return 0;
21. }
Output:
Eating...
Barking...
1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. int a = 4;
6. int b = 5;
7. public:
8. int mul()
9. {
10. int c = a*b;
11. return c;
12. }
13. };
14.
15. class B : private A
16. {
17. public:
18. void display()
19. {
20. int result = mul();
21. std::cout <<"Multiplication of a and b is : "<<result<< std::endl;
22. }
23. };
24. int main()
25. {
26. B b;
27. b.display();
28.
29. return 0;
30. }
Output:
Multiplication of a and b is : 20
In the above example, class A is privately inherited. Therefore, the mul() function of class 'A'
cannot be accessed by the object of class B. It can only be accessed by the member function
of class B.
The private member is not inheritable. If we modify the visibility mode by making it public,
but this takes away the advantage of data hiding.
C++ introduces a third visibility modifier, i.e., protected. The member which is declared as
protected will be accessible to all the member functions within the class as well as the class
immediately derived from it.
When one class inherits another class which is further inherited by another class, it is known
as multi level inheritance in C++. Inheritance is transitive so the last derived class acquires all
the members of all its base classes.
Let's see the example of multi level inheritance in C++.
1. #include <iostream>
2. using namespace std;
3. class Animal {
4. public:
5. void eat() {
6. cout<<"Eating..."<<endl;
7. }
8. };
9. class Dog: public Animal
10. {
11. public:
12. void bark(){
13. cout<<"Barking..."<<endl;
14. }
15. };
16. class BabyDog: public Dog
17. {
18. public:
19. void weep() {
20. cout<<"Weeping...";
21. }
22. };
23. int main(void) {
24. BabyDog d1;
25. d1.eat();
26. d1.bark();
27. d1.weep();
28. return 0;
29. }
Output:
Eating...
Barking...
Weeping...
1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. protected:
6. int a;
7. public:
8. void get_a(int n)
9. {
10. a = n;
11. }
12. };
13.
14. class B
15. {
16. protected:
17. int b;
18. public:
19. void get_b(int n)
20. {
21. b = n;
22. }
23. };
24. class C : public A,public B
25. {
26. public:
27. void display()
28. {
29. std::cout << "The value of a is : " <<a<< std::endl;
30. std::cout << "The value of b is : " <<b<< std::endl;
31. cout<<"Addition of a and b is : "<<a+b;
32. }
33. };
34. int main()
35. {
36. C c;
37. c.get_a(10);
38. c.get_b(20);
39. c.display();
40.
41. return 0;
42. }
Output:
The value of a is : 10
The value of b is : 20
Addition of a and b is : 30
In the above example, class 'C' inherits two base classes 'A' and 'B' in a public mode.
Ambiguity can be occurred in using the multiple inheritance when a function with the same
name occurs in more than one base class.
1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. public:
6. void display()
7. {
8. std::cout << "Class A" << std::endl;
9. }
10. };
11. class B
12. {
13. public:
14. void display()
15. {
16. std::cout << "Class B" << std::endl;
17. }
18. };
19. class C : public A, public B
20. {
21. void view()
22. {
23. display();
24. }
25. };
26. int main()
27. {
28. C c;
29. c.display();
30. return 0;
31. }
Output:
1. class A
2. {
3. public:
4. void display()
5. {
6. cout<<?Class A?;
7. }
8. } ;
9. class B
10. {
11. public:
12. void display()
13. {
14. cout<<?Class B?;
15. }
16. } ;
In the above case, the function of the derived class overrides the method of the base class.
Therefore, call to the display() function will simply call the function defined in the derived
class. If we want to invoke the base class function, we can use the class resolution operator.
1. int main()
2. {
3. B b;
4. b.display(); // Calling the display() function of B class.
5. b.B :: display(); // Calling the display() function defined in B class.
6. }
C++ Hybrid Inheritance
1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. protected:
6. int a;
7. public:
8. void get_a()
9. {
10. std::cout << "Enter the value of 'a' : " << std::endl;
11. cin>>a;
12. }
13. };
14.
15. class B : public A
16. {
17. protected:
18. int b;
19. public:
20. void get_b()
21. {
22. std::cout << "Enter the value of 'b' : " << std::endl;
23. cin>>b;
24. }
25. };
26. class C
27. {
28. protected:
29. int c;
30. public:
31. void get_c()
32. {
33. std::cout << "Enter the value of c is : " << std::endl;
34. cin>>c;
35. }
36. };
37.
38. class D : public B, public C
39. {
40. protected:
41. int d;
42. public:
43. void mul()
44. {
45. get_a();
46. get_b();
47. get_c();
48. std::cout << "Multiplication of a,b,c is : " <<a*b*c<< std::endl;
49. }
50. };
51. int main()
52. {
53. D d;
54. d.mul();
55. return 0;
56. }
Output:
Hierarchical inheritance is defined as the process of deriving more than one class from a base
class.
1. class A
2. {
3. // body of the class A.
4. }
5. class B : public A
6. {
7. // body of class B.
8. }
9. class C : public A
10. {
11. // body of class C.
12. }
13. class D : public A
14. {
15. // body of class D.
16. }
Output:
The term "Polymorphism" is the combination of "poly" + "morphs" which means many
forms. It is a greek word. In object-oriented programming, we use 3 main concepts:
inheritance, encapsulation, and polymorphism.
In the above case, the prototype of display() function is the same in both the base and
derived class. Therefore, the static binding cannot be applied. It would be great if the
appropriate function is selected at the run time. This is known as run time polymorphism.
o Run time polymorphism: Run time polymorphism is achieved when the object's
method is invoked at the run time instead of compile time. It is achieved by method
overriding which is also known as dynamic binding or late binding.
The function to be invoked is known at the The function to be invoked is known at the
compile time. run time.
It is less flexible as mainly all the things execute It is more flexible as all the things execute
at the compile time. at the run time.
1. #include <iostream>
2. using namespace std;
3. class Animal {
4. public:
5. void eat(){
6. cout<<"Eating...";
7. }
8. };
9. class Dog: public Animal
10. {
11. public:
12. void eat()
13. { cout<<"Eating bread...";
14. }
15. };
16. int main(void) {
17. Dog d = Dog();
18. d.eat();
19. return 0;
20. }
Output:
Eating bread...
Let's see another example of run time polymorphism in C++ where we are having two
derived classes.
1. #include <iostream>
2. using namespace std;
3. class Shape { // base class
4. public:
5. virtual void draw(){ // virtual function
6. cout<<"drawing..."<<endl;
7. }
8. };
9. class Rectangle: public Shape // inheriting Shape class.
10. {
11. public:
12. void draw()
13. {
14. cout<<"drawing rectangle..."<<endl;
15. }
16. };
17. class Circle: public Shape // inheriting Shape class.
18.
19. {
20. public:
21. void draw()
22. {
23. cout<<"drawing circle..."<<endl;
24. }
25. };
26. int main(void) {
27. Shape *s; // base class pointer.
28. Shape sh; // base class object.
29. Rectangle rec;
30. Circle cir;
31. s=&sh;
32. s->draw();
33. s=&rec;
34. s->draw();
35. s=?
36. s->draw();
37. }
Output:
drawing...
drawing rectangle...
drawing circle...
Runtime Polymorphism can be achieved by data members in C++. Let's see an example
where we are accessing the field by reference variable which refers to the instance of derived
class.
1. #include <iostream>
2. using namespace std;
3. class Animal { // base class declaration.
4. public:
5. string color = "Black";
6. };
7. class Dog: public Animal // inheriting Animal class.
8. {
9. public:
10. string color = "Grey";
11. };
12. int main(void) {
13. Animal d= Dog();
14. cout<<d.color;
15. }
Output:
Black
C++ Overloading (Function and Operator)
If we create two or more members having the same name but different in number or type of
parameter, it is known as C++ overloading. In C++, we can overload:
o methods,
o constructors, and
o indexed properties
o Function overloading
o Operator overloading
Function Overloading is defined as the process of having two or more function with the same
name, but different in parameters is known as function overloading in C++. In function
overloading, the function is redefined by using either different types of arguments or a
different number of arguments. It is only through these differences compiler can differentiate
between the functions.
The advantage of Function overloading is that it increases the readability of the program
because you don't need to use different names for the same action.
Let's see the simple example of function overloading where we are changing number of
arguments of add() method.
1. #include <iostream>
2. using namespace std;
3. class Cal {
4. public:
5. static int add(int a,int b){
6. return a + b;
7. }
8. static int add(int a, int b, int c)
9. {
10. return a + b + c;
11. }
12. };
13. int main(void) {
14. Cal C; // class object declaration.
15. cout<<C.add(10, 20)<<endl;
16. cout<<C.add(12, 20, 23);
17. return 0;
18. }
Output:
30
55
Let's see the simple example when the type of the arguments vary.
1. #include<iostream>
2. using namespace std;
3. int mul(int,int);
4. float mul(float,int);
5.
6.
7. int mul(int a,int b)
8. {
9. return a*b;
10. }
11. float mul(double x, int y)
12. {
13. return x*y;
14. }
15. int main()
16. {
17. int r1 = mul(6,7);
18. float r2 = mul(0.2,3);
19. std::cout << "r1 is : " <<r1<< std::endl;
20. std::cout <<"r2 is : " <<r2<< std::endl;
21. return 0;
22. }
Output:
r1 is : 42
r2 is : 0.6
When the compiler is unable to decide which function is to be invoked among the overloaded
function, this situation is known as function overloading.
When the compiler shows the ambiguity error, the compiler does not run the program.
o Type Conversion.
o Function with default arguments.
o Function with pass by reference.
o Type Conversion:
1. #include<iostream>
2. using namespace std;
3. void fun(int);
4. void fun(float);
5. void fun(int i)
6. {
7. std::cout << "Value of i is : " <<i<< std::endl;
8. }
9. void fun(float j)
10. {
11. std::cout << "Value of j is : " <<j<< std::endl;
12. }
13. int main()
14. {
15. fun(12);
16. fun(1.2);
17. return 0;
18. }
The above example shows an error "call of overloaded 'fun(double)' is ambiguous". The
fun(10) will call the first function. The fun(1.2) calls the second function according to our
prediction. But, this does not refer to any function as in C++, all the floating point constants
are treated as double not as a float. If we replace float to double, the program works.
Therefore, this is a type conversion from float to double.
1. #include<iostream>
2. using namespace std;
3. void fun(int);
4. void fun(int,int);
5. void fun(int i)
6. {
7. std::cout << "Value of i is : " <<i<< std::endl;
8. }
9. void fun(int a,int b=9)
10. {
11. std::cout << "Value of a is : " <<a<< std::endl;
12. std::cout << "Value of b is : " <<b<< std::endl;
13. }
14. int main()
15. {
16. fun(12);
17.
18. return 0;
19. }
The above example shows an error "call of overloaded 'fun(int)' is ambiguous". The fun(int a,
int b=9) can be called in two ways: first is by calling the function with one argument, i.e.,
fun(12) and another way is calling the function with two arguments, i.e., fun(4,5). The fun(int
i) function is invoked with one argument. Therefore, the compiler could not be able to select
among fun(int i) and fun(int a,int b=9).
1. #include <iostream>
2. using namespace std;
3. void fun(int);
4. void fun(int &);
5. int main()
6. {
7. int a=10;
8. fun(a); // error, which f()?
9. return 0;
10. }
11. void fun(int x)
12. {
13. std::cout << "Value of x is : " <<x<< std::endl;
14. }
15. void fun(int &b)
16. {
17. std::cout << "Value of b is : " <<b<< std::endl;
18. }
The above example shows an error "call of overloaded 'fun(int&)' is ambiguous". The first
function takes one integer argument and the second function takes a reference parameter as
an argument. In this case, the compiler does not know which function is needed by the user as
there is no syntactical difference between the fun(int) and fun(int &).
operator op is an operator function where op is the operator being overloaded, and the
operator is the keyword.
o Existing operators can only be overloaded, but the new operators cannot be
overloaded.
o The overloaded operator contains atleast one operand of the user-defined data type.
o We cannot use friend function to overload certain operators. However, the member
function can be used to overload those operators.
o When unary operators are overloaded through a member function take no explicit
arguments, but, if they are overloaded by a friend function, takes one argument.
o When binary operators are overloaded through a member function takes one explicit
argument, and if they are overloaded through a friend function takes two explicit
arguments.
Let's see the simple example of operator overloading in C++. In this example, void operator +
+ () operator function is defined (inside Test class).
1. #include <iostream>
2. using namespace std;
3. class Test
4. {
5. private:
6. int num;
7. public:
8. Test(): num(8){}
9. void operator ++() {
10. num = num+2;
11. }
12. void Print() {
13. cout<<"The Count is: "<<num;
14. }
15. };
16. int main()
17. {
18. Test tt;
19. ++tt; // calling of a function "void operator ++()"
20. tt.Print();
21. return 0;
22. }
Output:
1. #include <iostream>
2. using namespace std;
3. class A
4. {
5.
6. int x;
7. public:
8. A(){}
9. A(int i)
10. {
11. x=i;
12. }
13. void operator+(A);
14. void display();
15. };
16.
17. void A :: operator+(A a)
18. {
19.
20. int m = x+a.x;
21. cout<<"The result of the addition of two objects is : "<<m;
22.
23. }
24. int main()
25. {
26. A a1(5);
27. A a2(4);
28. a1+a2;
29. return 0;
30. }
Output:
o Data Abstraction is a process of providing only the essential details to the outside
world and hiding the internal details, i.e., representing only the essential details in the
program.
o Data Abstraction is a programming technique that depends on the seperation of the
interface and implementation details of the program.
o Let's take a real life example of AC, which can be turned ON or OFF, change the
temperature, change the mode, and other external components such as fan, swing.
But, we don't know the internal details of the AC, i.e., how it works internally. Thus,
we can say that AC seperates the implementation details from the external interface.
o C++ provides a great level of abstraction. For example, pow() function is used to
calculate the power of a number without knowing the algorithm the function follows.
In C++ program if we implement class with private and public members then it is an example
of data abstraction.
Abstraction in header files: An another type of abstraction is header file. For example,
pow() function available is used to calculate the power of a number without actually knowing
which algorithm function uses to calculate the power. Thus, we can say that header files hides
all the implementation details from the user.
o Public specifier: When the members are declared as public, members can be
accessed anywhere from the program.
o Private specifier: When the members are declared as private, members can only be
accessed only by the member functions of the class.
1. #include <iostream>
2. #include<math.h>
3. using namespace std;
4. int main()
5. {
6. int n = 4;
7. int power = 3;
8. int result = pow(n,power); // pow(n,power) is the power function
9. std::cout << "Cube of n is : " <<result<< std::endl;
10. return 0;
11. }
Output:
Cube of n is : 64
In the above example, pow() function is used to calculate 4 raised to the power 3. The pow()
function is present in the math.h header file in which all the implementation details of the
pow() function is hidden.
1. #include <iostream>
2. using namespace std;
3. class Sum
4. {
5. private: int x, y, z; // private variables
6. public:
7. void add()
8. {
9. cout<<"Enter two numbers: ";
10. cin>>x>>y;
11. z= x+y;
12. cout<<"Sum of two number is: "<<z<<endl;
13. }
14. };
15. int main()
16. {
17. Sum sm;
18. sm.add();
19. return 0;
20. }
Output:
In the above example, abstraction is achieved using classes. A class 'Sum' contains the private
members x, y and z are only accessible by the member functions of the class.
Advantages Of Abstraction:
o Implementation details of the class are protected from the inadvertent user level
errors.
o A programmer does not need to write the low level code.
o Data Abstraction avoids the code duplication, i.e., programmer does not have to
undergo the same tasks every time to perform the similar operation.
o The main aim of the data abstraction is to reuse the code and the proper partitioning of
the code across the classes.
o Internal implementation can be changed without affecting the user level code.
In C++, string is an object of std::string class that represents sequence of characters. We can
perform many operations on strings such as concatenation, comparison, conversion etc.
1. #include <iostream>
2. using namespace std;
3. int main( ) {
4. string s1 = "Hello";
5. char ch[] = { 'C', '+', '+'};
6. string s2 = string(ch);
7. cout<<s1<<endl;
8. cout<<s2<<endl;
9. }
Output:
Hello
C++
Let's see the simple example of string comparison using strcmp() function.
1. #include <iostream>
2. #include <cstring>
3. using namespace std;
4. int main ()
5. {
6. char key[] = "mango";
7. char buffer[50];
8. do {
9. cout<<"What is my favourite fruit? ";
10. cin>>buffer;
11. } while (strcmp (key,buffer) != 0);
12. cout<<"Answer is correct!!"<<endl;
13. return 0;
14. }
Output:
Let's see the simple example of string concatenation using strcat() function.
1. #include <iostream>
2. #include <cstring>
3. using namespace std;
4. int main()
5. {
6. char key[25], buffer[25];
7. cout << "Enter the key string: ";
8. cin.getline(key, 25);
9. cout << "Enter the buffer string: ";
10. cin.getline(buffer, 25);
11. strcat(key, buffer);
12. cout << "Key = " << key << endl;
13. cout << "Buffer = " << buffer<<endl;
14. return 0;
15. }
Output:
Enter the key string: Welcome to
Enter the buffer string: C++ Programming.
Key = Welcome to C++ Programming.
Buffer = C++ Programming.
Let's see the simple example of copy the string using strcpy() function.
1. #include <iostream>
2. #include <cstring>
3. using namespace std;
4. int main()
5. {
6. char key[25], buffer[25];
7. cout << "Enter the key string: ";
8. cin.getline(key, 25);
9. strcpy(buffer, key);
10. cout << "Key = "<< key << endl;
11. cout << "Buffer = "<< buffer<<endl;
12. return 0;
13. }
Output:
Let's see the simple example of finding the string length using strlen() function.
1. #include <iostream>
2. #include <cstring>
3. using namespace std;
4. int main()
5. {
6. char ary[] = "Welcome to C++ Programming";
7. cout << "Length of String = " << strlen(ary)<<endl;
8. return 0;
9. }
Output:
Length of String = 26
Function Description
void swap(string& str) It is used to swap the values of two string objects.
string& replace(int pos,int It replaces portion of the string that begins at character
len,string& str) position pos and spans len characters.
string& append(const string& str) It adds new characters at the end of another string
object.
int find(string& str,int pos,int n) It is used to find the string specified in the parameter.
int find_first_of(string& str,int It is used to find the first occurrence of the specified
pos,int n) sequence.
int find_first_not_of(string& It is used to search the string for the first character that
str,int pos,int n ) does not match with any of the characters specified in
the string.
int find_last_of(string& str,int It is used to search the string for the last character of
pos,int n) specified sequence.
int find_last_not_of(string& It searches for the last character that does not match
str,int pos) with the specified sequence.
void push_back(char ch) It adds a new character ch at the end of the string.
void shrink_to_fit() It reduces the capacity and makes it equal to the size of
the string.
allocator_type get_allocator(); It returns the allocated object associated with the string.
1. #include <iostream>
2. using namespace std;
3. int main() {
4. int n1=0,n2=1,n3,i,number;
5. cout<<"Enter the number of elements: ";
6. cin>>number;
7. cout<<n1<<" "<<n2<<" "; //printing 0 and 1
8. for(i=2;i<number;++i) //loop starts from 2 because 0 and 1 are already printed
9. {
10. n3=n1+n2;
11. cout<<n3<<" ";
12. n1=n2;
13. n2=n3;
14. }
15. return 0;
16. }
Output:
1. #include<iostream>
2. using namespace std;
3. void printFibonacci(int n){
4. static int n1=0, n2=1, n3;
5. if(n>0){
6. n3 = n1 + n2;
7. n1 = n2;
8. n2 = n3;
9. cout<<n3<<" ";
10. printFibonacci(n-1);
11. }
12. }
13. int main(){
14. int n;
15. cout<<"Enter the number of elements: ";
16. cin>>n;
17. cout<<"Fibonacci Series: ";
18. cout<<"0 "<<"1 ";
19. printFibonacci(n-2); //n-2 because 2 numbers are already printed
20. return 0;
21. }
Output:
In this program, we will get an input from the user and check whether number is palindrome
or not.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int n,r,sum=0,temp;
6. cout<<"Enter the Number=";
7. cin>>n;
8. temp=n;
9. while(n>0)
10. {
11. r=n%10;
12. sum=(sum*10)+r;
13. n=n/10;
14. }
15. if(temp==sum)
16. cout<<"Number is Palindrome.";
17. else
18. cout<<"Number is not Palindrome.";
19. return 0;
20. }
Output:
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int i,fact=1,number;
6. cout<<"Enter any Number: ";
7. cin>>number;
8. for(i=1;i<=number;i++){
9. fact=fact*i;
10. }
11. cout<<"Factorial of " <<number<<" is: "<<fact<<endl;
12. return 0;
13. }
Output:
1. #include<iostream>
2. using namespace std;
3. int main()
4. {
5. int factorial(int);
6. int fact,value;
7. cout<<"Enter any number: ";
8. cin>>value;
9. fact=factorial(value);
10. cout<<"Factorial of a number is: "<<fact<<endl;
11. return 0;
12. }
13. int factorial(int n)
14. {
15. if(n<0)
16. return(-1); /*Wrong value*/
17. if(n==0)
18. return(1); /*Terminating condition*/
19. else
20. {
21. return(n*factorial(n-1));
22. }
23. }
Output:
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int n,r,sum=0,temp;
6. cout<<"Enter the Number= ";
7. cin>>n;
8. temp=n;
9. while(n>0)
10. {
11. r=n%10;
12. sum=sum+(r*r*r);
13. n=n/10;
14. }
15. if(temp==sum)
16. cout<<"Armstrong Number."<<endl;
17. else
18. cout<<"Not Armstrong Number."<<endl;
19. return 0;
20. }
Output:
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int n,sum=0,m;
6. cout<<"Enter a number: ";
7. cin>>n;
8. while(n>0)
9. {
10. m=n%10;
11. sum=sum+m;
12. n=n/10;
13. }
14. cout<<"Sum is= "<<sum<<endl;
15. return 0;
16. }
Output:
Enter a number: 23
Sum is= 5
Enter a number: 624
Sum is= 12
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int n, reverse=0, rem;
6. cout<<"Enter a number: ";
7. cin>>n;
8. while(n!=0)
9. {
10. rem=n%10;
11. reverse=reverse*10+rem;
12. n/=10;
13. }
14. cout<<"Reversed Number: "<<reverse<<endl;
15. return 0;
16. }
Output:
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
6. cout<<"enter the number of row=";
7. cin>>r;
8. cout<<"enter the number of column=";
9. cin>>c;
10. cout<<"enter the first matrix element=\n";
11. for(i=0;i<r;i++)
12. {
13. for(j=0;j<c;j++)
14. {
15. cin>>a[i][j];
16. }
17. }
18. cout<<"enter the second matrix element=\n";
19. for(i=0;i<r;i++)
20. {
21. for(j=0;j<c;j++)
22. {
23. cin>>b[i][j];
24. }
25. }
26. cout<<"multiply of the matrix=\n";
27. for(i=0;i<r;i++)
28. {
29. for(j=0;j<c;j++)
30. {
31. mul[i][j]=0;
32. for(k=0;k<c;k++)
33. {
34. mul[i][j]+=a[i][k]*b[k][j];
35. }
36. }
37. }
38. //for printing result
39. for(i=0;i<r;i++)
40. {
41. for(j=0;j<c;j++)
42. {
43. cout<<mul[i][j]<<" ";
44. }
45. cout<<"\n";
46. }
47. return 0;
48. }
Output:
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a[10], n, i;
6. cout<<"Enter the number to convert: ";
7. cin>>n;
8. for(i=0; n>0; i++)
9. {
10. a[i]=n%2;
11. n= n/2;
12. }
13. cout<<"Binary of the given number= ";
14. for(i=i-1 ;i>=0 ;i--)
15. {
16. cout<<a[i];
17. }
18. }
Output:
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. long int n,sum=0,r;
6. cout<<"Enter the Number= ";
7. cin>>n;
8. while(n>0)
9. {
10. r=n%10;
11. sum=sum*10+r;
12. n=n/10;
13. }
14. n=sum;
15. while(n>0)
16. {
17. r=n%10;
18. switch(r)
19. {
20. case 1:
21. cout<<"one ";
22. break;
23. case 2:
24. cout<<"two ";
25. break;
26. case 3:
27. cout<<"three ";
28. break;
29. case 4:
30. cout<<"four ";
31. break;
32. case 5:
33. cout<<"five ";
34. break;
35. case 6:
36. cout<<"six ";
37. break;
38. case 7:
39. cout<<"seven ";
40. break;
41. case 8:
42. cout<<"eight ";
43. break;
44. case 9:
45. cout<<"nine ";
46. break;
47. case 0:
48. cout<<"zero ";
49. break;
50. default:
51. cout<<"tttt ";
52. break;
53. }
54. n=n/10;
55. }
56. }
Output: