Basic Structure of C++
Basic Structure of C++
Structure of C++
1
Contents
Simple Programs
New Things in C++
Pointers and Memory Allocation
2
A Simple Program
// A Simple Hello, World Program
#include <iostream.h>
main()
{
/* the output statement */
cout << “Hello, World!”;
}//ex2hello.cpp
3
4
5
Function Prototype
void Do_Task(int a, float b);
main()
{int x = 5;
float y = 10.65;
Do_Task(x, y);
}
void Do_Task(int a, float b)
{cout <<a+b<<‘\n’ ;}//ex2func.cpp
6
7
Declarations and Definitions
8
Example
definitions
int n;
int sum (int a , int b) { return a+b;}
const long count = 0;
declarations
extern int n;
int sum(int a, int b);
extern long count;
9
Definitions of structures, enumerated
constants, and classes Do Not
Allocate Storage.
struct Z {float r};
enum {up, down};
Class Student{long id;
char lastname[30];
}
10
Storage Duration
automatic storage duration
void sub() {int n;
auto int m; }
Static storage duration
Example:static.cpp
Dynamic storage duration
new and delete
11
Parameters and Arguments
12
Call By Value
#include <iostream.h>
void increment(int)
main()
{
int i=2;
increment(i);
cout << “i = “ << i;
}
void increment(int x) { x++; }//ex2callbyval.cpp
13
14
Call By Reference
#include <iostream.h>
void increment(int &)
main()
{
int i=2;
increment(i);
cout << “i = “ << i;
}
void increment(int& x) { x++; }//ex2callbyref.cpp
15
16
Constant Reference
Parameter
void fun(const int & x)
{
...
}
19
Example
// Find the sum of numbers in a range of values
// Between “lower” and “upper” using increment “inc”
20
21
22
New Things in C++
New Keywords
Cast operator
Functions
Type-safe linkage
Linking to C functions
23
New Keywords
asm, bool, catch, class, const_cast, delete,
dynamic_cast, explicit, false,friend, inline,
mutable, namespace, new, operator,
private, protected, public, reinterpret_cast,
static_cast, template, throw, true, try, typeid,
typename, using, virtual, wchat_t, …
bitand, and, bitor, or, xor, compl, ane_eq,
or_eq, xor_eq, not, not_eq
“__” and “_C” are reserved in C++, do not
use these as identifiers
24
New Keywords
Comments: /*…*/ or //
char for characters: int n += ‘a’;
Variables may be defined everywhere
before you use.
…
float sum = 0.0;
for (int k =0; k<count; k++; )
sum +=array[k]
…..
25
Cast operator
float g = (float) i/2;
float g = float ( i ) /2;
BUT:
void *v;
float *f;
…
f = v; //error;
f = (float *) v; //ok, explicit casting for pointer
26
Functions
In C++, you must at first declare (or
define) and then call.
The function name and its argument
type must be consistent with the
declaration or definition.
27
Linkage
Type-safe linkage
The linker checks for consistency
between the call and the definition.
Linking to a C function
extern “C” must be used to link a C
function.
28
C++ Features
Named Constants
Enumerated Constants
Reference Parameters
I/O Streams
29
Named Constants
Only one method in C:
#define ArraySize 100;
Another way in C++:
const ArraySize =100;
Again in C++:
constant can be used in local scope.
const is used when a value cannot
be changed.
30
Named Constants
C/C++ Differences in using constants
extern const int count = 5; //extern
//linkage
static const float average = 0.5;
//internal //linkage
const float f; //error!, invalid!
extern const float f; //ok, extern linkage
const int count = 100; //ok, internal
//linkage
31
Enumerated Constants
Without tag:
enum {red, yellow, blue};
int wincolor = red;
With tag:
enum priColors {red, yellow, blue};
priColors wincolor;
wincolor = red; //ok
wincolor = 0; //error
32
Enumerated Constants
enum tag_name{enum_list};
enum {running, standby, offline, inoperative}
enum {running=0, standby=99, offline=50,
inoperative=10}
33
enum const
const int idSize = 7;
const int nameSize = 30;
Class Student {
//…
private:
char id[idSize+1];
char name[nameSize +1];
}
34
enum const
Class Student {
//…
private:
enum {idSize =7, nameSize =30};
char id[idSize+1];
char name[nameSize +1];
}
35
Tag Names
enum TStatus {running, standby, offline,
inoperative}
TStatus currentStatus;
currentStatus = running; //ok
currentStatus = 1; //error
int n = currentStatus;
unsigned x = standby;
float f = inoperative;
36
Reference Parameters
A reference parameter is a function
parameter that is an alias for the
corresponding argument passed to
the function.
Examples:
ex2ref.cpp and ex2refc.c
37
#include <iostream.h> ex2ref.cpp
void swap(int &x, int &y)
{
int temp = x;
x = y;
y = temp;
}
main()
{ int a = 10, b = 20;
swap(a,b);
cout << "a = " <<a<< ", b = "<<b << "\n";
}
38
#include <stdio.h> ex2refc.c
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
main()
{ int a = 10, b = 20;
swap(&a,&b);
printf("C version: a = %d, b = %d \n ",a,b);
}
39
I/O Streams
A stream is a sequence of bytes that
may be either input to a program or
output from a program.
cin, cout, and cerr are three standard
devices for input (keyboard), output
and error output (tied to the screen).
iostream.h (or .hxx, or hpp)should be
included.
40
Stream I/O
Buffered(cin, cout), unbuffered(cerr)
Buffered characters should be
flushed.
Unbuffered characters can be seen
immediately.
41
Stream Output
<< operator, by default formats
int n;
cout<<n;
float f;
cout<< f;
File: ex2cout.cpp
42
43
44
Input Stream
>> operator
int n;
cin >>n;
Skip whitespace, eg. Spaces, tabs,
and newlines.
Example: ex2cin.cpp
45
46
47
Pointers and Dynamic Memory
Allocation
Constant Pointers
Pointer Conversions
Allocating Memory
Arrays and Dynamic Allocation
48
Constant Pointers
The object can not be modified when
this pointer used for access.
int n = 0;
const int * cp = &n;
* cp = 30; // Error!
n = 30; //OK!
//ex2constp.cpp
49
50
51
52
Constant Pointers
The same for parameters
size_t strlen(const char * str)
const char * aStr = “ABCDEFG”;
char name [] = “Johnson”;
unsigned n;
n = strlen(aStr);
n = strlen(name);
Cannot pass a pointer to a constant to
a function with a parameter that is a
pointer to a non-constant
53
Example
char * strcpy(char * dest, const char *
source);
…
const char * des;
const char * sou;
strcpy(des, sou); //error!
54
Const-Qualified Pointers
char message[80];
char *cost sp = message;
sp++; //error
strcpy(sp, “A new message”); //OK
55
Const-Qualified Pointers
char message[80];
const char *cost sp = message;
sp++; //error
strcpy(sp, “A new message”); //error
//ex2cqptr.cpp
56
57
58
59
Four ways to declare a pointer
60
Functions returning Pointers to
Constants
The variable receiving the returned
value should also be a pointer to a
constant.
class Student{
public:
const char * GetName() const;
// …
}
61
Functions returning Pointers to
Constants
Student s;
char * ncName = S.GetName(); //error
const char * cName = S.GetName();
//OK
62
Pointer Conversions
Pointers to Array Elements
Void Pointers
References to Pointers
63
Pointers to Array Elements
Pointer is related to a type or a class.
The pointer pointing to an array can be
incremented and decremented.
float flist[] = {10.3, 13.2, 4, 9.6};
float * fp = flist;
fp++;
cout<<fp;
//ex2ptrarray.cpp
64
65
66
Pointers to Array
float flist[] = {10.3, 13.2, 4, 9.6};
float * fp = flist;
int * ip = (int * )fp;
ip++;
cout<<*ip;//ex2ptrarrayint.cpp
//The result is the integer value
//transformed from the float value
67
68
69
Void Pointers
To obtain flexibility of types
void * memcpy ( void *dest, const void *
src, size_t nbytes)
const unsigned ArraySize = 500;
long arrayOne[ArraySize];
long arrayTwo[ArraySize];
memcpy (arrayOne, arrayTwo,
ArraySize* sizeof(long));
70
Void Pointers
Casting required
int *p;
void *v = p;
p = (int *) v; //cast needed
71
References to Pointers
#include <iostream.h>
void FindNext( char * & p, char delim )
{ while( *p && (*p != delim) )
p++;}
int main()
{char str[] = "abc,def,ghi,jkl";
for(char * p = str; *p; p++)
{ FindNext( p, ',' );
cout << p << endl;}
return 0;
} //ex2refptr.cpp
72
73
Allocating memory
Static and Dynamic Allocation
Allocating memory for objects at
compile time-- Static Allocation
Allocating memory for objects at run
time-- Dynamic Allocation
74
Static and Dynamic
Allocation
Deallocating storage refers to
releasing a block of memory whose
address is in a pointer variable--
deleting a pointer.
Fragmentation: is the condition where
enough objects have been allocated
and deallocated from the heap so that
gaps occur between allocated objects.
75
The new Operator
76
The delete Operator
The delete operator is used to
deallocate memory space (created
dynamically)
delete p;
delete [] array;
77
Allocating a Vector of
Storage
int* p = new int [5] ;
for (int j=0; j < 5; ++j) 0
10 p
*(p + j) = 10 * j; 20
30
for ( j=0 ; j < 5; j++ ) 40
cout << p[ j ];
delete [] p;
//ex2new.cpp
78
79
80
Storage Duration and Pointers
the storage duration of a pointer itself
and the memory that it addresses are
distinct issues.
if (a>b)
{float *fp = new float;} //temporary in
//the brackets, the storage it point to
//is unavailable out of the brackets
This is called memory leak.
81
Storage Duration and Pointers
char * globalName;
main()
{ globalName = new char[50];
//…
}
The memory remains available until
either it is deleted or the program
ends.
82
Dealing with memory exhaustion
83
Arrays and Dynamic Allocation
One-Dimensional Arrays
const unsigned arraySize= 1000;
// …
float *myArray = new float[ArraySize];
//…
delete [] myArray;
84
Two-Dimensional Arrays
Example:
int (*table)[10] = new int[3][10];
delete [] table;
Array of Pointers
const unsigned NumRows = 50;
const unsigned RowSize = 1000;
int * samples[NumRows];
for (unsigned i = 0; I<NumRows; I++)
samples[i]= new int[RowSize];//See the graph
85
Array of Pointers
Static Allocation Dynamic Allocation
0
1
2
3
.
.
. ......
N-1
N=50
1000
86
Initialization
for (unsigned i = 0; i<NumRows; i++)
for (unsigned j = 0; j<RowSize; j++)
samples[i][j]=0;
87
Ragged Array
Static Allocation
Dynamic Allocation
0
1
2
3
.
.
. ......
N-1
N=50
Various
88
Ragged Array
// ex2ragged.cpp,
#include <iostream.h>
#include <fstream.h>
#include <string.h>
int main()
{ifstream infile( "ragged.cpp" );
if( !infile ) return 1;
const unsigned NumRows = 100;
const unsigned BufSize = 1024;
char * names[NumRows];
89
char buffer[BufSize]; Ragged
unsigned j = 0;
while(!infile.eof())
{
infile.getline( buffer, BufSize );
names[j] = new char[ strlen(buffer)+1 ];
strcpy( names[j], buffer );
if( j++ >= NumRows ) break;
}
for(unsigned m = 0; m < j; m++)
cout << names[m] << '\n';
return 0;
} // ex2ragged.cpp,
90
91
Graph Example
A graph is defined as a collection of
nodes (or vertices) that are
connected by arcs (or edges).
2
4
1 3
92
Graph Applications
A series of states and transitions
between states.
Relationships between independent
entities.
93
Adjacent Matrix
j 0 1 2 3 4
i
0 0 1 0 0 1
1 1 0 (M11) 1 0 0
2 0 0 0 (M22) 1 (M23) 0
3 0 1 (M32) 0 0 0
4 1 0 0 0 0
94
Adjacent Matrix in C++
const int ROWS = 5;
const int COLS = 5;
int adjacent[ROWS][COLS]=
{ (0, 1, 0, 0, 1),
(1, 0, 1, 0, 0),
(0, 0, 0, 1, 0),
(0, 1, 0, 0, 0),
(1, 0, 0, 0, 0)}
95
In Memory
0
1
0
0
1
1
0
1
Adjacent[0][0] 0
0
0
0
0
1
0
0
1
0
Adjacent[2][4] 0
0
1
0
0
0
0
96
Sum of the Matrix
int sum = 0;
for (int i =0; i< ROWS; i++)
for (int j =0; j< COLS; j++)
sum = sum + adjacent[i][j];
useful for counting the total length of
roads among different cities.
97