[go: up one dir, main page]

0% found this document useful (0 votes)
66 views166 pages

Sabyasachi Moitra

C++ is a general-purpose, high-level programming language developed by Bjarne Stroustrup in 1980. It supports object-oriented, procedural and generic programming. C++ programs can be executed across many machines with little change. The document discusses key concepts in C++ including object-oriented programming, classes, inheritance, polymorphism, and provides a simple example of a first C++ program.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views166 pages

Sabyasachi Moitra

C++ is a general-purpose, high-level programming language developed by Bjarne Stroustrup in 1980. It supports object-oriented, procedural and generic programming. C++ programs can be executed across many machines with little change. The document discusses key concepts in C++ including object-oriented programming, classes, inheritance, polymorphism, and provides a simple example of a first C++ program.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 166

C++

Sabyasachi Moitra
moitrasabyasachi@hotmail.com
Introduction

▪ Like C, C++ is a general-purpose, high-level programming language.


▪ C++ programming language was developed in 1980 by Bjarne
Stroustrup at Bell Laboratories of AT&T (American Telephone &
Telegraph), located in U.S.A.
▪ Portable, i.e., it can be executed in many machines with little bit or
no change.
▪ Supports object-oriented, procedural and generic programming.
▪ Like C, it is also a structured programming language, i.e., the
program is broken in parts or blocks.

2
OOP vs POP

OOP POP
Object Oriented Programming Procedure Oriented Programming
Programs are divided into what are known as Large programs are divided into smaller
objects. programs known as functions.
Objects may communicate with each other Data move openly around the system from
through functions. function to function.
Data is hidden & cannot be accessed by Does not have any proper way for hiding data.
external functions. Thus, more secure. Thus, less secure.
Follows bottom-up approach. Follows top-down approach.

3
OOP Terminologies

Terminology Description
Objects are the basic run-time entities in an
Object
object-oriented system.
A class is a collection of similar type of objects.
Example
Class Employee emp1;

emp1  OBJECT
Employee  CLASS

Data abstraction refers to the act of


representing essential features without
Data Abstraction
including the background details or
explanations.
Data encapsulation refers to the wrapping up
Data Encapsulation
of data & functions into a single unit.

4
Terminology Description
Inheritance is the process by which objects of one
Inheritance class acquire the properties of objects of another
class.
• Ability to take more than one form.
• Using a single function name to perform
different types of tasks is known as Function
Polymorphism Overloading.
• The process of making an operator to exhibit
different behaviors in different instances is
termed as Operator Overloading.
Connecting a method call to the method body is
known as Binding.
When type of the object is determined at compile-
Dynamic Binding
time, it is known as Static Binding.
When type of the object is determined at run-time,
it is known as Dynamic Binding.
Involves specifying the name of the object, name of
Message Passing
the function (message) & the information to be sent.

5
First C++ Program

Source Code
Output
(first.cpp)
#include<iostream.h> HELLO WORLD!!!
#include<conio.h>

void main()
{
clrscr();

cout<<"HELLO WORLD!!!";

getch();
}

6
Parameter Description
#include<iostream.h> • Includes the standard input output library
functions.
• The cout function is defined in iostream.h
file.
#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.
clrscr() Used to clear the output screen.
cout Used to print data on the console.
getch() Asks for a single character, blocks the screen
until any key is pressed.

7
Flow of C++ Program

8
Constants, Variables & Data
Types

9
Tokens

Smallest individual units in a program are known as tokens.

Keywords

Identifiers

TOKENS
Constants

Strings

Special Symbols

Operators
10
Keywords

▪ Reserved identifiers.
▪ Cannot be used as names for the program variables or other user-
defined program elements.
auto else long switch
break enum register typedef
case extern return union
char float short unsigned
const for signed void
continue goto sizeof volatile
default if static while
do int struct ….. 11
Identifiers

▪ Identifiers refer to the names of variables, functions, arrays, etc.,


created by the programmers.
▪ An identifier starts with a letter A to Z, a to z, or an underscore '_'
followed by zero or more letters, underscores, and digits (0 to 9).
▪ Punctuation characters such as @, $, and % are not allowed within
identifiers.
▪ Case-sensitive, i.e., account & ACCOUNT are two different identifiers.

12
Constants

Constants refer to fixed values that do not change during the execution
of a program.
Integer
Constants 5
Numeric
Constants
Real Constants 5.5

CONSTANTS
Single Character
Constants 'A'

Character
String Constants "ABC"
Constants

Backslash
Character '\n'
Constants
13
Variables

▪ Identifier.
▪ Data name.
▪ Used to store a data value which can be changed during program
execution.
▪ E.g. sum, avg, etc.

14
Data Types

DATA TYPES

Primary or
Derived User-defined
Fundamental

int, float, array, pointer,


typedef, enum
char, void structure, union

15
User-defined Data Type
Data Type Description Example
Allow users to define an typedef int units;
identifier that would units batch1,batch2;
represent an existing data
typedef type.
Syntax
typedef type identifier;
enum identifier enum day
{value1,…,valuen}; {Mon,Tue,...,Sun};
The identifier is a user-defined enum day
enumerated data type which
week_st,week_end;
can be used to declare
variables that can have one of
enum
the values enclosed within the
braces.
After this definition, we can
declare variables of this new
type,
enum identifier v1,…,vn; 16
Storage Class

Storage class provides information about the location and visibility of


variables within a program.
Storage Class Meaning
Local variable, known only to
auto the function in which it is
defined.
Local variable, initialized only
once & exists till the end of the
static program. Retains its value
between multiple function
calls.
Global variable, known to all
extern
functions in the file.
Local variable, stored in the
register
register. 17
Type Qualifiers

The keywords which are used to modify the properties of a variable are
called type qualifiers.
Qualifier Description Example
Tells the size of basic data long int a;
Size Qualifier
type.
Tells the sign of the unsigned int a;
Sign Qualifier
variable.
A variable declared as const int a;
constant cannot be
Constant Qualifier
modified during program
execution.
A variable declared as volatile int a;
volatile can be changed at
Volatile Qualifier any time by some external
sources during program
execution. 18
Access Modifiers

Modifier Description
private Visible to the class only.
protected Visible to the derived classes.
public Visible to the world.

19
Operators & Expressions
Operators

▪ An operator is a symbol that tells the computer to perform certain


mathematical or logical manipulations.
▪ Operators are used in programs to manipulate data & variables.
▪ They usually form a part of the mathematical or logical expressions.

21
Types of Operator
Type Operators
Arithmetic Operators +, -, *, /, %
Relational Operators ==, !=, >, <, >=, <=
Logical Operators &&, ||, !
Increment & Decrement Operators ++, --
Conditional Operator ?:
Bitwise Operators &, |, ~, ^, <<, >>
=, +=, -=, *=, /=, %=, &=, |=, ^=, <<=,
Assignment Operators
>>=
Special Operators &, *, ,, sizeof()

22
Example

23
Output

24
Input Operator(>>) VS Output
Operator(<<)

Input Operator (>>) Output Operator (<<)

25
Type Cast Operator

C++ permits explicit type conversion of variables or expressions using


the type cast operator.
Syntax
expression(type-name);
Example
avg = sum/i(float);

26
Scope Resolution Operator (::)

▪ The scope resolution operator allows access to the global version of a


variable.
▪ A major application of scope resolution operator is in the classes to
identify the class to which a member function or variable belongs.

27
Example

28
Output

29
Decision Making & Branching
Simple if Statement

▪ An if statement consists of a Boolean expression followed by one or


more statements.
▪ If the Boolean expression evaluates to true, then the block of code
inside the if statement will be executed. If the Boolean expression
evaluates to false, then the first set of code after the end of the if
statement will be executed.

31
Example

32
if…else Statement

▪ An if statement can be followed by an optional else statement, which


executes when the Boolean expression is false.
▪ If the Boolean expression evaluates to true, then the if block will be
executed, otherwise, the else block will be executed.

33
Example

34
Nested if or if…else Statements

Use of one if or if…else statement inside another if or if…else


statement(s).

35
Example

36
if…else if Ladder Statement

The if…else if statement is used to execute one code from multiple


conditions.

37
Example

38
switch Statement

A switch statement allows a variable to be tested for equality against a


list of values known as case.

39
Example

40
goto Statement

▪ A goto statement in C++ programming provides an unconditional


jump from the goto to a labeled statement in the same function.
▪ A goto statement makes difficult to trace the control flow of a
program, making the program hard to understand and modify.

41
Example

42
Decision Making & Looping
What is loop?

▪ A loop in C++ language is used to execute a block of code or a part of


the program for several times.
▪ It saves code.

44
Types of Loops

LOOPS

while do while for


45
while Loop

▪ Iterates the code until the condition is false.


▪ Condition is given before the code. So the code may be executed 0 or
more times.

46
Example

Source Code Output


#include <iostream> 1
#include <conio.h>
2
void main() 3
{ 4
int i=1; 5
clrscr(); 6
7
while(i<=10) 8
{
cout<<i <<"\n";
9
i++; 10
}

getch();
}

47
do while Loop

▪ Iterates the code until the condition is false.


▪ Condition is given after the code. So at least once the code is
executed whether the condition is true or false.

48
Example

Source Code Output


#include <iostream> 1
#include <conio.h>
2
void main() 3
{ 4
int i=1; 5
clrscr(); 6
7
do 8
{
cout<<i<<"\n";
9
i++; 10
} while (i <= 10) ;

getch();
}

49
for Loop

▪ Iterates the code until the condition is false.


▪ Initialization, condition and increment/decrement is given before the
code. So the code may be executed 0 or more times.

50
Example

Source Code Output


#include <iostream> 1
#include <conio.h>
2
void main() 3
{ 4
int i=1; 5
clrscr(); 6
7
for(i=1;i<=10;i++) 8
{
cout<<i <<"\n";
9
} 10

getch();
}

51
break VS continue

break continue
▪ Can appear in both switch and ▪ Can appear only in loop
loop statements. statements.
▪ When encountered, terminates ▪ When encountered, gets the
the block and gets the control control to the next iteration of
out of the switch or loop. the loop.

52
Example

break continue
#include <iostream.h> #include <iostream.h>
#include <conio.h> #include <conio.h>

void main() void main()


{ {
int i=1; int i=1;

clrscr(); clrscr();

for(i=1;i<=10;i++) for(i=1;i<=10;i++)
{ {
if(i==5) if(i==5)
break; continue;

cout<<" "<<i; cout<<" "<<i;


} }

getch(); getch();
} }

1234 1 2 3 4 6 7 8 9 10

53
Arrays
What is an Array?

▪ Collection of homogeneous (similar) elements (data) in a contiguous


memory location.
▪ Linear Data Structure
- A data structure (data organization and storage format that enables
efficient access and modification) is said to be linear if the elements
form a sequence.

55
Example (1D Array)

56
Example (2D Array)

57
Manipulating Strings
C++ Strings

C++ provides following two types of string representations:−


- The C-style character string.
- The string class type introduced with Standard C++.

59
C-Style Character String

Strings are actually one-dimensional array of characters terminated by


a null character '\0'.
Declaration Syntax
char ch[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

char ch[6] = "Hello";

60
Example
Source Code Output
#include<iostream.h> Char Array Value is: Hello
#include<conio.h>
String Literal Value is: Hello
void main ()
{
char ch[6]={'H', 'e', 'l', 'l', 'o', '\0'};
char ch2[6]=“Hello";

clrscr();

cout<<"Char Array Value is: "<<ch;


cout<<"\nString Literal Value is: "<<ch2);

getch();
}

61
The getline() Function

▪ The getline() function reads string from user (similar to cin).


Example Output

#include<iostream.h> Enter your name: Bob Dylan


#include<conio.h> Your name is: Bob Dylan
void main()
{
char name[50];
clrscr();
cout<<"Enter your name: ";
cin.getline(name,50);
cout<<"Your name is: "<<name;
getch();
}

62
Some String Handling Functions
Function Description
strlen() Finds the length of a string.
strcpy() Copies one string over another.
strcat() Concatenates two strings.
strcmp() Compares two strings.
…..

63
Example

64
String Class in C++

In C++, string is an object of string class that represents a sequence of


characters.
Example Output

#include<iostream> Your name is: Bob Dylan


#include<string>
using namespace std;
int main()
{
string name="Bob Dylan";
cout<<"Your name is:
"<<name;
return 0;
} 65
Example

Output

Length of string is: 5


Value of second string is: Hello
Value of first string is: HelloWorld
Strings are not equal

66
User-defined functions
What is Function?

▪ A function is a group of statements that together perform a task.


▪ It can be called many times.
▪ It provides code reusability and code optimization.

68
Types of Functions

Function
created by
programmer
getch()

Library User-defined
Function Function
69
Example

70
Passing Array to Function

71
What is Recursion?

▪ When function is called within the same function, it is known as


recursion.
▪ The function which calls the same function, is known as recursive
function.

72
Example

73
Function Overloading

▪ Overloading refers to the use of the same thing for different


purposes.
▪ C++ supports overloading of functions, i.e., using the same function
name to create functions that perform a variety of different tasks.
▪ Using the concept of function overloading, we can design a family of
functions with one function name by changing the number of
arguments & the data type.
▪ Also termed as Function Polymorphism.
[NOTE: Function Overloading is not possible by changing the return
type of the function only.]

74
Example

75
Inline Function

▪ An inline function is a function that is expanded in line when it is


invoked, i.e., the compiler replaces the function call with the
corresponding function code.
▪ Inline expansion makes a program run faster because the overhead of
a function call & return is eliminated.
▪ However, it makes the program to take up more memory, as the
statements that define the inline function are reproduced at each
point where the function is called.

76
Example

77
Some Terminologies
Term Description
Parameters that appear in function calls.
Actual Parameters
s=add(10,20);
Parameters that appear in function
Formal Parameters declarations.
int add(int a,int b){…}
The point at which the function is being
invoked or called is known as the calling
Calling Function function.
s=add(10,20);

The function which is being executed due


to the function call is known as the called
Called Function function.
int add(int a,int b){…}
78
Structures & Unions

79
What is a Structure?

▪ User defined datatype.


▪ Allows us to hold different type of elements.
▪ Each element of a structure is called a member.
▪ Widely used to store student information, employee information,
product information, book information etc.
▪ Similar to class.

80
Example

81
Array of Structures

▪ Used to store many information of different data types.


▪ Also known as collection of structures.

82
Example

83
What is a Union?

▪ Like Structure, Union is also a user defined datatype that is used to


hold different type of elements.
▪ Unlike Structure, Union occupies the memory of the largest member
only, i.e., it shares the memory of the largest member.

84
Example

85
Structure VS Union
Structure Union
A structure is defined with struct keyword. A union is defined with union keyword.
The size of a structure variable is equal to the sum of The size of a union variable is equal to the size of its
the individual sizes of its members. largest member.
Structure members are allocated distinct memory. Union members share common memory space.

86
Pointers
What are Pointers?

▪ Derived data type, i.e., built from one of the fundamental data types
available in C++.
▪ Contains memory address of another variable as its value.

88
Example

89
Pointer to Pointer

A pointer referring to the address of another pointer, i.e., a pointer can


point to the address of another pointer which points to the address of a
value.

90
Example

91
Pointers & Arrays

92
Array of Pointers

▪ An indexed set of variables in which the variables are pointers, i.e., a


reference to a location in memory.
▪ Consider the following array of strings:
char name[3][25];
Here, name is a table containing three names, each with a maximum
length of 25 characters (including null character).
Thus, the total storage requirement for the name table is 75 bytes,

93
Therefore, instead of making each row a fixed number of characters, we can make it a pointer
to a string of varying length,
char *name[3]={
"New Zealand",
"Australia",
"India“
};

Here, name is an array of three pointers to characters, each pointer pointing to a particular
name,
name[0] New Zealand
name[1] Australia
name[2] India

94
Thus, allocating only 28 bytes of memory,
N e w Z e a l a n d \0
A u t r a l i a \0
I n d i a \0

95
Example

96
Call by Value VS Call by Reference
Call by Value Call by Reference
A copy of the value is passed to the function. An address of the value is passed to the function.
Changes made inside the function is not reflected on Changes made inside the function is reflected outside
other functions. the function also.
Actual and formal arguments will be created in Actual and formal arguments will be created in same
different memory locations. memory location.
Original value is not modified. Original value is modified.

97
Example (Call by Value)

98
Example (Call by Reference)

99
Static Memory Allocation VS Dynamic
Memory Allocation
Static Memory Allocation Dynamic Memory Allocation
Memory allocated at compile time. Memory allocated at run time.
Memory can’t be increased during execution . Memory can be increased during execution .

100
Dynamic Memory Allocation Functions

▪ malloc()
- Allocates single block of requested memory.
- Doesn't initialize memory at execution time, so it has garbage value
initially.
ptr=(cast-type*)malloc(byte-size)

▪ calloc()
- Allocates multiple blocks of requested memory, each of same size.
- Initially initialize all bytes to zero.
ptr=(cast-type*)calloc(number,byte-size)
101
Dynamic Memory Allocation Functions (2)

▪ realloc()
- Reallocates the memory occupied by malloc() or calloc() functions.
ptr=realloc(ptr, new-size)

▪ free()
- Frees the dynamically allocated memory.
free()

102
Example (malloc())

103
Example (calloc())

104
Example (realloc())

105
Classes & Objects
What is a Class?

▪ A class is a way to bind the data & its associated methods together.
▪ General form of a class definition:

107
Access Modifiers in C++

Access Modifier Description


private Accessible only within the class.
similar to a private member but they can
protected be accessed in child classes which are
called derived classes.
public Accessible everywhere.

108
What is an Object?

▪ An object is an entity that has state and behaviour.


▪ General form of a object declaration:

class-name object-name;

109
Example

110
Array within Class

111
Array of Objects

112
Static Member Variable

▪ Initialized to zero when the first object of the class is created.


▪ Only one copy of the variable is created for the entire class & shared
by all the objects of that class.

113
Example

114
Static Member Function

▪ Can have access to only static members (functions/variables)


declared within the same class.
▪ Can be called using the class name instead of its objects:

class-name :: function-name;

115
Example

116
Friend Function

▪ If a function is defined as a friend function in C++ then the protected


and private data of a class can be accessed using the function.
▪ Invoked like normal function without the help of any object.
▪ Can be declared either in private or in public part of a class.
▪ It has the objects as arguments.
▪ Can’t access the member names directly & has to use an object name
& dot membership operator with each member.

117
Example

118
Constructor & Destructor
What is Constructor?

▪ A special type of function that is used to initialize the object.


▪ It is invoked at the time of object creation.

120
Types of Constructor

CONSTRUCTOR
constructor
constructor with
without
parameters
parameters

Default Parameterized

121
Default Constructor

Source Code Output


#include<iostream.h> Default Constructor Invoked
#include<conio.h>
Default Constructor Invoked
class Employee
{
public:
Employee()
{
cout<<"Default Constructor
Invoked"<<endl;
}
};
void main()
{
Employee e1; //creating an object of
Employee
Employee e2;
getch();
}
122
Parameterized Constructor

Source Code Output


#include<iostream.h>
#include<conio.h> 101 Sonoo 890000
class Employee {
102 Nakul 59000
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
Employee(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
void main()
{
Employee e1 =Employee(101, "Sonoo", 890000);
//creating an object of Employee
Employee e2=Employee(102, "Nakul", 59000);
e1.display();
e2.display();
getch();
} 123
Constructor Overloading

▪ A technique in C++ in which a class can have any number of


constructors that differ in their parameter lists.
▪ The compiler differentiates these constructors by taking into account
the number of parameters in the list and their type.

124
Example

125
Copy Constructor

The Copy Constructor is a constructor which creates an object by


initializing it with an object of the same class, which has been created
previously.

126
Example

127
Constructor VS Function

Constructor Function
Constructor is used to initialize the state Function is used to expose behaviour of
of an object. an object.
Constructor must not have return type. Function must have return type.
Constructor is invoked implicitly. Function is invoked explicitly.
Constructor name must be same as the Function name may or may not be same
class name. as class name.

128
What is Destructor?

▪ Destroys the objects that have been created by a constructor.


▪ Frees memory of an object which is out of its scope.

129
Example

130
this Pointer

▪ Refers to the current instance or object of the class.

131
Example

132
Operator Overloading

133
What is Operator Overloading?

▪ Operator Overloading is used to overload or redefine most of the


operators available in C++.
▪ The advantage of operator overloading is to perform different
operations on the same operand.

return-type operator op(arglist)


{
//function_body
}

134
Example

135
Inheritance

136
What is Inheritance?

▪ Inheritance is a process in which one object acquires all the


properties and behaviours of its parent object automatically.
▪ We can reuse, extend or modify the attributes and behaviours which
are defined in other class.
▪ The class which inherits the members of another class is called
derived class and the class whose members are inherited is called
base class.

137
Types of Inheritance

138
Single Inheritance

139
Visibility of Inherited Members

140
Multiple Inheritance

141
Hierarchical Inheritance

142
143
Multilevel Inheritance

144
Hybrid Inheritance
(combination of more than one inheritance)

145
Virtual Base Class

▪ When a class is made virtual base class, only one copy of that class is
inherited, regardless of how many inheritance paths exist between
the virtual base class & a derived class.
▪ Thus duplication of inherited members due to multipath inheritance
can be avoided.

146
Example

147
148
Abstract Class

▪ An abstract class is one that is not used to create objects.


▪ Designed only to act as a base class (to be inherited by other classes).

149
Example

150
Exception Handling

151
What is an Exception?

▪ An Exception is a problem that arises during the execution of a


program (e.g., attempt to divide by zero).
▪ An Exception Handling is a process to handle such runtime errors.
▪ In C++ 3 keywords are used to perform exception handling:-
- try
- catch
- throw

152
Exception Handling Mechanism

153
Example

154
Template
What is a Template?

▪ Templates are the foundation of Generic Programming.


- Generic Programming is an approach where generic types are used
as parameters in algorithms so that they work for a variety of
suitable data types & data structures.
▪ A template is considered as a kind of macro.
- A macro is a fragment of code that is given a name & can be used in a
program by using the name.
▪ When an object of a specific type is defined for actual use, the
template definition for that class is substituted with the required
data type.

156
▪ The general format of a class template is:
template<class T>
class classname
{
//body
};
▪ The syntax for defining an object of a template class is:
classname<type> objectname(arglist);

157
Example (template class)

158
Example (function template)

159
Working with Files
What is File?

▪ A file is a collection of related data stored in a particular area on the


disk.
▪ Until now we have been using the iostream standard library, which
provides cin and cout methods for reading from standard input
(keyboard) and writing to standard output (screen) respectively.
- It becomes cumbersome & time consuming to handle large volumes of
data through terminal.
- The entire data is lost when either the program is terminated or the
computer is turned off.

161
▪ To overcome the discussed problems the concept of files is employed
in C++ programming.
▪ Reading from and writing to a file requires the standard C++ library
called fstream.
▪ The data types defined in fstream library are:
Data Type Description
Used to create files, write information to
fstream
files, and read information from files.
ifstream Used to read information from files.
Used to create files and write
ofstream
information to the files.
162
Writing to a File

163
Reading from a File

164
Some File Opening Modes

Mode Description
ios::app Append mode
ios::ate Go to the end-of-file on opening
ios::in Open a file for reading
ios::out Open a file for writing
ios::trunc Deletes the contents of the file if it exists
…..

165
References

▪ E Balagurusamy, Object Oriented Programming with C++, 5th


Edition, McGrawHill
▪ Courtesy of JavaTPoint – C++ Tutorial. URL:
https://www.javatpoint.com/cpp-tutorial
▪ Courtesy of TutorialsPoint – C++ Tutorial. URL:
https://www.tutorialspoint.com/cplusplus/
▪ Courtesy of JavaTPoint – Java Tutorial. URL:
https://www.javatpoint.com/java-tutorial

166

You might also like