C++ Unit I-1
C++ Unit I-1
Unit I
Software Crisis – Software Evolution – Basic Concepts of Object-Oriented
Programming – Benefits of OOP – Object-Oriented Languages - Applications of
OOP – Application of C++ - Structure of a C++ Program – Tokens – Keywords –
Identifiers – Basic Data Types – Userdefined Data types – Derived data types –
Symbolic constants – Type compatibility – Declaration of variables – Dynamic
initialization of variables –Reference variables – Operators in C++ - Manipulators
– Type cast operator – Expressions and their types-Implicit conversions – Control
structures – The main function – Function prototyping – inline functions –
Function overloading.
Software Crisis:
Software Crisis is a term used in computer science for the difficulty of writing
useful and efficient computer programs in the required time .software crisis was
due to using same workforce, same methods, same tools even though rapidly
increasing in software demand, complexity of software and software challenges.
With increase in the complexity of software, many software problems arise
because existing methods were insufficient.
Causes of Software Crisis:
• The cost of owning and maintaining software was as expensive as developing
the software
• At that time Projects was running over-time
• At that time Software was very inefficient
• The quality of software was low quality
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 1
• Software often did not meet requirements
• The average software project overshoots its schedule by half
• At that time Software was never delivered
Solution of Software Crisis:
There is no single solution to the crisis.one possible solution of software crisis
is Software Engineering because software engineering is a systematic, disciplined
and quantifiable approach. For preventing software crisis, there are some
guidelines:
• Reduction in software over-budget
• The quality of software must be high
• Less time needed for software project
• Experience working team member on software project
• Software must be delivered
Introduction to C++
C++, as we all know is an extension to C language and was developed by Bjarne stroustrup at
bell labs. C++ is an intermediate level language, as it comprises a confirmation of both high level
and low level language features. C++ is a statically typed, free form, multiparadigm, compiled
general-purpose language.
C++ is an Object Oriented Programming language but is not purely Object Oriented. Its
features like Friend and Virtual, violate some of the very important OOPS features, rendering
this language unworthy of being called completely Object Oriented. Its a middle level language.
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 2
1. There is Stronger Type Checking in C++.
2. All the OOPS features in C++ like Abstraction, Encapsulation, Inheritance etc makes it
more worthy and useful for programmers.
3. C++ supports and allows user defined operators (i.e Operator Overloading) and function
overloading is also supported in it.
4. Exception Handling is there in C++.
5. The Concept of Virtual functions and also Constructors and Destructors for Objects.
6. Inline Functions in C++ instead of Macros in C language. Inline functions make complete
function body act like Macro, safely.
7. Variables can be declared anywhere in the program in C++, but must be declared before
they are used.
C++ can be found in today's operating systems, Graphical User Interfaces, and embedded
systems.
C++ is an object-oriented programming language which gives a clear structure to programs and
allows code to be reused, lowering development costs.
C++ is portable and can be used to develop applications that can be adapted to multiple
platforms.
As C++ is close to C# and Java, it makes it easy for programmers to switch to C++ or vice versa
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 3
Object Oriented Programming in C++
Object Oriented programming is a programming style that is associated with the concept of
Class, Objects and various other concepts revolving around these two, like Inheritance,
Polymorphism, Abstraction, Encapsulation etc.
In the video below, we have explained the basic concepts of Object Oriented Programming with
help of a very easy to understand example. If you want to skip the video, everything is covered
below as well.
Let us try to understand a little about all these, through a simple example. Human Beings are
living forms, broadly categorized into two types, Male and Female. Right? Its true. Every Human
being(Male or Female) has two legs, two hands, two eyes, one nose, one heart etc. There are
body parts that are common for Male and Female, but then there are some specific body parts,
present in a Male which are not present in a Female, and some body parts present in Female but
not in Males.
All Human Beings walk, eat, see, talk, hear etc. Now again, both Male and Female, performs
some common functions, but there are some specifics to both, which is not valid for the other.
For example : A Female can give birth, while a Male cannot, so this is only for the Female.
Human Anatomy is interesting, isn't it? But let's see how all this is related to C++ and OOPS.
Here we will try to explain all the OOPS concepts through this example and later we will have
the technical definitons for all this.
Class
Here we can take Human Being as a class. A class is a blueprint for any functional entity which
defines its properties and its functions. Like Human Being, having body parts, and performing
various actions.
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 4
Inheritance
Considering HumanBeing a class, which has properties like hands, legs, eyes etc, and functions
like walk, talk, eat, see etc. Male and Female are also classes, but most of the properties and
functions are included in HumanBeing, hence they can inherit everything from
class HumanBeing using the concept of Inheritance.
Objects
My name is Abhishek, and I am an instance/object of class Male. When we say, Human Being,
Male or Female, we just mean a kind, you, your friend, me we are the forms of these classes. We
have a physical existence while a class is just a logical definition. We are the objects.
Abstraction
Abstraction means, showcasing only the required things to the outside world while hiding the
details. Continuing our example, Human Being's can talk, walk, hear, eat, but the details are
hidden from the outside world. We can take our skin as the Abstraction factor in our case, hiding
the inside mechanism.
Encapsulation
This concept is a little tricky to explain with our example. Our Legs are binded to help us walk.
Our hands, help us hold things. This binding of the properties to functions is called
Encapsulation.
Polymorphism
Polymorphism is a concept, which allows us to redefine the way something works, by either
changing how it is done or by changing the parts using which it is done. Both the ways have
different terms for them.
If we walk using our hands, and not legs, here we will change the parts used to perform
something. Hence this is called Overloading.
And if there is a defined way of walking, but I wish to walk differently, but using my legs, like
everyone else. Then I can walk like I want, this will be called as Overriding.
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 5
*****
C++ Tokens
A token is the smallest element of a program that is meaningful to the compiler. Tokens can be
classified as follows:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
Keywords: Keywords are pre-defined or reserved words in a programming language. Each
keyword is meant to perform a specific function in a program. Since keywords are referred
names for a compiler, they can’t be used as variable names because by doing so, we are trying
to assign a new meaning to the keyword which is not allowed. You cannot redefine keywords.
However, you can specify the text to be substituted for keywords before compilation by using
C/C++ preprocessor directives. C language supports 32 keywords which are given below:
do if static while
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 6
While in C++ there are 31 additional keywords other than C Keywords they are:
1. Identifiers: Identifiers are used as the general terminology for the naming of variables,
functions and arrays. These are user-defined names consisting of an arbitrarily long
sequence of letters and digits with either a letter or the underscore(_) as a first character.
Identifier names must differ in spelling and case from any keywords. You cannot use
keywords as identifiers; they are reserved for special use. Once declared, you can use the
identifier in later program statements to refer to the associated value. A special kind of
identifier, called a statement label, can be used in goto statements.
There are certain rules that should be followed while naming c identifiers:
• They must begin with a letter or underscore(_).
• They must consist of only letters, digits, or underscore. No other special character is
allowed.
• It should not be a keyword.
• It must not contain white space.
• It should be up to 31 characters long as only the first 31 characters are significant.
• main: method name.
• a: variable name.
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 7
2. Constants: Constants are also like normal variables. But, the only difference is, their
values can not be modified by the program once they are defined. Constants refer to fixed
values. They are also called literals.
Constants may belong to any of the data type.
3. Syntax:
const data_type variable_name; (or) const data_type *variable_name;
Types of Constants:
1. Integer constants – Example: 0, 1, 1218, 12482
2. Real or Floating-point constants – Example: 0.0, 1203.03, 30486.184
3. Octal & Hexadecimal constants – Example: octal: (013 )8 = (11)10, Hexadecimal:
(013)16 = (19)10
4. Character constants -Example: ‘a’, ‘A’, ‘z’
5. String constants -Example: “GeeksforGeeks”
4. Strings: Strings are nothing but an array of characters ended with a null character (‘\0’).
This null character indicates the end of the string. Strings are always enclosed in double-
quotes. Whereas, a character is enclosed in single quotes in C and C++.Declarations for
String:
• char string[20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘\0’};
• char string[20] = “geeksforgeeks”;
• char string [] = “geeksforgeeks”;
• when we declare char as “string[20]”, 20 bytes of memory space is allocated for
holding the string value.
• When we declare char as “string[]”, memory space will be allocated as per the
requirement during the execution of the program.
5. Special Symbols: The following special symbols are used in C having some special
meaning and thus, cannot be used for some other purpose.[] () {}, ; * = #
• Brackets[]: Opening and closing brackets are used as array element reference. These
indicate single and multidimensional subscripts.
• Parentheses(): These special symbols are used to indicate function calls and function
parameters.
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 8
• Braces{}: These opening and ending curly braces mark the start and end of a block of
code containing more than one executable statement.
• Comma (, ): It is used to separate more than one statements like for separating
parameters in function calls.
• Colon(:): It is an operator that essentially invokes something called an initialization
list.
• Semicolon(;): It is known as a statement terminator. It indicates the end of one logical
entity. That’s why each individual statement must be ended with a semicolon.
• Asterisk (*): It is used to create a pointer variable.
• Assignment operator(=): It is used to assign values.
• Pre-processor (#): The preprocessor is a macro processor that is used automatically by
the compiler to transform your program before actual compilation.
6. Operators: Operators are symbols that trigger an action when applied to C variables and
other objects. The data items on which operators act upon are called operands.
Depending on the number of operands that an operator can act upon, operators can be
classified as follows:
• Unary Operators: Those operators that require only a single operand to act upon are
known as unary operators.For Example increment and decrement operators
• Binary Operators: Those operators that require two operands to act upon are called
binary operators. Binary operators are classified into :
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Conditional Operators
6. Bitwise Operators
*****
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 9
variable is defined in C++, the compiler allocates some memory for that variable based on the
data-type with which it is declared. Every data type requires a different amount of memory.
• Integer: Keyword used for integer data types is int. Integers typically requires 4 bytes of
memory space and ranges from -2147483648 to 2147483647.
• Character: Character data type is used for storing characters. Keyword used for character
data type is char. Characters typically requires 1 byte of memory space and ranges from -
128 to 127 or 0 to 255.
• Boolean: Boolean data type is used for storing boolean or logical values. A boolean
variable can store either true or false. Keyword used for boolean data type is bool.
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 10
• Floating Point: Floating Point data type is used for storing single precision floating point
values or decimal values. Keyword used for floating point data type is float. Float variables
typically requires 4 byte of memory space.
• Double Floating Point: Double Floating Point data type is used for storing double
precision floating point values or decimal values. Keyword used for double floating point
data type is double. Double variables typically requires 8 byte of memory space.
• void: Void means without any value. void datatype represents a valueless entity. Void data
type is used for those function which does not returns a value.
• Wide Character: Wide character data type is also a character data type but this data type
has size greater than the normal 8-bit datatype. Represented by wchar_t. It is generally 2
or 4 bytes long.
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 11
FunctionType FunctionName(parameters)
Example:
filter_none
edit
play_arrow
brightness_4
#include <iostream>
if (x > y)
return x;
else
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 12
return y;
int main()
return 0;
Output:
m is 20
2. Array: An array is a collection of items stored at continuous memory locations. The idea of
array is to represent many instances in one variable.
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 13
Syntax:
DataType ArrayName[size_of_array];
Example:
filter_none
edit
play_arrow
brightness_4
#include <iostream>
int main()
int arr[5];
arr[0] = 5;
arr[2] = -10;
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 14
// this is same as arr[1] = 2
arr[3 / 2] = 2;
arr[3] = arr[0];
return 0;
Output:
5 2 -10 5
3. Pointers: Pointers are symbolic representation of addresses. They enable programs to
simulate call-by-reference as well as to create and manipulate dynamic data structures. It’s
general declaration in C/C++ has the format:
Syntax:
datatype *var_name;
Example:
int *ptr;
Example:
filter_none
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 15
edit
play_arrow
brightness_4
#include <bits/stdc++.h>
void geeks()
int* ptr;
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 16
ptr = &var;
// to a pointer
// Driver program
int main()
geeks();
Output:
Value at ptr = 0x7ffc10d7fd5c
Value at var = 20
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 17
Value at *ptr = 20
edit
play_arrow
brightness_4
#include <iostream>
int main()
int x = 10;
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 18
// ref is a reference to x.
int& ref = x;
ref = 20;
x = 30;
return 0;
Output:
x = 20
ref = 30
3. ABSTRACT OR USER-DEFINED DATA TYPES: These data types are defined by user
itself. Like, defining a class in C++ or a structure. C++ provides the following user-defined
datatypes:
• Class
• Structure
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 19
• Union
• Enumeration
• Typedef defined DataType
3.User-Defined DataTypes:
The data types that are defined by the user are called the derived datatype or user-defined
derived data type.
These types include:
• Class
• Structure
• Union
• Enumeration
• Typedef defined DataType
Below is the detailed description of the following types:
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 20
1. Class: The building block of C++ that leads to Object-Oriented programming is a Class. It
is a user-defined data type, which holds its own data members and member functions,
which can be accessed and used by creating an instance of that class. A class is like a
blueprint for an object.
Example:
filter_none
edit
play_arrow
brightness_4
// Class
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 21
#include <bits/stdc++.h>
class Geeks {
// Access specifier
public:
// Data Members
string geekname;
// Member Functions()
void printname()
};
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 22
int main()
Geeks obj1;
obj1.geekname = "GeeksForGeeks";
obj1.printname();
return 0;
Output:
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 23
Geekname is: GeeksForGeeks
2. Structure: A structure is a user defined data type in C/C++. A structure creates a data type
that can be used to group items of possibly different types into a single type.
Syntax:
struct address {
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};
Example:
filter_none
edit
play_arrow
brightness_4
// Structures in C++
#include <iostream>
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 24
struct Point {
int x, y;
};
int main()
arr[0].x = 10;
arr[0].y = 20;
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 25
return 0;
Output:
10, 20
3. Union: Like Structures, union is a user defined data type. In union, all members share the
same memory location. For example in the following C program, both x and y share the
same location. If we change x, we can see the changes being reflected in y.
filter_none
edit
play_arrow
brightness_4
#include <iostream>
union test {
int x, y;
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 26
};
int main()
// A union variable t
union test t;
t.x = 2;
<< endl
<< endl;
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 27
// t.x is also updated to 10
t.y = 10;
<< endl
<< endl;
return 0;
Output:
After making x = 2:
x = 2, y = 2
x = 10, y = 10
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 28
4. Enumeration: Enumeration (or enum) is a user defined data type in C. It is mainly used to
assign names to integral constants, the names make a program easy to read and maintain.
Syntax:
enum State {Working = 1, Failed = 0};
filter_none
edit
play_arrow
brightness_4
// of enum in C++
#include <iostream>
Tue,
Wed,
Thur,
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 29
Fri,
Sat,
Sun };
int main()
day = Wed;
return 0;
Output:
2
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 30
5. Typedef : C++ allows you to define explicitly new data type names by using the keyword
typedef. Using typedef does not actually create a new data class, rather it defines a name
for an existing type. This can increase the portability(the ability of a program to be used
across different types of machines; i.e., mini, mainframe, micro, etc; without much changes
into the code)of a program as only the typedef statements would have to be changed. Using
typedef one can also aid in self-documenting code by allowing descriptive names for the
standard data types.
Syntax:
typedef type name;
where type is any C++ data type and name is the new name for this data type.
This defines another name for the standard type of C++.
Example:
filter_none
edit
play_arrow
brightness_4
#include <iostream>
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 31
typedef unsigned char BYTE;
int main()
b1 = 'c';
return 0;
Output:
C
Declaration of Variables:
A variable provides us with named storage that our programs can manipulate. Each variable in
C++ has a specific type, which determines the size and layout of the variable's memory; the
range of values that can be stored within that memory; and the set of operations that can be
applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character. It must
begin with either a letter or an underscore. Upper and lowercase letters are distinct because C++
is case-sensitive
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 32
A variable definition tells the compiler where and how much storage to create for the variable.
A variable definition specifies a data type, and contains a list of one or more variables of that
type as follows −
type variable_list;
Here, type must be a valid C++ data type including char, w_char, int, float, double, bool or any
user-defined object, etc., and variable_list may consist of one or more identifier names
separated by commas. Some valid declarations are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; both declares and defines the variables i, j and k; which instructs the
compiler to create variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer
consists of an equal sign followed by a constant expression as follows −
type variable_name = value;
Some examples are −
extern int d = 3, f = 5; // declaration of d and f.
int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.
For definition without an initializer: variables with static storage duration are implicitly
initialized with NULL (all bytes have the value 0); the initial value of all other variables is
undefined.
A variable declaration provides assurance to the compiler that there is one variable existing with
the given type and name so that compiler proceed for further compilation without needing
complete detail about the variable. A variable declaration has its meaning at the time of
compilation only, compiler needs actual variable definition at the time of linking of the
program.
A variable declaration is useful when you are using multiple files and you define your variable
in one of the files which will be available at the time of linking of the program. You will
use extern keyword to declare a variable at any place. Though you can declare a variable
multiple times in your C++ program, but it can be defined only once in a file, a function or a
block of code.
Example
Try the following example where a variable has been declared at the top, but it has been defined
inside the main function −
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 33
#include <iostream>
using namespace std;
// Variable declaration:
extern int a, b;
extern int c;
extern float f;
int main () {
// Variable definition:
int a, b;
int c;
float f;
// actual initialization
a = 10;
b = 20;
c = a + b;
f = 70.0/3.0;
cout << f << endl ;
return 0;
}
When the above code is compiled and executed, it produces the following result −
30
23.3333
Operators in C++
Previous Page
Next Page
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C++ is rich in built-in operators and provide the following types of operators −
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 34
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators
This chapter will examine the arithmetic, relational, logical, bitwise, assignment and other
operators one by one.
Arithmetic Operators
Show Examples
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 35
++ Increment operator, increases integer A++ will give 11
value by one
Relational Operators
Show Examples
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 36
< Checks if the value of left operand is less (A < B) is true.
than the value of right operand, if yes then
condition becomes true.
Logical Operators
Show Examples
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 37
becomes true.
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^
are as follows −
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 38
A|B = 0011 1101
~A = 1100 0011
The Bitwise operators supported by C++ language are listed in the following table. Assume
variable A holds 60 and variable B holds 13, then −
Show Examples
| Binary OR Operator copies a bit if it exists (A | B) will give 61 which is 0011 1101
in either operand.
~ Binary Ones Complement Operator is (~A ) will give -61 which is 1100 0011 in
unary and has the effect of 'flipping' bits. 2's complement form due to a signed
binary number.
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 39
>> Binary Right Shift Operator. The left
operands value is moved right by the
A >> 2 will give 15 which is 0000 1111
number of bits specified by the right
operand.
Assignment Operators
Show Examples
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 40
/= Divide AND assignment operator, It divides
left operand with the right operand and assign C /= A is equivalent to C = C / A
the result to left operand.
Misc Operators
The following table lists some other operators that C++ supports.
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 41
1 sizeof
sizeof operator returns the size of a variable. For example, sizeof(a), where ‘a’ is integer,
and will return 4.
2 Condition ? X : Y
Conditional operator (?). If Condition is true then it returns value of X otherwise returns
value of Y.
3 ,
Comma operator causes a sequence of operations to be performed. The value of the entire
comma expression is the value of the last expression of the comma-separated list.
Member operators are used to reference individual members of classes, structures, and
unions.
5 Cast
Casting operators convert one data type to another. For example, int(2.2000) would return
2.
6 &
Pointer operator & returns the address of a variable. For example &a; will give actual
address of the variable.
7 *
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 42
Pointer operator * is pointer to a variable. For example *var; will pointer to a variable var.
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator −
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Show Examples
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 43
Equality == != Left to right
The :: (scope resolution) operator is used to get hidden names due to variable scopes so that you
can still use them. The scope resolution operator can be used as both unary and binary. You can
use the unary scope operator if a namespace scope or global scope name is hidden by a particular
declaration of an equivalent name during a block or class. For example, if you have a global
variable of name my_var and a local variable of name my_var, to access global my_var, you'll
need to use the scope resolution operator.
example
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 44
#include <iostream>
int my_var = 0;
int main(void) {
int my_var = 0;
return 0;
Output
1, 2
Manipulators:
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 45
Manipulators are helping functions that can modify the input/output stream. It does not mean
that we change the value of a variable, it only modifies the I/O stream using insertion (<<) and
extraction (>>) operators.
For example, if we want to print the hexadecimal value of 100 then we can print it as:
cout<<setbase(16)<<100
Types of Manipulators
There are various types of manipulators:
Examples:
#include <iostream>
#include <istream>
#include <sstream>
#include <string>
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 46
using namespace std;
int main()
string line;
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 47
// Use of ends Manipulator
return 0;
Output:
Programmer
only a test
abc
A cast is a special operator that forces one data type to be converted into another. As an
operator, a cast is unary and has the same precedence as any other unary operator.
The most general cast supported by most of the C++ compilers is as follows −
(type) expression
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 48
Where type is the desired data type. There are other casting operators supported by C++, they
are listed below −
All of the above-mentioned casting operators will be used while working with classes and
objects. For now, try the following example to understand a simple cast operators available in
C++. Copy and paste the following C++ program in test.cpp file and compile and run this
program.
Live Demo
#include <iostream>
using namespace std;
main() {
double a = 21.09399;
float b = 10.20;
int c ;
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 49
c = (int) a;
cout << "Line 1 - Value of (int)a is :" << c << endl ;
c = (int) b;
cout << "Line 2 - Value of (int)b is :" << c << endl ;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Control Structures
A program is usually not limited to a linear sequence of instructions. During its process it
may bifurcate, repeat code or take decisions. For that purpose, C++ provides control
structures that serve to specify what has to be done to perform our program.
With the introduction of control sequences we are going to have to introduce a new
concept: the block of instructions. A block of instructions is a group of instructions
separated by semicolons (;) but grouped in a block delimited by curly bracket
signs: { and }.
Most of the control structures that we will see in this section allow a generic statement as
a parameter, this refers to either a single instruction or a block of instructions, as we
want. If we want the statement to be a single instruction we do not need to enclose it
between curly-brackets ({}). If we want the statement to be more than a single instruction
we must enclose them between curly brackets ({}) forming a block of instructions.
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 50
Conditional structure: Simple if:
if else:
We can additionally specify what we want that happens if the condition is not fulfilled by
using the keyword else. Its form used in conjunction with if is:
if (condition) statement1 else statement2
For example:
if (x == 100)
cout << "x is 100";
else
cout << "x is not 100";
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 51
prints out on the screen x is 100 if indeed x is worth 100, but if it is not -and only if not- it
prints out x is not 100.
The if + else structures can be concatenated with the intention of verifying a range of
values. The following example shows its use telling if the present value stored in x is
positive, negative or none of the previous, that is to say, equal to zero.
if (x > 0)
cout << "x is positive";
else if (x < 0)
cout << "x is negative";
else
cout << "x is 0";
For example
int main ()
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 52
{
int n;
cin >> n;
while (n>0)
return 0;
Output:
Do while Loop:
Format:
do statement while (condition);
Its functionality is exactly the same as the while loop except that condition in the do-
while is evaluated after the execution of statement instead of before, granting at least one
execution of statement even if condition is never fulfilled. For example, the following
program echoes any number you enter until you enter 0.
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 53
Example:
// number echoer
#include <iostream.h>
int main ()
unsigned long n;
do
cin >> n;
} while (n != 0);
return 0;
Output:
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 54
Enter number (0 to end): 0
You entered: 0
For Loop:
Example:
int main ()
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 55
}
return 0;
Output:
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
Jump statements
The break statement
Using break we can leave a loop even if the condition for its end is not fulfilled. It can be used to
end an infinite loop, or to force it to end before its natural end. For example, we are going to stop
the count down before its natural end (maybe because of an engine check failure?):
#include <iostream>
using namespace std;
int main ()
{
int n;
for (n=10; n>0; n--)
{
cout << n << ", ";
if (n==3)
{
cout << "countdown aborted!";
break;
}
}
return 0;
}
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 56
The continue statement
The continue statement causes the program to skip the rest of the loop in the current iteration as
if the end of the statement block had been reached, causing it to jump to the start of the following
iteration. For example, we are going to skip the number 5 in our countdown:
int main ()
{
for (int n=10; n>0; n--) {
if (n==5) continue;
cout << n << ", ";
}
cout << "FIRE!\n";
return 0;
}
Generally speaking, this instruction has no concrete use in structured or object oriented
programming aside from those that low-level programming fans may find for it. For example,
here is our countdown loop using goto:
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 57
#include <iostream>
using namespace std;
int main ()
{
int n=10;
loop:
cout << n << ", ";
n--;
if (n>0) goto loop;
cout << "FIRE!\n";
return 0;
}
The purpose of exit is to terminate the current program with a specific exit code. Its prototype is:
The exitcode is used by some operating systems and may be used by calling programs. By
convention, an exit code of 0 means that the program finished normally and any other value
means that some error or unexpected results happened.
Functions in C/C++
A function is a set of statements that take inputs, do some specific computation and produces
output.
The idea is to put some commonly or repeatedly done task together and make a function so that
instead of writing the same code again and again for different inputs, we can call the function.
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 58
The general form of a function is:
filter_none
brightness_4
Example:
Below is a simple C/C++ program to demonstrate functions.
• C
• C++
filter_none
edit
play_arrow
brightness_4
#include <stdio.h>
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 59
if (x > y)
return x;
else
return y;
// returns integer.
int main(void)
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 60
printf("m is %d", m);
return 0;
Output:
m is 20
int *swap(int*,int);
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 62
int fun(char, int);
It is always recommended to declare a function before it is used (See this, this and this for
details)
In C, we can do both declaration and definition at the same place, like done in the above example
program.
C also allows to declare and define functions separately, this is especially needed in case of
library functions. The library functions are declared in header files and defined in library files.
Below is an example declaration.
Pass by Reference Both actual and formal parameters refer to same locations, so any changes
made inside the function are actually reflected in actual parameters of caller.
Parameters are always passed by value in C. For example. in the below code, value of x is not
modified using the function fun().
• C
• C++
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 63
filter_none
edit
play_arrow
brightness_4
#include <stdio.h>
void fun(int x)
x = 30;
int main(void)
int x = 20;
fun(x);
return 0;
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 64
}
Output:
x = 20
However, in C, we can use pointers to get the effect of pass by reference. For example, consider
the below program. The function fun() expects a pointer ptr to an integer (or an address of an
integer). It modifies the value at the address ptr. The dereference operator * is used to access the
value at an address. In the statement ‘*ptr = 30’, value at address ptr is changed to 30. The
address operator & is used to get the address of a variable of any data type. In the function call
statement ‘fun(&x)’, the address of x is passed so that x can be modified using its address.
• C
• C++
filter_none
edit
play_arrow
brightness_4
# include <stdio.h>
*ptr = 30;
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 65
}
int main()
int x = 20;
fun(&x);
return 0;
Output:
x = 30
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 66
mentioning the ‘return;’ statement which would symbolise the termination of the function as
shown below:
filter_none
brightness_4
3) In C, functions can return any type except arrays and functions. We can get around this
limitation by returning pointer to array or pointer to function.
4) Empty parameter list in C mean that the parameter list is not specified and function can be
called with any parameters. In C, it is not a good idea to declare a function like fun(). To declare
a function that can only be called without any parameter, we should use “void fun(void)”.
As a side note, in C++, empty list means function can only be called without any parameter. In
C++, both void fun() and void fun(void) are same.
5)If in a C program, a function is called before its declaration then the C compiler automatically
assumes the declaration of that function in the following way:
int function name();
And in that case if the return type of that function is different than INT ,compiler would show an
error.
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 67
Main Function:
The main function is a special function. Every C++ program must contain a function named
main. It serves as the entry point for the program. The computer will start running the code from
the beginning of the main function.
filter_none
brightness_4
// Without Parameters
int main()
...
return 0;
filter_none
brightness_4
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 68
// With Parameters
...
return 0;
The reason for having the parameter option for the main function is to allow input from the
command line.
When you use the main function with parameters, it saves every group of characters (separated
by a space) after the program name as elements in an array named argv.
Since the main function has the return type of int, the programmer must always have a return
statement in the code. The number that is returned is used to inform the calling program what the
result of the program’s execution was. Returning 0 signals that there were no problems.
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 69
See this function signature of Return by Reference Below:
dataType& functionName(parameters);
where,
dataType is the return type of the function,
and parameters are the passed arguments to it.
filter_none
edit
play_arrow
brightness_4
#include <iostream>
int& returnValue(int& x)
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 70
// Print the address
// Return reference
return x;
// Driver Code
int main()
int a = 20;
int& b = returnValue(a);
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 71
// Print a and its address
// by returnValue function
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 72
// of x, which is itself an alias of a,
returnValue(a) = 13;
return 0;
Output:
x = 20 The address of x is 0x7fff3025711c
Explanation:
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 73
Since reference is nothing but an alias(synonym) of another variable, the address
of a, b and x never changes.
Note: We should never return a local variable as a reference, reason being, as soon as the
functions returns, local variable will be erased, however, we still will be left with
a reference which might be a security bug in the code.
filter_none
edit
play_arrow
brightness_4
// by reference
#include <iostream>
// Global variable
int x;
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 74
// by reference
int& retByRef()
return x;
// Driver Code
int main()
// by reference
retByRef() = 10;
// Print X
cout << x;
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 75
return 0;
Output:
10
Explanation:
Return type of the above function retByRef() is a reference of the variable x so value 10 will be
assigned into the x.
Inline function is one of the important feature of C++. So, let’s first understand why inline
functions are used and what is the purpose of inline function?
When the program executes the function call instruction the CPU stores the memory address of
the instruction following the function call, copies the arguments of the function on the stack and
finally transfers control to the specified function. The CPU then executes the function code,
stores the function return value in a predefined memory location/register and returns control to
the calling function. This can become overhead if the execution time of function is less than the
switching time from the caller function to called function (callee). For functions that are large
and/or perform complex tasks, the overhead of the function call is usually insignificant compared
to the amount of time the function takes to run. However, for small, commonly-used functions,
the time needed to make the function call is often a lot more than the time needed to actually
execute the function’s code. This overhead occurs for small functions because execution time of
small function is less than the switching time.
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 76
C++ provides an inline functions to reduce the function call overhead. Inline function is a
function that is expanded in line when it is called. When the inline function is called whole code
of the inline function gets inserted or substituted at the point of inline function call. This
substitution is performed by the C++ compiler at compile time. Inline function may increase
efficiency if it is small.
The syntax for defining the function inline is:
// function code
Remember, inlining is only a request to the compiler, not a command. Compiler can ignore the
request for inlining. Compiler may not perform inlining in such circumstances like:
1) If a function contains a loop. (for, while, do-while)
2) If a function contains static variables.
3) If a function is recursive.
4) If a function return type is other than void, and the return statement doesn’t exist in function
body.
5) If a function contains switch or goto statement.
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 77
called context.
5) Inline function may be useful (if it is small) for embedded systems because inline can yield
less code than the function call preamble and return.
Inline function disadvantages:
1) The added variables from the inlined function consumes additional registers, After in-lining
function if variables number which are going to use register increases than they may create
overhead on register variable resource utilization. This means that when inline function body is
substituted at the point of function call, total number of variables used by the function also gets
inserted. So the number of register going to be used for the variables will also get increased. So if
after function inlining variable numbers increase drastically then it would surely cause an
overhead on register utilization.
2) If you use too many inline functions then the size of the binary executable file will be large,
because of the duplication of same code.
3) Too much inlining can also reduce your instruction cache hit rate, thus reducing the speed of
instruction fetch from that of cache memory to that of primary memory.
4) Inline function may increase compile time overhead if someone changes the code inside the
inline function then all the calling location has to be recompiled because compiler would require
to replace all the code once again to reflect the changes, otherwise it will continue with old
functionality.
5) Inline functions may not be useful for many embedded systems. Because in embedded
systems code size is more important than speed.
6) Inline functions might cause thrashing because inlining might increase size of the binary
executable file. Thrashing in memory causes performance of computer to degrade.
filter_none
edit
play_arrow
brightness_4
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 78
#include <iostream>
return s*s*s;
int main()
cout << "The cube of 3 is: " << cube(3) << "\n";
return 0;
Function overloading is a feature in C++ where two or more functions can have the same name
but different parameters.
Function overloading can be considered as an example of polymorphism feature in C++.
Following is a simple C++ example to demonstrate function overloading.
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 79
#include <iostream>
void print(int i) {
void print(double f) {
int main() {
print(10);
print(10.10);
print("ten");
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 80
return 0;
Output:
Here is int 10
Here is float 10.1
Here is char* ten
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 81