GE3 Computer Science
C and C ++ Lecture series for
B.SC 3rd semester by
Subhadip Mukherjee
Department of computer science
Kharagpur College
LECTURE 13
Introduction to C++ Programming
• What is programming?
Programming is taking
A problem
Find the area of a rectangle
A set of data
length
width
A set of functions
area = length * width
Then,
Applying functions to data to solve the problem
2
Introduction to C++ Programming
Programming Concept Evolution
• Procedural
• Object-Oriented
3
Procedural Concept
• The main program coordinates calls to procedures and hands over
appropriate data as parameters.
4
Procedural Concept (II)
• Procedural Languages
• C, Pascal, Basic, Fortran
• Facilities to
• Pass arguments to functions
• Return values from functions
• For the rectangle problem, we develop a function
int compute_area (int l, int w){
return ( l * w );
}
5
Object-Oriented Concept
• Objects of the program interact by sending messages to
each other
6
Characteristics of OOPL
• Encapsulation: Combining data structure with actions
• Data structure: represents the properties, the state, or characteristics of objects
• Actions: permissible behaviors that are controlled through the member functions
Data abstraction: Process of making certain data inaccessible
• Inheritance: Ability to derive new objects from old ones
• permits objects of a more specific class to inherit the properties (data) and
behaviors (functions) of a more general/base class
• ability to define a hierarchical relationship between objects
• Polymorphism: Ability for different objects to interpret
functions differently
7
Basic C++ Extension from C
• comments
/* You can still use the old comment style, */
/* but you must be // very careful about mixing them */
// It's best to use this style for 1 line or partial lines
/* And use this style when your comment
consists of multiple lines */
• cin and cout (and #include <iostream.h>)
cout << "hey";
char name[10];
cin >> name;
cout << "Hey " << name << ", nice name." << endl;
cout << endl; // print a blank line
• declaring variables almost anywhere
// declare a variable when you need it
for (int k = 1; k < 5; k++){
cout << k;
}
8
Properties C++
• Is a better C
• Expressive
• Supports Data Abstraction
• Supports OOP
• Supports Generic Programming
• Containers
• Stack of char, int, double etc
• Generic Algorithms
• sort(), copy(), search() any container Stack/Vector/List
9
C++ Data Types
simple structured
integral enum floating array struct union class
char short int long bool
address
float double long double
pointer reference
10
Recall that . . .
char str [ 8 ];
• str is the base address of the array.
• We say str is a pointer because its value is an address.
• It is a pointer constant because the value of str itself
cannot be changed by assignment. It “points” to the
memory location of a char.
6000
‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘\0’
str [0] [1] [2] [3] [4] [5] [6] [7]
11
Addresses in Memory
• When a variable is declared, enough memory to hold a value
of that type is allocated for it at an unused memory location.
This is the address of the variable
int x;
float number;
char ch;
2000 2002 2006
x number ch
12
Obtaining Memory Addresses
• The address of a non-array variable can be obtained by using
the address-of operator &
int x; 2000 2002 2006
float number;
char ch;
x number ch
cout << “Address of x is “ << &x << endl;
cout << “Address of number is “ << &number << endl;
cout << “Address of ch is “ << &ch << endl;
13
What is a pointer variable?
• A pointer variable is a variable whose value is the address of a
location in memory.
• To declare a pointer variable, you must specify the type of value
that the pointer will point to, for example,
int* ptr; // ptr will hold the address of an int
char* q; // q will hold the address of a char
14
Using a Pointer Variable
2000
int x;
12
x = 12;
x
int* ptr; 3000
ptr = &x; 2000
ptr
NOTE: Because ptr holds the address of x,
we say that ptr “points to” x
15
*: dereference operator
int x; 2000
x = 12; 12
x
3000
int* ptr;
2000
ptr = &x;
ptr
cout << *ptr;
NOTE: The value pointed to by ptr is denoted by *ptr
16
Using the Dereference Operator
int x; 2000
x = 12; 12 5
x
3000
int* ptr;
2000
ptr = &x;
ptr
*ptr = 5;
// changes the value at the
address ptr points to 5
17
Self –Test on Pointers
4000
char ch;
A Z
ch = ‘A’;
ch
6000
char* q; 5000
q = &ch; 4000 4000
q p
*q = ‘Z’;
char* p;
p = q; // the rhs has value 4000
// now p and q both point to ch
18
Using a Pointer to Access the Elements of a
String
char msg[ ] =“Hello”;
msg
char* ptr;
3000
ptr = msg;
‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘\0’
*ptr = ‘M’ ;
‘M’ ‘a’
ptr++;
*ptr = ‘a’;
3000
3001
ptr
19
Reference Variables
Reference variable = alias for another variable
- Contains the address of a variable (like a pointer)
- No need to perform any dereferencing (unlike a pointer)
- Must be initialized when it is declared
int x = 5;
int &z = x; // z is another name for x
int &y ; //Error: reference must be initialized
cout << x << endl; -> prints 5
cout << z << endl; -> prints 5
z = 9; // same as x = 9;
cout << x << endl; -> prints 9
cout << z << endl; -> prints 9
20
Why Reference Variables
•Are primarily used as function parameters
•Advantages of using references:
• you don’t have to pass the address of a variable
• you don’t have to dereference the variable inside the called function
21
Reference Variables Example
#include <iostream.h>
void p_swap(int *a, int *b)
{
// Function prototypes
(required in C++) int temp;
temp = *a; (2)
void p_swap(int *, int *); *a = *b; (3)
void r_swap(int&, int&); *b = temp;
}
int main (void){
int v = 5, x = 10; void r_swap(int &a, int &b)
cout << v << x << endl; {
p_swap(&v,&x); int temp;
cout << v << x << endl; temp = a; (2)
r_swap(v,x); a = b; (3)
cout << v << x << endl; b = temp;
return 0; }
} 22
Dynamic Memory Allocation Diagram
High-end
Run-time allocated
Stack
memory
Heap
Compile-time
static data
allocated
memory
Program
code
Low-end
23
Dynamic Memory Allocation
• In C, functions such as malloc() are used to dynamically
allocate memory from the Heap.
• In C++, this is accomplished using the new and delete
operators
• new is used to allocate memory during execution time
• returns a pointer to the address where the object is to be stored
• always returns a pointer to the type that follows the new
24
Operator new Syntax
new DataType
new DataType [IntExpression]
• If memory is available, in an area called the heap (or free
store) new allocates the requested object or array, and
returns a pointer to (address of ) the memory allocated.
• Otherwise, program terminates with error message.
• The dynamically allocated object exists until the delete
operator destroys it.
25
Operator new
2000
char* ptr; ???
5000
ptr
ptr = new char;
5000
*ptr = ‘B’;
‘B’
cout << *ptr;
NOTE: Dynamic data has no variable name
26
The NULL Pointer
• There is a pointer constant called the “null pointer”
denoted by NULL
• But NULL is not memory address 0.
• NOTE: It is an error to dereference a pointer whose
value is NULL. Such an error may cause your program
to crash, or behave erratically. It is the programmer’s
job to check for this.
while (ptr != NULL) {
. . . // ok to use *ptr here
}
27
Operator delete Syntax
delete Pointer
delete [ ] Pointer
• The object or array currently pointed to by Pointer is
deallocated, and the value of Pointer is undefined. The
memory is returned to the free store.
• Good idea to set the pointer to the released
memory to NULL
• Square brackets are used with delete to deallocate a
dynamically allocated array.
28
Operator delete
2000
char* ptr;
5000
???
ptr = new char; ptr
*ptr = ‘B’;
5000
cout << *ptr;
‘B’
delete ptr; NOTE:
delete deallocates the
memory pointed to by ptr
29
Example
char *ptr ;
3000
ptr
ptr = new char[ 5 ]; ???
NULL
6000
???
strcpy( ptr, “Bye” );
ptr[ 0 ] = ‘u’; 6000
‘B’ ‘y’ ‘e’ ‘\0’
‘u’
delete [] ptr; // deallocates the array pointed to by ptr
// ptr itself is not deallocated
ptr = NULL; // the value of ptr becomes undefined
30
Pointers and Constants
char* p;
p = new char[20];
char c[] = “Hello”;
const char* pc = c; //pointer to a constant
pc[2] = ‘a’; // error
pc = p;
char *const cp = c; //constant pointer
cp[2] = ‘a’;
cp = p; // error
const char *const cpc = c; //constant pointer to a const
cpc[2] = ‘a’; //error
cpc = p; //error
31
Thank You
32