OOP (C++) Unit1
OOP (C++) Unit1
SEM2-E1-ECE
Object Oriented Programming with C++
Unit-1:
Review of C: strings, arrays,pointers, Programming in C++, Build and
execute a C program in C++, C++ as better C: Procedural Execution of C
About C
C Programming Language
The C Language is developed by Dennis Ritchie for creating system applications that
directly interact with the hardware devices such as drivers, kernels, etc.
C programming is considered as the base for other programming languages, that is why
it is known as mother language.
1. Mother language
1) C as a mother language
C language is considered as the mother language of all the modern programming
languages because most of the compilers, JVMs, Kernels, etc. are written in C
language, and most of the programming languages follow C syntax, for example,
C++, Java, C#, etc.
It provides the core concepts like the array, strings, functions, file handling, etc. that
are being used in many languages like C++, Java, C#, etc.
It can't be used for internet programming like Java, .Net, PHP, etc.
3) C as a procedural language
A procedure is known as a function, method, routine, subroutine, etc. A procedural
language specifies a series of steps for the program to solve the problem.
A procedural language breaks the program into functions, data structures, etc.
In the C language, we break the program into parts using functions. It makes the
program easier to understand and modify.
File: main.c
Output:
Hello C Programming
History of C Language
History of C language is interesting to know. Here we are going to discuss
a brief history of the c language.
C is the widely used language. It provides many features that are given below.
1. Simple
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible
1) Simple
C is a simple language in the sense that it provides a structured approach (to break
the problem into parts), the rich set of library functions, data types, etc.
5) Rich Library
C provides a lot of inbuilt functions that make the development fast.
6) Memory Management
It supports the feature of dynamic memory allocation. In C language, we can free
the allocated memory at any time by calling the free() function.
7) Speed
The compilation and execution time of C language is fast since there are lesser inbuilt
functions and hence the lesser overhead.
8) Pointer
C provides the feature of pointers. We can directly interact with the memory by using
the pointers. We can use pointers for memory, structures, functions, array, etc.
9) Recursion
In C, we can call the function within the function. It provides code reusability for
every function. Recursion enables us to use the approach of backtracking.
10) Extensible
C language is extensible because it can easily adopt new features.
C Array
An array is defined as the collection of similar type of data items stored at contiguous
memory locations. Arrays are the derived data type in C programming language which
can store the primitive type of data such as int, char, double, float, etc. It also has the
capability to store the collection of derived data types, such as pointers, structure, etc.
The array is the simplest data structure where each data element can be randomly
accessed by using its index number.
C array is beneficial if you have to store similar elements. For example, if we want to
store the marks of a student in 6 subjects, then we don't need to define different
variables for the marks in the different subject. Instead of that, we can define an array
which can store the marks in each subject at the contiguous memory locations.
By using the array, we can access the elements easily. Only a few lines of code are
required to access the elements of the array.
Properties of Array
The array contains the following properties.
o Each element of an array is of same data type and carries the same size, i.e., int
= 4 bytes.
o Elements of the array are stored at contiguous memory locations where the first
element is stored at the smallest memory location.
o Elements of the array can be randomly accessed since we can calculate the
address of each element of the array with the given base address and the size of
the data element.
Advantage of C Array
1) Code Optimization: Less code to the access the data.
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array
easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code
only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we
can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we
will learn later.
Declaration of C Array
We can declare an array in the c language in the following way.
1. data_type array_name[array_size];
int marks[5];
Here, int is the data_type, marks are the array_name, and 5 is the array_size.
Initialization of C Array
The simplest way to initialize an array is by using the index of each element. We can initialize
each element of the array by using the index. Consider the following example.
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
C array example
Output
C Array: Declaration with Initialization
We can initialize the c array at the time of declaration. Let's see the code.
int marks[5]={20,30,40,50,60};
int marks[]={20,30,40,50,60};
1. By char array
2. By string literal
1. char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
As we know, array index starts from 0, so it will be represented as in the figure given
below.
While declaring string, size is not mandatory. So we can write the above code as given
below:
In such case, '\0' will be appended at the end of the string by the compiler.
Difference between char array and string literal
There are two main differences between char array and literal.
o We need to add the null character '\0' at the end of the array by ourself
whereas, it is appended internally by the compiler in the case of the character
array.
String Example in C
Let's see a simple example where a string is declared and being printed. The
'%s' is used as a format specifier for the string in c language.
Traversing String
Traversing the string is one of the most important aspects in any of the programming
languages. We may need to manipulate a very large text which can be done by
traversing the text. Traversing string is somewhat different from the traversing an
integer array. We need to know the length of the array to traverse an integer array,
whereas we may use the null character in the case of string to identify the end the
string and terminate the loop.
Output
o The compiler doesn't perform bounds checking on the character array. Hence,
there can be a case where the length of the string can exceed the dimension of
the character array which may always overwrite some important data.
o Instead of using scanf, we may use gets() which is an inbuilt function defined in
a header file string.h. The gets() is capable of receiving only one string at a time.
Pointers with strings
We have used pointers with the array, functions, and primitive data types so far. However
pointers can be used to point to the strings. There are various advantages of using pointer
point strings. Let us consider the following example to access the string via the pointer.
As we know that string is an array of characters, the pointers can be used in the same
way they were used with arrays. In the above example, p is declared as a pointer to the
array of characters s. P affects similar to s since s is the base address of the string and
treated as a pointer internally. However, we can not change the content of s or copy
the content of s into another string directly. For this purpose, we need to use the
pointers to store the strings. In the following example, we have shown the use of
pointers to copy the content of a string into another.
Once a string is defined, it cannot be reassigned to another set of characters. However, us
pointers, we can assign the set of characters to the string. Consider the following example
C Pointers
The pointer in C language is a variable which stores the address
of another variable. This variable can be of type int, char, array,
function, or any other pointer. The size of the pointer depends on
the architecture. However, in 32-bit architecture the size of a
pointer is 2 byte.
Pointers in c language are widely used in arrays, functions, and structures. It reduces
the code and improves the performance.
Advantage of functions in C
There are the following advantages of C functions.
o By using functions, we can avoid rewriting same logic/code again and again in a
program.
o We can call C functions any number of times in a program and from any place in
a program.
o We can track a large C program easily when it is divided into multiple functions.
Function Aspects
There are three aspects of a C function.
o Function call Function can be called from anywhere in the program. The
parameter list must not differ in function calling and function declaration. We
must pass the same number of functions as it is declared in the function
declaration.
Our C++ tutorial includes all topics of C++ such as first example, control statements,
objects and classes, inheritance, constructor, destructor, this, static, polymorphism,
abstraction, abstract class, interface, namespace, encapsulation, arrays, strings,
exception handling, File IO, etc.
What is C++
C++ is a general purpose, case-sensitive, free-form programming language that
supports object-oriented, procedural and generic programming.
C++ is a middle-level language, as it encapsulates both high and low level language
features.
1. Inheritance
2. Polymorphism
3. Encapsulation
4. Abstraction
o The core library includes the data types, variables and literals, etc.
o The standard library includes the set of functions manipulating strings, files, etc.
o The Standard Template Library (STL) includes the set of methods manipulating a
data structure.
Usage of C++
By the help of C++ programming language, we can develop different types of secured and
robust applications:
o Window application
o Client-Server application
o Device drivers
C++ Program
In this tutorial, all C++ programs are given with C++ compiler so that you can easily chan
C++ program code.
File: main.cpp
C is the basic programming language that can be used to develop from the operating
systems (like Windows) to complex programs like Oracle database, Git, Python
interpreter, and many more. C programming language can be called a god's
programming language as it forms the base for other programming languages. If we
know the C language, then we can easily learn other programming languages. C
language was developed by the great computer scientist Dennis Ritchie at the Bell
Laboratories. It contains some additional features that make it unique from other
programming languages.
What is C++?
C++ is a special-purpose programming language developed by Bjarne Stroustrup at
Bell Labs circa 1980. C++ language is very similar to C language, and it is so
compatible with C that it can run 99% of C programs without changing any source of
code though C++ is an object-oriented programming language, so it is safer and well-
structured programming language than C.
ADVERTISEMENT
o Definition
C is a structural programming language, and it does not support classes and
objects, while C++ is an object-oriented programming language that supports
the concept of classes and objects.
o Subset
C++ is a superset of C programming language. C++ can run 99% of C code but
C language cannot run C++ code.
o Type of approach
C follows the top-down approach, while C++ follows the bottom-up approach.
The top-down approach breaks the main modules into tasks; these tasks are
broken into sub-tasks, and so on. The bottom-down approach develops the lower
level modules first and then the next level modules.
o Security
In C, the data can be easily manipulated by the outsiders as it does not support
the encapsulation and information hiding while C++ is a very secure language,
i.e., no outsiders can manipulate its data as it supports both encapsulation and
data hiding. In C language, functions and data are the free entities, and in C++
language, all the functions and data are encapsulated in the form of objects.
o Function Overloading
Function overloading is a feature that allows you to have more than one function
with the same name but varies in the parameters. C does not support the
function overloading, while C++ supports the function overloading.
o Function Overriding
Function overriding is a feature that provides the specific implementation to the
function, which is already defined in the base class. C does not support the
function overriding, while C++ supports the function overriding.
o Reference variables
C does not support the reference variables, while C++ supports the reference
variables.
o Keywords
C contains 32 keywords, and C++ supports 52 keywords.
o Namespace feature
A namespace is a feature that groups the entities like classes, objects, and
functions under some specific name. C does not contain the namespace feature,
while C++ supports the namespace feature that avoids the name collisions.
o Exception handling
C does not provide direct support to the exception handling; it needs to use
functions that support exception handling. C++ provides direct support to
exception handling by using a try-catch block.
o Input/Output functions
In C, scanf and printf functions are used for input and output operations,
respectively, while in C++, cin and cout are used for input and output
operations, respectively.
o Inheritance
Inheritance is a feature that allows the child class to reuse the properties of the
parent class. C language does not support the inheritance while C++ supports
the inheritance.
o Header file
C program uses <stdio.h> header file while C++ program
uses <iostream.h> header file.
No. C C++
2) Data is less secured in C. In C++, you can use modifiers for class
members to make it inaccessible for
outside users.
7) In C, scanf() and printf() are C++ mainly uses stream cin and
mainly used for input/output. cout to perform input and output
operations.
10) C does not provide the feature C++ supports the feature of namespace.
of namespace.
11) Exception handling is not easy C++ provides exception handling using
in C. It has to perform using Try and Catch block.
other functions.
C++ Features
C++ is object oriented programming language. It provides a lot of features that are
given below.
1. Simple
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible
1) Simple
C++ is a simple language in the sense that it provides structured approach (to break
the problem into parts), rich set of library functions, data types etc.
6) Memory Management
It supports the feature of dynamic memory allocation. In C++ language, we can free
the allocated memory at any time by calling the free() function.
7) Speed
The compilation and execution time of C++ language is fast.
8) Pointer
C++ provides the feature of pointers. We can directly interact with the memory by
using the pointers. We can use pointers for memory, structures, functions, array etc.
9) Recursion
In C++, we can call the function within the function. It provides code reusability for
every function.
10) Extensible
C++ language is extensible because it can easily adopt new features.
C++ Program
Before starting the abcd of C++ language, you need to learn how to write, compile and
run the first C++ program.
To write the first C++ program, open the C++ console and write the following code:
1. #include <iostream.h>
2. #include<conio.h>
3. void main() {
4. clrscr();
5. cout << "Welcome to C++ Programming.";
6. getch();
7. }
#include <conio.h> includes the console input output library functions. The getch()
function is defined in conio.h file.
void main() The main() function is the entry point of every program in C++
language. The void keyword specifies that it returns no value.
cout << "Welcome to C++ Programming." is used to print the data "Welcome to C++
Programming." on the console.
getch() The getch() function asks for a single character. Until you press any key, it blocks the
screen.
C++ Basic Input/Output
C++ I/O operation is using the stream concept. Stream is the sequence of bytes or flow
of data. It makes the performance fast.
If bytes flow from main memory to device like printer, display screen, or a network
connection, etc, this is called as output operation.
If bytes flow from device like printer, display screen, or a network connection, etc to
main memory, this is called as input operation.
<iostream> It is used to define the cout, cin and cerr objects, which correspond to standard output
stream, standard input stream and standard error stream, respectively.
<iomanip> It is used to declare services useful for performing formatted I/O, such as setprecision and
setw.
1. #include <iostream>
2. using namespace std;
3. int main( ) {
4. char ary[] = "Welcome to C++ tutorial";
5. cout << "Value of ary is: " << ary << endl; // similar like printf() in C
6. }
Output:
1. #include <iostream>
2. using namespace std;
3. int main( ) {
4. int age;
5. cout << "Enter your age: ";
6. cin >> age; //similar like scanf() in C
7. cout << "Your age is: " << age << endl;
8. }
Output:
Enter your age: 22
Your age is: 22
1. #include <iostream>
2. using namespace std;
3. int main( ) {
4. cout << "C++ Tutorial";
5. cout << " Javatpoint"<<endl; // it is a new line similar like \n in C
6. cout << "End of line"<<endl;
7. }
Output:
C++ Variable
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.
1. int x;
2. float y;
3. char z;
Here, x, y, z are variables and int, float, char are data types.
We can also provide values while declaring the variables as given below:
4. char ary[] = "Welcome to C++ tutorial"; // Declaring a string called array of characters
A variable name can start with alphabet and underscore only. It can't start with digit.
A variable name must not be any reserved word or keyword e.g. char, float etc.
1. int a;
2. int _ab;
3. int a30;
1. int 4;
2. int x y;
3. int double;
The memory size of basic data types may change according to 32 or 64 bit operating system.
Let's see the basic data types. It size is given according to 32 bit OS.
Data Types Memory Size Range
float 4 byte
double 8 byte
C++ Keywords
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.
A list of 30 Keywords in C++ Language which are not available in C language are given below.
o Arithmetic Operators
o Relational Operators
o Logical Operators
o Bitwise Operators
o Assignment Operator
o Unary operator
o Misc Operator
Precedence of Operators in C++
The precedence of operator species that which operator will be evaluated first and next.
The associativity specifies the operators direction to be evaluated, it may be left to right
or right to left.
1. int data=5+10*10;
The "data" variable will contain 105 because * (multiplicative operator) is evaluated
before + (additive operator).
In short, we can say that the C++ identifiers represent the essential elements in a program which are
given below:
o Constants
o Variables
o Functions
o Labels
Some naming rules are common in both C and C++. They are as follows:
o The identifier name cannot start with a digit, i.e., the first letter should be alphabetical. After
the first letter, we can use letters, digits, or underscores.
o In C++, uppercase and lowercase letters are distinct. Therefore, we can say that C++
identifiers are case-sensitive.
For example, suppose we have two identifiers, named as 'FirstName', and 'Firstname'. Both the
identifiers will be different as the letter 'N' in the first case in uppercase while lowercase in second.
Therefore, it proves that identifiers are case-sensitive.
Valid Identifiers
Result
Test2
_sum
power
Invalid Identifiers
Note: Identifiers cannot be used as the keywords. It may not conflict with the keywords, but
it is highly recommended that the keywords should not be used as the identifier name. You
should always use a consistent way to name the identifiers so that your code will be more
readable and maintainable.
The major difference between C and C++ is the limit on the length of the name of the
variable. ANSI C considers only the first 32 characters in a name while ANSI C++
imposes no limit on the length of the name.
Constants are the identifiers that refer to the fixed value, which do not change during
the execution of a program. Both C and C++ support various kinds of literal constants,
and they do have any memory location. For example, 123, 12.34, 037, 0X2, etc. are the
literal constants.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a;
6. int A;
7. cout<<"Enter the values of 'a' and 'A'";
8. cin>>a;
9. cin>>A;
10. cout<<"\nThe values that you have entered are : "<<a<<" , "<<A;
11. return 0;
12. }
In the above code, we declare two variables 'a' and 'A'. Both the letters are same but
they will behave as different identifiers. As we know that the identifiers are the case-
sensitive so both the identifiers will have different memory locations.
Output
Identifiers Keywords
Identifiers are the names defined by the programmer to the Keywords are the reserved words whose meaning
basic elements of a program. is known by the compiler.
It is used to identify the name of the variable. It is used to specify the type of entity.
It can use both lowercase and uppercase letters. It uses only lowercase letters.
No special character can be used except the underscore. It cannot contain any special character.
The starting letter of identifiers can be lowercase, It can be started only with the lowercase letter.
uppercase or underscore.
Examples are test, result, sum, power, etc. Examples are 'for', 'if', 'else', 'break', etc.
C++ Expression
C++ expression consists of operators, constants, and variables which are arranged according to the
rules of the language. It can also contain function calls which return values. 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 Integral expressions
o Float expressions
o Pointer expressions
o Relational expressions
o Logical expressions
o Bitwise expressions
Constant expressions
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.
In the above scenarios, the constant expression can have integer, character, and
enumeration constants. We can use the static and extern keyword with the constants to
define the function-scope.
x = (2/3) * 4 (2/3) * 4
extern int y = 67 67
int z = 43 43
static int a = 56 56
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x; // variable declaration.
6. x=(3/2) + 2; // constant expression
7. cout<<"Value of x is : "<<x; // displaying the value of x.
8. return 0;
9. }
In the above code, we have first declared the 'x' variable of integer type. After
declaration, we assign the simple constant expression to the 'x' variable.
Output
Value of x is : 3
Integral Expressions
An integer expression is an expression that produces the integer value as output after
performing all the explicit and implicit conversions.
1. (x * y) -5
2. x + int(9.0)
3. where x and y are the integers.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x; // variable declaration.
6. int y; // variable declaration
7. int z; // variable declaration
8. cout<<"Enter the values of x and y";
9. cin>>x>>y;
10. z=x+y;
11. cout<<"\n"<<"Value of z is :"<<z; // displaying the value of z.
12. return 0;
13. }
In the above code, we have declared three variables, i.e., x, y, and z. After declaration, we take
the user input for the values of 'x' and 'y'. Then, we add the values of 'x' and 'y' and stores their
result in 'z' variable.
Output
In the above code, we declare two variables, i.e., x and y. We store the value of
expression (y+int(10.0)) in a 'x' variable.
Output
Value of x : 19
Float Expressions
A float expression is an expression that produces floating-point value as output after
performing all the explicit and implicit conversions.
1. x+y
2. (x/10) + y
3. 34.5
4. x+float(10)
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5.
6. float x=8.9; // variable initialization
7. float y=5.6; // variable initialization
8. float z; // variable declaration
9. z=x+y;
10. std::cout <<"value of z is :" << z<<std::endl; // displaying the value of z.
11.
12.
13. return 0;
14. }
Output
value of z is :14.5
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. float x=6.7; // variable initialization
6. float y; // variable declaration
7. y=x+float(10); // float expression
8. std::cout <<"value of y is :" << y<<std::endl; // displaying the value of y
9. return 0;
10. }
In the above code, we have declared two variables, i.e., x and y. After declaration, we store the
value of expression (x+float(10)) in variable 'y'.
Output
value of y is :16.7
Pointer Expressions
A pointer expression is an expression that produces address value as an output.
1. &x
2. ptr
3. ptr++
4. ptr-
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5.
6. int a[]={1,2,3,4,5}; // array initialization
7. int *ptr; // pointer declaration
8. ptr=a; // assigning base address of array to the pointer ptr
9. ptr=ptr+1; // incrementing the value of pointer
10. std::cout <<"value of second element of an array : " << *ptr<<std::endl;
11. return 0;
12. }
In the above code, we declare the array and a pointer ptr. We assign the base address to the
variable 'ptr'. After assigning the address, we increment the value of pointer 'ptr'. When pointer is
incremented then 'ptr' will be pointing to the second element of the array.
Output
Relational Expressions
A relational expression is an expression that produces a value of type bool, which can be either true
or false. It is also known as a boolean expression. When arithmetic expressions are used on both
sides of the relational operator, arithmetic expressions are evaluated first, and then their results are
compared.
1. a>b
2. a-b >= x-y
3. a+b>80
In the above code, we have declared two variables, i.e., 'a' and 'b'. After declaration, we have
applied the relational operator between the variables to check whether 'a' is greater than 'b' or not.
Output
Value of y is :0
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=4; // variable declaration
6. int b=5; // variable declaration
7. int x=3; // variable declaration
8. int y=6; // variable declaration
9. cout<<((a+b)>=(x+y)); // relational expression
10. return 0;
11. }
In the above code, we have declared four variables, i.e., 'a', 'b', 'x' and 'y'. Then, we apply the
relational operator (>=) between these variables.
Output
1
Logical Expressions
A logical expression is an expression that combines two or more relational expressions and
produces a bool type value. The logical operators are '&&' and '||' that combines two or more
relational expressions.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=2;
6. int b=7;
7. int c=4;
8. cout<<((a>b)||(a>c));
9. return 0;
10. }
Output
Bitwise Expressions
A bitwise expression is an expression which is used to manipulate the data at a bit level. They are
basically used to shift the bits.
For example:
x=3
x>>3 // This statement means that we are shifting the three-bit position to the right.
In the above example, the value of 'x' is 3 and its binary value is 0011. We are shifting the value of 'x'
by three-bit position to the right. Let's understand through the diagrammatic representation.
Let's see a simple example.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x=5; // variable declaration
6. std::cout << (x>>1) << std::endl;
7. return 0;
8. }
In the above code, we have declared a variable 'x'. After declaration, we applied the bitwise
operator, i.e., right shift operator to shift one-bit position to right.
Output
2
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x=7; // variable declaration
6. std::cout << (x<<3) << std::endl;
7. return 0;
8. }
In the above code, we have declared a variable 'x'. After declaration, we applied the left shift
operator to variable 'x' to shift the three-bit position to the left.
Output
56
o Chained Assignment
Chained assignment expression is an expression in which the same value is assigned to more than
one variable by using single statement.
For example:
1. a=b=20
2. or
3. (a=b) = 20
1. #include <iostream>
2. using namespace std;
3. int main()
4.
5. int a; // variable declaration
6. int b; // variable declaration
7. a=b=80; // chained assignment
8. std::cout <<"Values of 'a' and 'b' are : " <<a<<","<<b<< std::endl;
9. return 0;
10. }
In the above code, we have declared two variables, i.e., 'a' and 'b'. Then, we have assigned the
same value to both the variables using chained assignment expression.
Output
Note: Using chained assignment expression, the value cannot be assigned to the variable
at the time of declaration. For example, int a=b=c=90 is an invalid statement.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a; // variable declaration
6. int b; // variable declaration
7. a=10+(b=90); // embedded assignment expression
8. std::cout <<"Values of 'a' is " <<a<< std::endl;
9. return 0;
10. }
In the above code, we have declared two variables, i.e., 'a' and 'b'. Then, we applied embedded
assignment expression (a=10+(b=90)).
Output
o Compound Assignment
A compound assignment expression is an expression which is a combination of an assignment
operator and binary operator.
For example,
1. a+=10;
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=10; // variable declaration
6. a+=10; // compound assignment
7. std::cout << "Value of a is :" <<a<< std::endl; // displaying the value of a.
8. return 0;
9. }
In the above code, we have declared a variable 'a' and assigns 10 value to this variable. Then, we
applied compound assignment operator (+=) to 'a' variable, i.e., a+=10 which is equal to (a=a+10).
This statement increments the value of 'a' by 10.
Output
Value of a is :20
C++ Functions
The function in C++ language is also known as procedure or subroutine in other
programming languages.
To perform any task, we can create function. A function can be called many times. It
provides modularity and code reusability.
Advantage of functions in C
There are many advantages of functions.
1) Code Reusability
By creating functions in C++, you can call it many times. So we don't need to write the
same code again and again.
2) Code optimization
Suppose, you have to check 3 numbers (531, 883 and 781) whether it is prime number
or not. Without using function, you need to write the prime number logic 3 times. So,
there is repetition of code.
But if you use functions, you need to write the logic only once and you can reuse it
several times.
Types of Functions
There are two types of functions in C programming:
1. Library Functions: are the functions which are declared in the C++ header files such
as ceil(x), cos(x), exp(x), etc.
2. User-defined functions: are the functions which are created by the C++
programmer, so that he/she can use it many times. It reduces complexity of a big
program and optimizes the code.
Declaration of a function
The syntax of creating function in C++ language is given below:
1. #include <iostream>
2. using namespace std;
3. void func() {
4. static int i=0; //static variable
5. int j=0; //local variable
6. i++;
7. j++;
8. cout<<"i=" << i<<" and j=" <<j<<endl;
9. }
10. int main()
11. {
12. func();
13. func();
14. func();
15. }
Output:
i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1
Let's understand call by value and call by reference in C++ language one by one.
Call by value in C++
In call by value, original value is not modified.
In call by value, value being passed to the function is locally stored by the function
parameter in stack memory location. If you change the value of function parameter, it is
changed for the current function only. It will not change the value of variable inside the
caller method such as main().
Let's try to understand the concept of call by value in C++ language by the example
given below:
1. #include <iostream>
2. using namespace std;
3. void change(int data);
4. int main()
5. {
6. int data = 3;
7. change(data);
8. cout << "Value of the data is: " << data<< endl;
9. return 0;
10. }
11. void change(int data)
12. {
13. data = 5;
14. }
Output:
Note: To understand the call by reference, you must have the basic knowledge of
pointers.
Let's try to understand the concept of call by reference in C++ language by the example
given below:
1. #include<iostream>
2. using namespace std;
3. void swap(int *x, int *y)
4. {
5. int swap;
6. swap=*x;
7. *x=*y;
8. *y=swap;
9. }
10. int main()
11. {
12. int x=500, y=100;
13. swap(&x, &y); // passing value to function
14. cout<<"Value of x is: "<<x<<endl;
15. cout<<"Value of y is: "<<y<<endl;
16. return 0;
17. }
Output:
C++ Recursion
When function is called within the same function, it is known as recursion in C++. The
function which calls the same function, is known as recursive function.
A function that calls itself, and doesn't perform any task after function call, is known as
tail recursion. In tail recursion, we generally call the same function with return
statement.
1. recursionfunction(){
2. recursionfunction(); //calling self function
3. }
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:
We can understand the above program of recursive method call by the figure given
below:
C++ Storage Classes
Storage class is used to define the lifetime and visibility of a variable and/or function
within a C++ program.
Lifetime refers to the period during which the variable remains active and visibility refers
to the module of a program in which the variable is accessible.
There are five types of storage classes, which can be used in a C++ program
1. Automatic
2. Register
3. Static
4. External
5. Mutable
1. {
2. auto int y;
3. float y = 3.45;
4. }
The above example defines two variables with a same storage class, auto can only be
used within functions.
It is recommended to use register variable only for quick access such as in counter.
The static variable has the default value 0 which is provided by compiler.
1. #include <iostream>
2. using namespace std;
3. void func() {
4. static int i=0; //static variable
5. int j=0; //local variable
6. i++;
7. j++;
8. cout<<"i=" << i<<" and j=" <<j<<endl;
9. }
10. int main()
11. {
12. func();
13. func();
14. func();
15. }
Output:
i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1