You are on page 1of 245

Outline

Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Appendix
2
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Appendix
Hello world
C/C++ files
Entry point
C/C++ libraries
Source compile process
3
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Appendix
Variables and constant
Primary data type
Array Pointer String
Data structure: enum union - struct
Function
Namespace
4
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Appendix
Class & Object
Inheritance
Polymorphism
Operator overloading
Class static member
5
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Appendix
Recall pointer
Memory leak
6
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Appendix
Forward declaration
Standard IO Console IO & FILE
Template
Type casting
Exception handling
Endian
STL introduction
GNU GCC/G++
7
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Hello world!
C/C++ files
Entry point
C/C++ libraries
Source compile process
8
Outline
Preparation
Getting Start
Basic Data Structure
OOP
Memory management
Rest of C/C++ features
Hello world!
C/C++ files
Entry point
C/C++ libraries
Source compile process
9
Hello world using VS
10
Hello world
# include <stdio.h>
void main()
{
printf("Hello world");
}
main.cpp
Use standard IO lib
Entry point
Print to console screen
11
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Hello world!
C/C++ files
Entry point
C/C++ libraries
Source compile process
12
C/C++ source files
Header file (.h)
aka include file
Hold declarations for other files
use (prototype)
Not required
#include "stdio.h"
void Todo1();
void Todo2();
# include "header.h"
void Todo1()
{
Todo2();
}
void Todo2(){}
void main()
{
Todo1();
}
Source file (.c / .cpp)
Content implementation
Required
13
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Hello world!
C/C++ files
Entry point
C/C++ libraries
Source compile process
14
Entry point
Required unique entry point
The most common is: main
void main()
{
// your code here
}
Form1.cpp
int main(int n, char ** args)
{
// your code here
}
Form2.cpp
1>LINK : fatal error LNK1561: entry point
must be defined
Error when no entry point is defined
15
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Hello world!
C/C++ files
Entry point
C/C++ libraries
Source compile process
16
C/C++ standard library
C/C++ support a set of internal
basic library, such as
Basic IO
Math
Memory handle

For using, include the header
file
#include <>
#include ""
#include "stdio.h"
void main()
{
printf("hello");
}
17
C header C++ header
<assert.h> <cassert>
Content assert macro, for debugging
<Ctype.h> <cctype>
For character classification/convert functions
<Errno.h> <cerrno>
For testing error number
<float.h> <cfloat>
Floating point macros
<limits.h> <climits>
Define range of value of common type
<math.h> <cmath>
Mathematical functions
<setjmp.h> <csetjmp>
Provide non-local jumps for flow control
<signal.h> <csignal>
Controlling various exceptional conditions
<stdlib.h> <cstdlib>
Standard lib
<stddef.h> <cstddef>
<stdarg.h> <cstdarg>
<stdio.h> <cstdio>
Standard IO
<string.h> <cstring>
Manipulating several kinds of string
<time.h> <ctime>
Converting between time & date formats
<wchar.h> <cwchar>
<wctype> <cwctype>
18
C/C++ user-defined lib
Not C/C++ standard lib
Come from:
Third-party
User own
In common, include 2 parts
.h files & .lib files: for developer
.dll file (dynamic library): for end-user
error LNK2019: unresolved external symbol
Error caused when forget to add .lib file
19
C/C++ user-defined lib (cont.)
For using
Include .h files
Inform .lib files to compiler
Copy all .dll file to (if any) :
osame folder with execute file, or
oto system32 (windows) not recommend
20
Declare path to .lib
Import user-defined library
Visual studio
21
Import user-defined library
Visual studio
Declare .lib file
22
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
C/C++ files
Entry point
C/C++ libraries
Hello world!
Source compile process
23
Process
Source
.h/.c/.cpp
preprocess
Preprocessed
source
(c/cpp)
Compile
.o / .obj
(object file)
Linker
Executable/
lib
Tools:
Visual Studio: cl.exe (Press F7 / F5)
GNU GCC: gcc/ g++
24
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Variables and constant
Primary data type
Array Pointer - String
Data structure: enum union - struct
Function
Namespace
25
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Variables and constant
Primary data type
Array Pointer - String
Data structure: enum union - struct
Function
Namespace
26
Variable classification
Scope:
Local variable
Global variable
Static variable
Storage class specifier
auto
static
register
extern
27
Global & local
int mGlobalVar;
void Foo()
{
int localVar;
printf("Foo : %d %d\n",
localVar, mGlobalVar);
}
int main()
{
int localVar = 1;
printf("Main: %d %d\n",
localVar, mGlobalVar);
mGlobalVar = 1;
Foo();
return 1;
}
Global variable
Available in all of program
Set default value to zero
Local variable
NO default value
Available inside block
Main: 1 0
Foo : 2280752 1
Command prompt
28
Auto variable
As default, a variable is a auto variable
int myVar auto int myVar
Go out of scope once the program exits from the
current block
29
Static variable
Allocated when the program
starts and is deallocated when
the programends.
Default value is zero (0)
#include <cstdio>
static int s_iGlobalStatic;
void Foo()
{
static int s_iLocalStatic;
printf("Foo: called %d\n",
s_iLocalStatic++);
}
int main()
{
int localVar = 1;
printf("Main: %d\n",
s_iGlobalStatic);
Foo();
Foo();
Foo();
return 1;
}
Main: 0
Foo: called 0
Foo: called 1
Foo: called 2
Command prompt
30
Register variable
Stored in a machine register if
possible
Usually used in for iterator
for improve performance
int main()
{
int sum = 0;
for (register int i = 0;
i < 100;
i++)
{
sum += i;
}
printf("Sum = %d\n", sum);
return 1;
}
31
Extern variable
Specify that the variable is
declared in a different file.
Compiler will not allocate
memory for the variable
Avoid duplicate declaration
Share (global) variable for
multiple .cpp files
#include <cstdio>
extern int m_iExternVar;
int main()
{
printf("Value = %d\n",
m_iExternVar);
return 1;
}
main.cpp
int m_iExternVar = 100;
Extern.cpp
Value = 100
Command prompt
32
Constant
Variable's value is constant
To prevent the programmer from modifying
int const k_Hello = 0;
int main()
{
k_Hello = 10;
}
error C3892: 'k_Hello' : you cannot assign to
a variable that is const
Error
33
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Variables and constant
Primary data type
Array Pointer - String
Data structure: enum union - struct
Function
Namespace
34
Primitive data type
(32bits processor)
Type Size Range
void n/a
char 1 byte unsigned char: -128 127
signed char: 0255
short 2 bytes unsigned short: 0 (2
16
-1)
signed short: -2
15
(2
15
1)
int 4 bytes
-2
31
(2
31
1)
unsigned int: 0 (2
32
-1)
signed int: -2
31
(2
31
1)
long 4 bytes
-2
31
(2
31
1)
unsigned long: 0 (2
32
-1)
signed long: -2
31
(2
31
1)
long long 8 bytes
-2
63
(2
63
1)
unsigned long long: 0 (2
64
-1)
signed long long: -2
63
(2
63
1)
bool 1 byte True /false (non-zero / zero)
float 4 bytes
double 8 bytes
35
New type definition
Use typedef
36
typedef int Mytype;
typedef int MyArr[5];
Mytype var1;
MyArr arr;
sizeof operator
0 Return size (in byte) of a type, data structure, variable
int sizeInt = sizeof(int);
int sizeLong = sizeof(long);
char a;
int sizeA = sizeof(a);
Return 4
Return 4
Return 1
37
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Variables and constant
Primary data type
Array Pointer - String
Data structure: enum union - struct
Function
Namespace
38
Array
Used to store consecutive values of the same data types
int b[4] = {1, 2, 3, 4};
n-dimensions array
int b[<s
1
>][<s
2
>][<s
n
>] s
i
MUST BE constant
Index of array is counted from0 to (s
i
-1)
C/C++ do not handle out-of-range exception
int b[4] = {1, 2, 3, 4};
for (int i = 0; i < 4; i++)
{
printf("%d\n", b[i]);
}
printf("%d\n", b[10]);
b[10] = ?
39
Array Assignment
40
int a[4] = {1, 2, 3, 4};
int a[] = {1, 2, 3, 4};
int a[4];
a[0] = 1;
a[1] = 2;
a[2] = 3;
a[3] = 4;
int a[4] = {1};
a[0], a[1],
a[2], a[3] = ?
int a[4];
memset(a, 0, 4*sizeof(int));
Array Assignment
2D Array
41
int a[3][2];
a[0][0] = 1;
a[0][1] = 2;
a[1][0] = 3;
a[1][1] = 4;
a[2][0] = 5;
a[2][1] = 6;
int a[3][2] = {1, 2, 3, 4, 5, 6};
int a[3][2];
memset(a, 0, 6*sizeof(int));
int a[][2] = {1, 2, 3, 4, 5, 6};
Same as
1D. Why?
int a[3][2] = {
{1, 2},
{3, 4},
{5, 6}
};
Pointer
Computer's memory is made up of bytes.
Each byte has a number, an address, associated with it.
0x01 0x02 0x03 0x01 0x05 0x06 0x07 0x08
When storing a variable, such as int i = 1
0x00 0x00 0x00 0x01
0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08
i
o i = 1
o &i = 0x01 & operator: get address of a variable
42
Pointer (cont.)
For storing address of a variable, use a special type:
pointer
int *pi; char *pc; float *pf;
Pointer of a
integer variable
Pointer of a
char variable
Pointer of a
float variable
int *pi = &i;
43
int* pi;
pi = &i;
0x10 0x00 0x00 0x00
0xF1 0xF2 0xF3 0xF4 0xF5 0xF6 0xF7 0xF8
i
&i
Pointer (cont.)
Pointer is also a variable its stored in memory
int i = 10;
int *p
i = 10 0x2f00002c
0x2f00aabb p
p =
&p =
*p =
*p : get value at address pointed by p
44
0x2f00002c
0x2f00aabb
10
= &i;
= 0x2f00002c
Pointer (cont.)
Type of pointer notify that how to get the value
pointed by pointer
int i = 0x3f20cc01;
char *p1 = (char *)&i;
short *p2 = (short *)&i;
int *p3 = &i;
p1 is pointed to char-block. *p1 =
p2 is pointed to short-block. *p2 =
p3 is pointed to int-block. *p3 =
P1 P2
0x01 0xcc 0x20 0x3f
0xF1 0xF2 0xF3 0xF4 0xF5 0xF6 0xF7 0xF8
i
Little Endian
P3
45
0x01
0xCC01
0x3f20cc01
Pointer (cont.)
sizeof operator
Size of pointer is not belong to type of pointer
Size of pointer depend on processor (16 bits, 32 bits, 64
bits)
For windows 32 bits: size of pointer is 4 bytes
int main()
{
char c = 0;
char *p = &c;
printf("size = %d", sizeof(p));
}
46
Pointer
pointer operator
Note: each step is a distance k bytes
belongs to type of pointer:
byte: 1 byte
Short: 2 byte
.
Operat
or
desc Example
+ move forward n steps
p += 10;
- move backward n step
p -= 1;
++ move forward 1 step
p++;
-- move backward 1 step
p--;
0x01 0xcc 0x20 0x3f 0x00 0x10 0xaa
0x01 0x02 0x03 0x04 0x05 0x06 0x07
p1 p1+1
p1+5
0x01 0xcc 0x20 0x3f 0x00 0x10 0xaa
0x01 0x02 0x03 0x04 0x05 0x06 0x07
p2 p2+1
p2+3
char *p1; short *p2;
(p1+1) (p2 + 1)
*(p1+1) *(p2+1)
&(p1+1) &(p2+1)
47
Pointer
pointer operator - Practice
48
char a[6] = {10, 20, 30, 40, 50, 60};
char *p = a;
a
0x001cff08
p
0x001cff04
a = ?
&a = ?
*a = ?
p = ?
&p = ?
*p = ?
p + 1 = ?
(*p) + 1 = ?
*(p + 1) = ?
&p + 1;
&a + 1
a++; a = ?
p++; p = ?
Pointer to pointer
Recall that, a pointer variable is a variable.
To store address of a pointer variable, we use pointer-
to-pointer variable.
49
int iVar = 10;
int *p1 = &iVar;
int **p2 = &p1;
iVar = 10
p1 = 0x100
p2 = 0x200
0x200
0x100
0x300
*p1 == ?
*p2 == ?
*(*p2) == ?
p
nx4 bytes
Pointer
Dynamic allocation
Static allocation:
int a = 10;
int array[1000];
Variable will be allocated in stack limited size
Number of elements of array is const
Can not clean up when they become useless
Dynamic allocation
User pointer
Allocation a block of memory in heap high capacity
Clean up easily
Alloc n-int elements in heap
int *p = new int[n];
p
Free memory block pointed by p
50
delete p;
How about
p after
deleting?
Pointer
Dynamic allocation (cont.)
There are two ways for dynamic allocation
51
Using stdlib.h
Using malloc/free
Old C style
Using new/delete
Using new[] / delete[]
C++ style
int main()
{
char *i = (char*) malloc (100);
// some code here
free(i);
}
int main()
{
char *i = new char[100];
// some code here
delete []i;
}
Pointer
Dynamic allocation (cont.)
Use delete for new,
Use delete[] for new[]
52
struct A
{
public:
static int count;
int val;
A()
{
printf("Created %d\n",
val = count++);}
~A()
{
printf("Deleted %d\n",
val);}
};
int A::count = 0;
int main()
{
A *cA = new A[10];
delete cA;
return 1;
}
Delete cA[0] only
int main()
{
A *cA = new A[10];
delete []cA;
return 1;
}
Delete all cA
Pointer-to-pointer dynamic
allocation
In common, used for allocation an 2D-array
53
int **p;
p = new int*[2];
*(p+0) = new int;
*(p+1) = new int;
p 0x900
0x500
= 0x500
0x200
0x200
0x300
0x300
int **p = new int*[3];
p[0] = new int[4];
p[1] = new int[4];
p[2] = new int[4];
*(*(p + i) +j ) p[i][j]
Pointer vs. Array
In common, pointer could be used like array
int main()
{
int *p
p[0] = 1;
*(p + 1) = 12;
p[2] = 5
}
P
0x2f330000
0x2f330004
0x2f330008
0x2f0A0000
stack
heap
*p = *(p+0) = p[0]
*(p + n) = p[n]
54
new int [3];
= 0x2f330000
1
12
5
=
Pointer vs. Array
Array is a pointer
pointed to itself
A pointer can point to
an array addr.
int main()
{
char a[3] = {1, 2, 3, 4};
printf ("0x%x 0x%x %d\n", a, &a, *a);
int *p = new int[3];
p[0] = 1; p[1] = 2; p[2] = 3;
printf ("0x%x 0x%x %d\n", p, &p, *p);
int *p2 = (int*)a;
printf("value of p2 = 0x%x\n", *p2);
}
0x14fd64 0x14fd64 1
0x591398 0x14fd60 1
Value of p2 = 0x04030201
Command prompt
55
Pointer vs. Array
char a[3] = {1, 2, 3};
char *p = new char[3];
p[0] = 10; p[1] = 20; p[2] = 30;
printf ("a = 0x%x p = 0x%x\n", a, p);
printf ("a+1 = 0x%x p+1 = 0x%x\n", a+1, p+1);
printf ("&a = 0x%x &p = 0x%x\n", &a, &p);
printf ("&a+1= 0x%x &p+1 = 0x%x\n", &a+1, &p+1);
a = 0x26FE6C p = 0x0E1AF0
a+1 = 0x26FE6D p+1 = 0x0E1AF1
&a = 0x26FE6C &p = 0x26FE70
&a+1= 0x26FE6F &p+1 = 0x26FE74
Command prompt
10
20
30
1 a
0x0E1AF0
p
0x0E1AF1
0x0E1AF2
0x0E1AF3
0x0E1AF4
0x26FE70
0x26FE71
0x26FE72
0x26FE73
0x26FE74
0x26FE6C
2 0x26FE6D
3
0x26FE6E
0x26FE6F
&p + 1
&a + 1
56
a + 1
p + 1
Due to stack limited, can not create a too big array
Pointer vs. Array
int main()
{
char arr[1034996];
}
int main()
{
char *p = new char[1034996];
}
FAIL OK
0 Can not delete an array
int main()
{
char arr[100];
delete arr;
}
int main()
{
char *p = new char[1034996];
delete p;
}
FAIL OK
Memory block of array is freed automatically when out-of-
scope
Dynamic memory MUST be clean manually by call delete
57
Pointer vs. Array
2D array
int arr[2][3]
pointer-to-pointer
int **p = new int*[2];
p[0] = new int[3];
p[1] = new int[3];
[0][0] [0][1] [0][2]
[1][0] [1][1] [1][2]
p[1]
p[0] p
p[0][0] p[0][1] p[0][2]
p[1][0] p[1][1] p[1][2]
0 2D array & 2D pointer could use in the same way
arr[2][2] = 5 p[2][2] = 10
58
[0][0] [0][1] [0][2] [1][0] [1][1] [1][2]
Block 0 Block 1
*(*(p + i) +j ) p[i][j]
C/C++ String
59
String
No standard string in C/C++
Use char*, or char[] instead
String in C/C++ is array of byte, end with \0
char *st = "String";
S t r i n g \0 st
60
String allocation
Static allocation
char *st = "String";
char st2[] = "String";
Dynamic allocation
char *st3 = new char[6];
st3[0] = 's';
st3[1] = 't';
st3[2] = 'i';
st3[3] = 'n';
st3[4] = 'g';
st3[5] = '\0';
61
String allocation (cont.)
62
char* GetString1()
{
char *st = "String";
return st;
}
char* GetString2()
{
char st[] = "String";
return st;
}
char* GetString3()
{
char *st = new char[6];
strcpy(st, "String");
return st;
}
int main()
{
printf("Say: %s\n", GetString1());
printf("Say: %s\n", GetString2());
printf("Say: %s\n", GetString3());
}
What are
different?
Memory utility functions
MUST #include <string.h>
void * memcpy ( void * destination, const void * source, size_t num )
Copies the values of numbytes from the location pointed
by source directly to the memory block pointed by destination
int memcmp ( const void * ptr1, const void * ptr2, size_t num )
Compare the C string pointed by source into the array pointed
by destination, including the terminating null character
63
Memory utility functions
size_t strlen ( const char * str )
Returns the length of str
The length of a C string is determined by the terminating null-character
This should not be confused with the size of the array that holds the
string
char * strcpy ( char * destination, const char * source )
Copies the C string pointed by source into the array pointed
by destination, including the terminating null character
int strcmp ( const char * str1, const char * str2 )
Compares the C string str1 to the C string str2.
http://www.cplusplus.com/reference/clibrary/cstring/
64
Constant pointer vs.
pointer to constant
Constant pointer:
Address of memory stored is constant
Value at address which pointed to could be changed
65
Pointer to constant:
Value at address which pointed to is constant
Address of memory stored could be changed
char char_A = 'A';
const char * myPtr = &char_A;
*myPtr = 'J'; // error - can't change value of *myPtr
char char_A = 'A';
char char_B = 'B';
char * const myPtr = &char_A;
myPtr = &char_B; // error - can't change address of myPtr
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Variables and constant
Primary data type
Array Pointer - String
Data structure: enum union - struct
Function
Namespace
66
Enum
Use for set up collections of named integer constants
In traditional C way:
Alternate approach
#define SPRING 0
#define SUMMER 1
#define FALL 2
#define WINTER 3
enum {SPRING, SUMMER, FALL, WINTER};
0 1 2 3
67
Enum(cont.)
Declaration
Values of enumconstants
enum MyEnum {SPRING, SUMMER, FALL, WINTER};
enum MyEmum x; // C style
MyEnum y; // C++ style
int main()
{
y = MyEnum::SPRING;
y = FALL;
y = 1; // ILLEGAL
}
enum MyEnum {SPRING = 0, SUMMER = 10, FALL = 11, WINTER = 100};
int main()
{
y = MyEnum::SPRING;
printf("%d", y);
} 68
Union
Allow same portion of memory to be accessed as
different data type
union MyUnion
{
int iValue;
char cValue;
char aValue[4];
};
int main()
{
MyUnion mine = {0x01020304};
printf("iValue: 0x%x\n", mine.iValue);
printf("iValue: 0x%x\n", mine.cValue);
printf("iValue: 0x%x 0x%x 0x%x 0x%x\n",
mine.aValue[0],
mine.aValue[1],
mine.aValue[2],
mine.aValue[3]);
}
0x04 0x03 0x02 0x01
iValue
0x01020304
0x04
0x04 0x03 0x02 0x01
cValue
aValue
Memory block
sizeof(mine) = ?
69
Struct
Define a structure type and/or a variable of a
structure type.
struct T_MyStruct
{
int val1;
char val2;
char val3[5];
};
struct T_MyStruct myStruct;
val1
val2
val3
T_MyStruct
70
Struct
Using struct:
typedef struct T_MyStruct
{
int val1;
char val2;
char val3[5];
}MyStruct;
MyStruct myStruct;
int main()
{
myStruct.val1 = 10;
myStruct.val2 = 100;
myStruct.val3[0] = 1000;
}
71
Data Structure alignment
Is the way data is arranged and accessed in computer
memory.
Consist two issue:
Data alignment:
oPut data at memory offset equal to multiple word size
Structure padding:
oInsert some meaningless bytes between the of last data
structure and start of next
72
Data Structure alignment
0 Before compile, total memory
of T_MyStruct is 8 byte
struct T_MyStruct
{
char val1;
short val2;
int val3;
char val4;
};
char: 1 byte aligned
short: 2 byte aligned
int : 4 byte aligned

val1 val2 val3 val4
0
1 3
7
pad
1
val2 val3 val4
0 1 2 3 4 8 9 10 11
val1
4 bytes block 4 bytes block 4 bytes block
pad2
4 bytes alignment
sizeof(T_MyStruct) == 12 bytes
73
VS Struct member alignment
74
GCC alignment
75
struct test_t
{
int a;
char b;
int c;
}__attribute__((aligned(8)));
struct test_t
{
int a;
char b;
int c;
}__attribute__((__packed__));
http://www.delorie.com/gnu/docs/gcc/gcc_62.html
8 byte alignment
smallest possible alignment
Struct - function
C++ only, not available
in C
Beside variable, struct
also has had function
Struct alignment is not
effected to struct-
function
Function is not counted
when calculate struct
size
typedef struct T_MyStruct
{
int val1;
char val2;
char val3[12];
void SayHello();
}MyStruct;
void MyStruct::SayHello()
{
printf("Hello world");
}
int main()
{
MyStruct myStruct;
myStruct.SayHello();
}
76
Struct
constructor / destructor
C++ only, not available in C
Two special function of struct
Constructor: automatically call
when a instant of struct is created
Destructor: automatically call
when a instant of struct is destroy
typedef struct T_MyStruct
{
int val1;
T_MyStruct();
~T_MyStruct();
}MyStruct;
T_MyStruct::T_MyStruct()
{
printf("Created\n");
}
T_MyStruct::~T_MyStruct()
{
printf("Destroy\n");
}
int main()
{
MyStruct myStruct;
}
constructor
destructor
Created
Destroy
Command prompt
77
Struct and static member
Static function & static
variable
Static variable is not
counted is struct
alignment and struct
size
typedef struct T_MyStruct
{
int val1;
static char val2;
static void SayHello() {}
}MyStruct;
int main()
{
MyStruct myStruct;
printf("%d", sizeof(myStruct));
MyStruct::SayHello();
}
78
Struct and Access privilege
C++ only, not available in C
Three access privilege methods
public: visible for all
private: visible inside struct only
protected: visible inside struct and
retrieved struct (OOP)
Default is public
o For example: valx is public
79
struct MyStruct
{
int valx;
public:
int val1;
private:
int val2;
protected:
int val3;
};
int main()
{
MyStruct mine;
mine.val1 = 0;
mine.valx = 0;
mine.val2 = 0;
mine.val3 = 0;
}
Fatal Error, val2 is private
Fatal Error, val3 is protected
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Variables and constant
Primary data type
Array Pointer - String
Data structure: enum union - struct
Function
Namespace
80
C/C++ function
<return-type> function_name([<type> <param>], [])
void foo() {}
void foo(int a, int b, char c)
{}
int foo()
{
return 1;
}
No return function
Required return
81
Default parameters
#include <cstdio>
void foo(int a,
int b = 1 ,
int c = 2 );
void foo(int a, int b, int c)
printf("%d %d %d\n",
a, b, c);
}
void main()
{
foo(0);
foo(0, 10);
foo(0, 10, 100);
}
Set default value
Use b, c as default value
No default value
Use b, c as default value
0 1 2
0 10 2
0 10 100
Command prompt
82
void foo(int a, int b = 1, int c )
{
printf("%d %d %d\n", a, b, c);
}
Default parameters (cont.)
ERROR
error C2548: 'foo' : missing default
parameter for parameter 3
When a parameter is set default value, the
rest of next parameters MUST BE set
default value too
RULES
83
Variable number of
parameters
#include <cstdio>
#include <cstdarg>
int sum(int num_param, ... )
{
int sum = 0, val = 0;
va_list marker;
va_start(marker, num_param);
for (register int i = 0; i < num_param; i++)
{
val = va_arg(marker, int);
sum += val;
}
va_end(marker);
return sum;
}
void main()
{
printf("%d\n", sum(1, 10));
printf("%d\n", sum(3, 1, 2, 3));
}
84
Parameter classification
Value parameter
Reference parameter
Constant
parameter
Const Reference
parameter
Pointer parameter
85
Parameter classification
Pass-by-value
A copy of parameter is made
Value parameter
Reference parameter
Constant parameter
Const Reference
parameter
Pointer parameter
void foo(int n)
{
n++;
}
void main()
{
int x = 2;
foo(x);
printf("%d\n", x);
}
x = 2
2
x
2
x
2
n
2
x
3
n
2
x
foo
86
Parameter classification
Pass-by-reference
Actually parameter itself is passed
Use reference operator &
Value parameter
Reference parameter
Constant parameter
Const Reference
parameter
Pointer parameter
void foo(int &n)
{
n++;
}
void main()
{
int x = 2;
foo(x);
printf("%d\n", x);
}
x = 3
2
x
2
x
n
x
3
n
3
x
foo
87
Parameter classification
Pass-by-value
A copy of parameter is made and
strict as const.
Value parameter
Reference parameter
Constant parameter
Const Reference
parameter
Pointer parameter
void foo(int const n)
{
n++;
}
void main()
{
int x = 2;
foo(x);
printf("%d\n", x);
}
Fail, can not
modified
const value
2
x
2
x
2
n
2
x
3
n
foo
88
Parameter classification
Pass-by-ref
Actually parameter itself is passed but
avoid modify
Void the overhead of creating a copy
Value parameter
Reference parameter
Constant parameter
Const Reference
parameter
Pointer parameter
void foo(int const &n)
{
//todo
}
89
Parameter classification
In common, Pass-by-value
A copy of parameter is made
Value of parameter is an address of a
memory block
Value parameter
Reference parameter
Constant parameter
Const Reference
parameter
Pointer parameter
void foo(int *n)
{
//todo
}
Value of parameter will not be
change,
but memory block which pointed
by parameter could be modified.
90
Pointer Parameter
#include <cstdio>
void foo(int *A, int *B)
{
int *tmp = A;
A = B;
B = tmp;
}
void main()
{
int A[] = {1, 2, 3};
int B[] = {10, 11};
printf("0x%x 0x%x\n", A, B);
foo(A, B);
printf("0x%x 0x%x\n", A, B);
}
A
B
A
B
A
B
A
B
Copy value
(addr. of data)
foo
0x29faa8 0x29faa0
0x29faa8 0x29faa0
Command prompt
91
Pointer Parameter
#include <cstdio>
void foo(int *A)
{
A[2] = 10;
}
void main()
{
int A[] = {1, 2, 3};
printf(%d\n", A[2]);
foo(A);
printf(%d\n", A[2]);
}
A
A
foo
1
2
3
A[2] = 10
10
A
A[2] = 3
A[2] = 10
Copy value
(addr. of data)
92
Pointer reference parameter
A special case of pointer parameter
Value of pointer parameter (address of block memory) could be changed
Pass-by-reference
CAN NOT work with array directly
#include <cstdio>
void foo(int *&A, int *&B)
{
int *tmp = A; A = B; B = tmp;
}
void main()
{
int arr1[] = {1, 2, 3};
int arr2[] = {10, 11};
int *A = arr1;
int *B = arr2;
printf("0x%x 0x%x\n", A, B);
foo(A, B);
printf("0x%x 0x%x\n", A, B);
}
A
B
A
B
A
B
A
B
foo
0x31fc90 0x31fc88
0x31fc88 0x31fc90
Command prompt
93
Function overloading
C++ only
Allow multiple functions with the same name, so long
as they have different parameters.
void Todo(int a)
{}
void Todo(int a, int b)
{}
94
Function Prototype
In C/C++, functions MUST BE declare before using.
To solve this problems
Keep all functions in correct order
Use prototype inside .cpp file
Use prototype inside header (.h) file -> recommend
#include "header.h"
void Todo1()
{
Todo2();
}
void Todo2(){}
int main(){}
Main.cpp
void Todo1()
{
Todo2();
}
void Todo2()
{}
int main()
{}
Error
error C3861:
'Todo2': identifier
not found
Main.cpp
header.h
void Todo1();
void Todo2();
95
Extern function
Sometimes, we need to use a function in another
module (.cpp file)
Header file is too complicated to use (caused error
when used)
#include <cstdio>
extern void TodoExtern();
int main()
{
TodoExtern();
return 1;
}
Main.cpp
#include <cstdio>
void TodoExtern()
{
printf("TodoExtern\n");
}
Extern.cpp
96
Extern C
Name mangling:
Aka name decoration
The way of encoding additional information in a name of
function, struct, class
In C++:
For adapting overload, class/struct functions, name of
function will be encoding
int f (void) { return 1; }
int f (int) { return 0; }
int __f_v (void) { return 1; }
int __f_i (int) { return 0; }
97
Extern C
For mixing C and C++ source (Object C also) use extern "C"
Extern C talk to compiler that use C style for its scope
No name mangling
No overloading
Extern C is also extern function could be implement in another module
#include <stdio.h>
void ExternC()
{
printf("ExternC\n");
}
Ansi_c.c
extern "C"
{
void ExternC();
void Todo()
{
printf("%d", i);
}
}
C_plusplus.cpp
98
Extern C in practice
#ifdef __cplusplus
extern "C" {
#endif
// your code here
#ifdef __cplusplus
}
#endif
__cplusplus: default C++ preprocessor definition
99
Pointer to function
A variable store address of a function
Advantage
Flexible
User for event handling mechanism
// C
void DoIt (float a, char b, char c){}
void (*pt2Function)(float, char, char) = DoIt;
// using
pt2Function(0, 0, 0);
100
Inline function
Macro: preprocessor replaces all macro calls directly
with the macro code
101
#define NEXT(a) (a+1)
int main()
{
printf("%d", NEXT(1));
}
int main()
{
printf("%d", (a + 1));
}
Inline function (cont)
Like macro, but obeys C/C++ syntax
102
inline int Next(int x)
{
return x + 1;
}
int main()
{
printf("%d", Next(1));
}
For OOP, Inline function is allowed to set access privilege
Improve performance (for short/simple inline functions)
NOTE: The compiler is not forced to inline anything at all
Why
performance is
improved?
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Variables and constant
Primary data type
Array Pointer - String
Data structure: enum union - struct
Function
Namespace
103
Namespace
A abstract container uses for grouping source code.
In C++, a namespace is defined with a namespace
block
namespace maths {
void sin() {}
void cos() {}
void add() {}
}
namespace matrix {
void mult() {}
void add() {}
}
104
Using namespace
For using methods, variables, of a namespace:
<namespace>::<methods/variables>
namespace maths {
void sin() {}
void cos() {}
void add() {}
}
namespace matrix {
void mult() {}
void add() {}
}
void main()
{
maths::sin();
matrix::add();
}
105
Using namespace
Use using namespace for shorten way.
namespace maths {
void sin() {}
void cos() {}
void add() {}
}
namespace matrix {
void mult() {}
void add() {}
}
using namespace maths;
using namespace matrix;
void main()
{
sin();
mult();
}
106
Namespace ambiguous call
More than two definition of
add functions
maths::add()
matrix::add()
ambiguous call fatal error.
In this case, MUST BE specify
namespace.
namespace maths
{
void add();
}
namespace matrix
{
void add();
}
using namespace maths;
using namespace matrix;
void main()
{
add();
}
error C2668: 'matrix::add' : ambiguous call to overloaded function
.\main.cpp(8): could be 'void matrix::add(void)'
.\main.cpp(3): or 'void maths::add(void)'
107
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Class & Object
Inheritance
Polymorphism
Operator overloading
Class static member
108
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Class & Object
Inheritance
Polymorphism
Operator overloading
Class static member
109
Class
As same as struct
Default access is private
110
class MyClass
{
public:
MyClass();
~MyClass();
protected:
int GetVal() {return m_Var;}
void Todo();
private:
int m_Var;
void SayHello();
};
void MyClass::Todo()
{
//some code here
}
Class name
Access methods
Constructor
Destructor
Function (methods)
Inline methods
Class variable (property)
Function implementation
Class (cont)
In traditional, code of class is divided into 2 parts
Declaration: in .h file
Implementation: in .cpp file
111
#ifndef __CCLASS_H__
#define __CCLASS_H__
class CClass
{
public:
CClass();
~CClass();
private:
void Toso() ;
};
#endif
Any_name.h
#include "Any_name.h"
void CClass::Todo()
{

}
CClass::~CClass()
{

}
Any_name.cpp
How to use class
112
MyClass objA; //or MyClass objA()
objA.SayHello();
Create a object directly
Access class methods,
properties by using dot
Create a object through pointer.
Two ways to use methods,
properties
o (*objA). C style
o objA-> C++ style
Supported polymorphism
MyClass *ObjB = new MyClass;
//or MyClass *ObjB = new MyClass();
(*objA).SayHello();
objA->SayHello();
Recommend!
MyClass *ObjB = new MyClass;
objA->SayHello();
Access methods
Aka Encapsulation
Public: allow access inside & outside class
Protected: allow access inside class & in derived class
Private : allow access inside class only
113
Constructor
Should be public
Called when an instance is created
A class could define a set of constructors (constructor
overloading)
114
class MyClass
{
public:
MyClass();
MyClass(MyClass* A);
MyClass(const MyClass& A);
MyClass(int val);
}
Default constructor
Copy constructor.
Copy constructor
Definition:
A constructor with the same name as the class
Used to make a deep copy of objects (be careful if class
content pointer properties)
115
If no user-defined constructor is defined, compiler defines
one.
X (const X& copy_from_me)
X (X* copy_from_me)
X (X& copy_from_me)
X (const X&copy_from_me, int a = 10, float b = 1.0 )
Must be set default value
Copy constructor (cont.)
Invoked when
When a object is created
from another object of
the same type
When an object is
passed by value as
parameter to function
When a object is return
from a function
116
class ABC
{
public:
ABC(){}
ABC(ABC *A){printf("here1\n");}
ABC(const ABC &A)
{
printf("here2\n");
}
};
void Foo1(ABC A){}
ABC Foo2()
{
ABC a;
return a;
}
int main()
{
ABC *A = new ABC();
ABC B(A);
Foo1(A);
Foo2();
}
Copy constructor (cont)
A default copy constructor is created automatically,
but it is often not what you want.
117
Image(Image *img) {
width = img->width;
height = img->height;
data = new int[width*height];
for (int i=0; i<width*height; i++)
data[i] = img->data[i];
}
Image(Image *img) {
width = img->width;
height = img->height;
data = img->data;
}
Automatic generated copy constructor User-defined (expected) copy contructor
Explicit constructor
"nonconverting"
Explicit constructor syntax is required.
118
class A {
public:
explicit A(int) {}
};
void f(A) {}
void g()
{
A a1 = 37;
A a2 = A(47);
a1 = 67;
f(77);
}
Without explicit With explicit
Destructor
Automatically invoked when
an object is destroy:
Out of scope
Or manually free (use
pointer)
Use for collect class memory
119
class MyClass
{
char m_Var;
int m_pData;
public:
MyClass(char id) {
m_Var = id;
m_pData = new int[100];
};
~MyClass() {
delete m_pData;
cout<<"Destroyed "<<m_Var<<endl;
}
};
int main()
{
cout << "---Alloc A---"<<endl;
MyClass *A = new MyClass('A');
cout << "---Free A---"<<endl;
delete A;
cout << "---Create B---"<<endl;
MyClass B('B');
cout << "---End---"<<endl;
return 1;
}
---Alloc A---
---Free A---
Destroyed A
---Create B---
---End---
Destroyed B
Command prompt
this pointer
A special pointer point to class instance itself
Used inside class, for access class methods, properties
120
class MyClass
{
char m_Var;
public:
MyClass(char id) {m_Var = id;};
~MyClass() {}
MyClass* Todo1(int val)
{
if (this->m_Var == val)
{
return this;
}
return 0;
}
void Todo2()
{
this->Todo1('A');
}
};
Member initialization
121
class MyClass
{
private:
int m_iVar1;
float m_fVar2;
char * m_pVar3;
public:
MyClass();
}
MyClass::MyClass():
m_iVar1(10),
m_fVar2(1.3f),
m_pVar3(0)
{
}
Setup value of properties
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Class & Object
Inheritance
Polymorphism
Operator overloading
Class static member
122
Inheritance
Code reuse:
Composition: create objects of existing class inside the
new class
Inheritance: create a new class as a type of an existing
class
123
Existing class
New class
class NewClass
{
public:
ExistingClass *m_member;
};
Base class
Derive class
Hierarchy model
class Derive: public Base
{
};
Inheritance syntax
124
class Derive: public Base
{
public:
Derive():Base() {}
void Todo();
};
void Derive::Todo()
{
this->protectedFunc();
this->publicFunc();
this->privateFunc();
Base::Todo();
}
class Base
{
public:
Base() {}
void publicFunc() {}
void Todo() {}
protected:
void protectedFunc() {}
private:
void privateFunc() {}
};
FAIL: cannot access private member
Access bases method (same name)
Constructor init
Inheritance access
Base access Inherit access Derive access
Public
Public
Public
Protected Protected
Private Private
Public
Protected
Protected
Protected
Private
Private
Public
Private private Protected
Private
125
Inheritance access
Example
126
class CAnimal
{
public:
void Drink();
protected:
void Run();
private:
void Eat();
};
class CRabbit: private CAnimal
{
public:
CRabbit()
{
Run();
Eat();
Drink();
}
};
void main()
{
CRabbit rab;
rab.Drink();
rab.Eat();
rab.Run();
}
Why?
Constructor Destructor
Inheritance
127
Animal
Mammal
Lion
Lion *theLion = new Lion()
Lion()
Animal()
Mammal()
delete theLion;
~Lion()
~Mammal()
~Animal()
Multiple inheritance
A class could be inherit from multiple base class
128
Human
StreetMusician
Musician Worker
class Human{};
class Musician
{
public:
Musician(int instrument, int year){}
};
class Worker
{
public:
Base2(int level){}
};
class StreetMusician: public Human,
protected Musician,
private Worker
{
public:
StreetMusician(): Human(),
Musician(1, 1),
Worker(10) {}
};
Inheritance
Ambiguous access
CBase1::Hello()
CBase2::Hello()
129
class CBase1
{
public:
void Hello();
};
class CBase2
{
public:
void Hello();
};
class CDerive: CBase1, CBase2
{
public:
CDerive(): CBase1(), CBase2()
{
Hello();
}
};
Ambiguous access of 'Hello
How to
solve?
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Class & Object
Inheritance
Polymorphism
Operator overloading
Class static member
130
Polymorphism
Implemented in C++ with virtual functions
Virtual function
Pure virtual function
Pure virtual class (abstract class)
Use for improved code organization
Extensible
131
Function call binding
Binding:
Connecting a function call to a function body
Early binding:
Binding is performed before the program is run by compiler,
linker
Late binding:
Binding occurs at runtime, based on the type of the object
Aka Dynamic binding or Runtime binding
For C++, to cause late binding, use keyword virtual
132
Overriding vs. Overloading
Overriding: override a
bases virtual or non-
virtual methods
Overloading: several
methods with the same
name which differ from
parameters
133
class Animal
{
public:
virtual void Eat(){}
void Run(){}
};
class Cat: public Animal
{
public:
//overiding
void Eat(){}
void Run(){}
//overloading
void Jump();
void Jump(int distance);
};
Virtual Overriding vs.
non-virtual Overriding
Obj is a Animal pointer, but
really a Cat instant
Without virtual (early binding),
Animal:Run was called instead
of Cat::Run
134
class Animal
{
public:
virtual void Eat()
{
cout<<Animal:Eat"<<endl;
}
void Run()
{
cout<<Animal:Run"<<endl;
}
};
class Cat: public Animal
{
public:
void Eat()
{
cout<<Cat:Eat"<<endl;
}
void Run()
{
cout<<Cat:Run"<<endl;
}
};
int main()
{
Animal *obj = new Cat();
obj->Eat();
obj->Run();
}
Cat:Eat
Animal:Run
Command prompt
Virtual
destructor
When obj is freed, both
itself and base MUST BE
deleted
Its ok for obj1, but
problem for obj2
135
class Base
{
public:
~Base()
{
cout<<"Destroy Base"<<endl;
}
};
class Derive: public Base
{
public:
~Derive()
{
cout<<"Destroy Derive"<<endl;
}
};
int main()
{
Derive *obj1 = new Derive();
Base *obj2 = new Derive();
cout<<"--Free obj1--"<<endl;
delete obj1;
cout<<"--Free obj2--"<<endl;
delete obj2;
}
--Free obj1--
Destroy Derive
Destroy Base
--Free obj2--
Destroy Base
Command prompt
Virtual destructor
(cont)
To solve this problem,
use virtual destructor
136
class Base
{
public:
~Base()
{
cout<<"Destroy Base"<<endl;
}
};
class Derive: public Base
{
public:
~Derive()
{
cout<<"Destroy Derive"<<endl;
}
};
int main()
{
Derive *obj1 = new Derive();
Base *obj2 = new Derive();
cout<<"--Free obj1--"<<endl;
delete obj1;
cout<<"--Free obj2--"<<endl;
delete obj2;
}
virtual
--Free obj1--
Destroy Derive
Destroy Base
--Free obj2
Destroy Derive
Destroy Base
Command prompt
Pure virtual function
Pure virtual class
Pure virtual function:
Virtual function with no body
Pure virtual class:
Class content pure virtual function
CAN NOT create an instance of
pure virtual class directly
Derive class of pure virtual class
MUST implements all pure virtual
functions
137
class Base
{
public:
virtual void Todo() = 0;
};
class Derive: public Base
{
void Todo() {}
}
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Class & Object
Inheritance
Polymorphism
Operator overloading
Class static member
138
Operator overloading
Another way to make a function call
Define function of operator such as : +, -, *, /,
WARNING: Not recommend to use. Its easy to read,
but hard to debug !
139
Operator overloading
example
140
class Integer
{
public:
int i;
Integer(int ii) : i(ii) {}
const Integer operator+(const Integer& rv)
{
return Integer(i - rv.i);
}
Integer& operator+=(const Integer& rv)
{
i *= rv.i;
return *this;
}
};
int main()
{
Integer ii(1), jj(2), kk(3);
kk += ii + jj;
cout << "Value = " << kk.i << endl;
}
This implementation make user confused
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Class & Object
Inheritance
Polymorphism
Operator overloading
Class static member
141
Static function
Allow user invokes
without creating an
instance
Declaration with static
keyword
No need to create
object, but must be
declared class name
142
class MyClass
{
public:
static void Todo();
};
void MyClass::Todo()
{
//implemetation
}
int main()
{
MyClass::Todo();
}
Static variable
Same as static function
Value of static variable
MUST BE set outside
class declaration.
143
class MyClass {
public:
static int s_Var;
};
int MyClass::s_Var = 99;
int main()
{
printf("%d",
MyClass::s_Var);
}
Lazy initialization
(Single-Ton)
0 The tactic of delaying the
creation of an object,
calculation of a value, or
some other expensive
process until the first
time it is need.
144
class ExpensiveRes
{
public:
ExpensiveRes() {}
void todo1();
static ExpensiveRes* GetInstance();
private:
static ExpensiveRes* s_Instance;
};
ExpensiveRes* ExpensiveRes::s_Instance = 0;
ExpensiveRes* ExpensiveRes::GetInstance()
{
if (!s_Instance)
{
s_Instance = new ExpensiveRes();
}
return s_Instance;
}
int main()
{
ExpensiveRes::GetInstance()->todo1();
ExpensiveRes::GetInstance()->todo1();
}
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Recall pointer
Memory leak
145
Question?
What does memory leak mean ?
How is memory structure ?
What does its consequences ?
Why does memory leak happen ?
How to detect and solve?
146
What does memory leak
mean ?
First, How is memory structure ?
147
How is memory structure ?
STACK vs HEAP
148
Run-time storage
Code segment:
where the compiled program sits in
memory
Global area:
store global variables
Stack segment:
where parameters and local variables are
allocated
Heap segment:
where dynamically allocated variables are
allocated
149
Text segment
(Code segment)
Stack segment
Heap Segment
Global area
Stack
Where parameters and local
variables are allocated
Limited size Stack
overflow
Memory use in stack is
temporary and auto release
Fast processing/low size
150
Parameters
Return Address
where to begin execution
when function exits
Dynamic link
pointer to caller's stack
frame
Static link
pointer to lexical parent
(for nested functions)
Return value
Local variables
Concept Stack frame
Text segment
(Code segment)
Stack frame
Heap Segment
Global area
Stack frame
Heap
Large pool of memory
Dynamic allocation
Stays allocated until
specifically deallocated
leak !
Must be accessed through a
pointer
Large arrays, structures, or
classes should be stored
Heap why?
Large & dynamic
151
Parameters
Return Address
where to begin execution
when function exits
Dynamic link
pointer to caller's stack
frame
Static link
pointer to lexical parent
(for nested functions)
Return value
Local variables
Concept Stack frame
Text segment
(Code segment)
Stack frame
Heap Segment
Global area
Stack frame
Heap vs Stack
int _array[10]; stored in stack
152
Stack
_array
int *_array = new int[n]
Pointer _array is stored in Stack
Data of array is stored in Heap
_array
0x00FF
Stack
10
Heap
0x00FF
0x0005
Value of:
_array : address where int point into in heap (0x00FF)
(*_array): value at it's address on heap (10)
(&_array): address of the memory which used for stored pointer
_array in stack (0x0005)
FAQ
Why we use
Classname *Obj = new Classname();
instead of
Classname Obj;
153
Memory leak overview
154
What does memory leaking
mean?
Definition:
Particular type of unused memory, unable to release
Common:
Refer to any unwanted increase in memory usage
* usually for heap memory
155
void Leak()
{
int *A = new int[1000];
// some code here
// ...
// without delete A
//
return;
}
4000 bytes
Return without free A Leak
What does its consequences ?
Application gets slow fps
Application is crashed
Device has been freeze, restarted
156
Why does memory leak
happen?
First, Let's see some examples
157
Example 0
Forget to release resources
No GC mechanic supported
Button is
pressed
Save current floor
On target
floor ?
Wait until lift is idle
Go to required
floor
Release memory used to
save current floor
True
Finished Memory
Leaking
here
158
void Fa()
{
}
void Fb()
{}
void Leak()
{
int *a = new int[10];
Fa();
Fb();
return;
}
void main()
{
Leak();
}
C/C++ Example 1
Leak memory
caused by
lacking of release
dynamic memory

delete a[];
return;
Solution
Leak !
159
C/C++ Example 2
void leak()
{
int **list = new int*[10];
for (int i = 0; i < 10; i++)
{
list[i] = new int;
}
delete list;
return;
}
Allocation a series,
delete only one unit
Leak !
for (int i = 0; i < 10; i++)
{
delete list[i];
}
delete list;
Solution
160
C/C++ Example 3
Leak memory when
using pointer-return-
type
delete []str;
Avoid to call directly GenString()
Solution
161
char* GenString()
{
char *a = new char[10];
a[9] = '\0';
return a;
}
void Leak()
{
char *str = GenString();
printf("%s\n", str);
printf("%s\n", GenString());
}
#include <cstdio>
void Foo()
{
int* a = new int[100];
a = new int[1000];
}
void Foo1()
{
int* a = new int[100];
int* b = new int[1000];
a = b;
}
C/C++ Example 4
Leak memory because of
misunderstanding = operator in
C++
Stack
Heap
A
LEAK!
162
Leak!
C/C++ Example 5
void main()
{
Classname *A = new A();
...
...
//free A
A = NULL;
}
163
Misunderstand free memory method
in C/C++
Stack
Heap
A
NULL
LEAK!
Keep in mind we are using C/C++
Use MACRO for safe deallocating
#define SAFE_DEL(a) {if(a){delele a;a = 0;}}
Solution
C/C++ Example 6 - STL
164
class Element
{
int ID;
public:
Element(int id)
{
printf("Created %d at 0x%x\n", id, this);
ID = id;
}
~Element()
{
printf("Destroy %d at 0x%x\n", ID, this);
}
};
int main()
{
list<Element*> m_List;
Element *e0 = new Element(0);
Element *e1 = new Element(1);
//add to list
m_List.push_back(e0); m_List.push_back(e1);
//clear list
printf("-----Before clear-----\n");
m_List.clear();
printf("-----After clear-----\n");
return 0;
}
Created 0 addr 0xa719c0
Created 1 addr 0xa81a18
-----Before clear-----
-----After clear-----
Command prompt
Memory
leak here
list
Item 0
Item 1
e0
e1
C/C++ Example 6 STL
(cont.)
165
int main()
{
list<Element*> m_List;
Element *e0 = new Element(0);
Element *e1 = new Element(1);
//add to list
m_List.push_back(e0);
m_List.push_back(e1);
//clear list
printf("-----Before clear-----\n");
list <Element*>::iterator i;
for (i = m_List.begin(); i != m_List.end(); i++)
{
delete *i;
}
m_List.clear();
printf("-----After clear-----\n");
return 0;
}
Free data of each
element pointer
Created 0 addr 0xb61a28
Created 1 addr 0xb71a70
-----Before clear-----
Destroy 0 addr 0xb61a28
Destroy 1 addr 0xb71a70
-----After clear-----
Command prompt
Example 7
166
class CB {
public:
CB(){
m_iVal = 0;
}
~CB(){}
int m_iVal;
};
class CA {
public:
CA(){
m_pB = 0;
}
~CA(){
delete m_pB;
m_pB = 0;
}
CB *m_pB;
};
int main()
{
CB *B = new CB;
CA *A = new CA();
A->m_pB = B;
delete(A);
printf("%d", B->m_iVal);
}
B
A
m_pB
Access violation
reading location
.
Try to
remove
delete m_pB
Example 7 (cont.)
167
class CB {
public:
CB(){
m_iVal = 0;
}
~CB(){}
int m_iVal;
};
class CA {
public:
CA(){
m_pB = 0;
}
~CA(){
delete m_pB;
m_pB = 0;
}
CB *m_pB;
};
int main()
{
CA *A = new CA();
A->m_pB = new CB()
delete(A);
}
A
m_pB
Leak
Delete or not?
Use manual delocate m_pB
Solution
C/C++ Example 8
class cA()
{
public :
cA() {m_pdata = new int[100];}
virtual ~cA() {delete[]
m_pdata;}
int *m_pdata;
};
class cB: public cA()
{
public
cB():cA() {m_pdata2 = new
int[100];}
~cB() {delete []m_pdata2;}
int *m_pdata2;
}
void main()
{
cA *A = new cB();
delete A;
}
Memory leak caused by
misunderstanding finalization
method
Without virtual, in this case,
m_pdata is not deleted leak
Be careful with virtual for
finalization method
Solution
168
C/C++ Example 9
Using newvs free. No
destructor will be invoked
after free
169
class MyClass
{
public
MyClass()
{
m_pdata2 = new int[100];
}
~ MyClass()
{
delete []m_pdata2;
}
int *m_pdata2;
}
void main()
{
MyClass* p = new MyClass();
free(p);
}
Leak here
What are reasons of memory
leak?
Forget/ misunderstand C/C++ mechanism
Out-of-Control (logic)
170
Current Solutions
For Forget/ misunderstand C/C++ mechanism
Semi-automatic memory management
oReference Counting
Automatic memory management
oTracing Garbage Collection (GC): Java , C #
No GC mechanic for C/C++
171
Reference Counter: Good or bad ?
Reference counter:
Simple method for
memory conflict
resolution
Algorithms:
Increase counter when
use as reference
Decrease when release
Delete memory of
counter is zero
172
class IShareMem
{
public:
IShareMem():m_iRefCounter(1){}
virtual ~IShareMem(){}
static
IShareMem* SetReference(IShareMem* src)
{
src->m_iRefCounter++;
return src;
}
void Release()
{
m_iRefCounter--;
if (m_iRefCounter <= 0)
{
delete this;
}
}
private:
int m_iRefCounter;
};
Reference Counter: Good or bad ?
Good:
o Avoid conflict in memory usage. (See example no.7)
Bad:
o Cause memory leak if user forget to release
o Hard to detect memory leak
o CAN NOT DETECT by tool
173
Current Solutions -
Disadvantage
Garbage collectors generally can do nothing about
logical memory leaks
174
0
1
2
n
..
.
Alloc
Alloc
Alloc
Alloc
Which is really needed?
A
B
D
E
Z
Do I alloc some-
where without
release?
Somethings else
is pointed
to an object
C/C++
How to avoid, detect?
Rule:
o Remember to release dynamic data (pointer) HARD
o Keep our resource in well controlled TOO HARD
Detect
o By phenomenon on device ? not exactly
o By review source ? TOO HARD
o By tool
VC++ memory leak debugging
External tool
o Cannot detect some cases.
175
C/C++
How to solve?
Easy to detect, but hard to solve
Depend on kind of memory leak
Experience
Organize source and keep it in control
Such as a document about resource ?!?
176
Detect Memory Leak
177
Memory leak quick detection
0 Windows: use task manager / process tab
0 Android:
adb shell top -m <number_of_record>
See VSS, RSS
178
Use Visual studio supported
function
Use __CrtDumpMemoryLeaks
Advantage
o Easy to use
o Fully report about leak when application completed
o Free
Disadvantage
o Cannot detect run-time
o Fail if application Crashed
Presentation:
o Manually coding by user
o Use some lib such as VLD
179
Debug in Visual studio
180
VLD Tool
http://www.codeproject.com/KB/applications/visual
leakdetector.aspx
http://vld.codeplex.com/
Include vld.h in source
Add vld.lib
181
#include "vld.h"
#pragma comment(lib, "vld.lib")
VLD Tool
0 After finish application normally, memory leak
information will be display in output
182
WARNING: Visual Leak Detector detected memory leaks!
---------- Block 3 at 0x006F4F98: 12 bytes ----------
Call Stack:
c:\users\ricky.ngk\desktop\testleak\testleak\main.cpp (81): TestLeak.exe!Init + 0x7 bytes
c:\users\ricky.ngk\desktop\testleak\testleak\main.cpp (108): TestLeak.exe!main
f:\dd\vctools\crt_bld\self_x86\crt\src\crtexe.c (586): TestLeak.exe!__tmainCRTStartup + 0x19 bytes
f:\dd\vctools\crt_bld\self_x86\crt\src\crtexe.c (403): TestLeak.exe!mainCRTStartup
0x76BBED6C (File and line number not available): kernel32.dll!BaseThreadInitThunk + 0x12 bytes
0x772237F5 (File and line number not available): ntdll.dll!RtlInitializeExceptionChain + 0xEF bytes
0x772237C8 (File and line number not available): ntdll.dll!RtlInitializeExceptionChain + 0xC2 bytes
Data:
74 A7 DF 00 01 00 00 00 20 60 6F 00 t....... .`o.....
0 Double click the stack to navigate to source
Debug memory leak run-time
Use some tool, such as:
o Glow code: http://www.glowcode.com/
o Memory validator: http://www.softwareverify.com/cpp-memory.php
Advantage
o Runtime checking
o Nice Interface
Disadvantage
o Not free
o Not easy to use. Need tutorial
Note: Those tool cannot working well with VLD
183
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Forward declaration
Standard IO Console IO & FILE
Template
Type casting
Exception handling
Endian
STL introduction
GNU GCC/G++
184
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Forward declaration
Standard IO Console IO & FILE
Template
Type casting
Exception handling
Endian
Bit processing
STL introduction
GNU GCC/G++ 185
Forward declaration
Declaration of a identifier which not completed
definition
For C/C++, aka function prototype (for function)
186
int first(int x) {
if (x == 0)
return 1;
return second(x-1);
}
int second(int x) {
if (x == 0)
return 0;
return first(x-1);
}
int second(int x);
int first(int x) {
if (x == 0)
return 1;
return second(x-1);
}
int second(int x) {
if (x == 0)
return 0;
return first(x-1);
}
Forward declaration
187
ClassA.h ClassB.h
#ifndef _CLASSA_H_
#define _CLASSA_H_
class ClassA
{
public:
ClassA();
ClassB* m_pB;
};
#endif
#ifndef _CLASSB_H_
#define _CLASSB_H_
class ClassB
{
public:
ClassB();
ClassA* m_pA;
};
#endif
ClassA.cpp ClassB.cpp
#include "ClassA.h"
ClassA::ClassA(){}
#include "ClassB.h"
ClassB::ClassB(){}
Class forward declaration
#include "ClassB.h" #include "ClassA.h"
class ClassB;
class ClassA;
Must be pointer
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Forward declaration
Standard IO Console IO & FILE
Template
Type casting
Exception handling
Endian
Bit processing
STL introduction
GNU GCC/G++ 188
Standard IO
stdio.h
int printf ( const char * format, ... );
Format: %[flags][width][.precision][length]specifier
Write data to stdout and store
189
printf ("Characters: %c %c \n", 'a', 65);
printf ("Decimals: %d %ld\n", 1977, 650000L);
printf ("Preceding with blanks: %10d \n", 1977);
printf ("Preceding with zeros: %010d \n", 1977);
printf ("Some different radixes: %d %x %o %#x %#o \n", 100, 100, 100, 100, 100);
printf ("floats: %4.2f %+.0e %E \n", 3.1416, 3.1416, 3.1416);
printf ("Width trick: %*d \n", 5, 10);
printf ("%s \n", "A string");
Standard IO
stdio.h
int scanf( const char * format, ... );
Format: %[flags][width][.precision][length]specifier
Reads data fromstdin and store
190
int n;
scanf ("%d",&n);
Standard IO
<iostream>
std::cout
an object of class ostreamthat represents the standard
output stream
191
cout << "Hello there.\n";
cout << "Here is 5: " << 5 << "\n";
cout << "The manipulator endl writes a new line to the screen." << endl;
cout << "Here is a very big number:\t" << 70000 << endl;
cout << "Here is the sum of 8 and 5:\t" << 8+5 << endl;
cout << "Here's a fraction:\t\t" << (float) 5/8 << endl;
cout << "And a very very big number:\t" << (double) 7000 * 7000 << endl;
cout << "I am a C++ programmer!\n";
Standard IO
0 <iostream>
std::cin
an object of class istreamthat represents the standard
input stream
192
int input = 0;
cout << "Enter a number here: ";
cin >> input;
cout << "You entered the number " << input << ".\n";
File <stdio.h>
193
FILE * fopen ( const char * filename, const char * mode ); Open file
int fclose ( FILE * stream ); Close a file
size_t fwrite ( const void * ptr, size_t size, size_t count,
FILE * stream );
Write block of data to stream
size_t fread ( void * ptr, size_t size, size_t count, FILE *
stream );
Read a block data from stream
int fscanf ( FILE * stream, const char * format, ... ); Read formatted data from stream
int fprintf ( FILE * stream, const char * format, ... ); Write formatted output to stream
int fseek ( FILE * stream, long int offset, int origin ); Reposition stream position indicator
Origin:
SEEK_SET : beginning of gfile
SEEK_END: end of file
SEEK_CUR: current position
long int ftell ( FILE * stream ); Get current position in stream
void rewind ( FILE * stream ); Set position indicator to the beginning
File <stdio.h>
194
#include <stdio.h>
int main ()
{
FILE * pFile;
pFile = fopen ("myfile.txt","w");
if (pFile!=NULL)
{
fprintf (pFile, "example");
fclose (pFile);
}
return 0;
}
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Forward declaration
Standard IO Console IO & FILE
Template
Type casting
Exception handling
Endian
STL introduction
GNU GCC/G++
195
Function template
special functions that can operate with generic types
Can be adapted to more than one type or class
without repeating code
A set of needed functions will be created when
compile slowdown compiling process
196
template <class identifier> function_declaration;
template <typename identifier> function_declaration;
Function template
Example 1
197
template <class T> T GetMax (T a, T b)
{
return (a>b?a:b);
}
int main ()
{
int i=5, j=6, k;
long l=10, m=5, n;
k=GetMax<int>(i,j);
n=GetMax<long>(l,m);
cout << k << endl;
cout << n << endl;
return 0;
}
Function template
Example 2
198
template <class U, class V> U GetMax (U a, V b)
{
return (a>b?a:b);
}
int main()
{
cout << GetMax<float, int>(10.5, 12.5) <<endl;
cout << GetMax<float>(10.5, 12.5) <<endl;
return 1;
}
Class template
A class can have members that use template
parameters as types
199
template <class T>
class mypair
{
T values [2];
public:
mypair (T first, T second)
{
values[0]=first; values[1]=second;
}
};
int main()
{
return 1;
mypair<int> Pair1(100, 200);
mypair<char> Pair2('A', 'B');
}
template <class T> class mypair
{
T a, b;
public:
mypair (T first, T second) {a=first; b=second;}
T getmax ();
};
template <class T> T mypair<T>::getmax ()
{
T retval;
retval = a>b? a : b;
return retval;
}
int main ()
{
mypair <int> myobject (100, 75);
cout << myobject.getmax();
return 0;
}
Class template
Function member outside the declaration of the class template, we
must always precede that definition with the template <...> prefix
200
Template prefix
Return type
Class prefix
Class template.
Template specialization
Define a different implementation for a template
when a specific type is passed as template parameter
201
// class template:
template <class T>
class mycontainer
{
T element;
public:
mycontainer (T arg)
{
element=arg;
}
T increase () {return ++element;}
};
// class template specialization:
template <>
class mycontainer <char>
{
char element;
public:
mycontainer (char arg)
{
element=arg;
}
char uppercase ()
{
if ((element>='a')&&(element<='z'))
element+='A'-'a';
return element;
}
};
Class template
New code will be generated while compiling, DO NOT
split a template class into two parts: .h, and .cpp
Easy to use, but not easy to debug/read
202
Mixin
We can implement inheritance delaying the definition
of the base.
203
template <class Base>
class Mixin : public Base {};
class Base {};
Mixin issue
If the client never calls Todo there is no error
message!
204
template <class Base>
class Mixin : public Base
{
public:
void Todo() {Base::Do();}
};
class Base
{};
C++ meta programming
Is writing programs that represent and manipulate
other programs (e.g. compilers, program generators,
interpreters) or themselves (reflection).
In C++, meta programming base on: Template
205
Example: Factorial
N! = 1 x 2 x 3 x x N
206
template<int n> struct Factorial
{
enum {RET=Factorial<n-1>::RET*n};
};
// Note: template specialization
template<> struct Factorial<0>
{
enum{RET=1};
};
int main()
{
printf("%d", Factorial<10>::RET);
return 1;
}
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Forward declaration
Standard IO Console IO & FILE
Template
Type casting
Exception handling
Endian
STL introduction
GNU GCC/G++
207
Type casting
0 Convert from specific type to another type
char a = 10;
int b = (int) a;
bool c = a;
float d = float(a);
Explicit casting
c-like casting notation
Implicit casting
Explicit casting
Functional notation
208
Numeric overflow
void main()
{
int a = 200;
char c = a;
}
c = -56 ?
209
Float to int casting
void main()
{
float f = 2.7;
int i = f;
}
i is equal
to or ?
210
Bool & bool casting
Bool have two values:
True
False
In C/C++:
False is zero
True is non-zero
void main()
{
int i = 10;
bool b = i;
bool c = !i;
}
b = true
c = false
211
C++ type casting
Beside basic implicit and explicit type casting, C++
also supported:
dynamic_cast<>
static_cast<>
const_cast<>
reinterpret_cast<>
212
const_cast<>
Used to add to or remove the const-ness or volatile-
ness of the expression
213
struct One
{
void funct1() { cout<<"Testing..."<<endl;}
} ;
void funct2(const One& c)
{
//will generate warning/error, if without const_cast
One &noconst = const_cast<One&> (c);
noconst.funct1();
}
void main()
{
One b;
funct2(b);
}
reinterpret_cast<>
Allows any integral type to be converted into any
pointer type and vice versa
Can be used for conversions such as char* to int*,
or One_class* to Unrelated_class*, which are
inherently unsafe.
Can not cast away the const, volatile
214
reinterpret_cast<>
Example
215
// Returns a hash code based on an address
unsigned short Hash( void *p )
{
unsigned int val = reinterpret_cast<unsigned int>( p );
return ( unsigned short )( val ^ (val >> 16));
}
int main()
{
int a[20];
for ( int i = 0; i < 20; i++ )
cout << Hash( a + i ) << endl;
}
static_cast<>
0 Allows casting
0 a pointer of a derived class to its base class and vice versa
0 int to enum
0 Reference of type &p to &q
0 Object type P to Object type Q
0 Pointer to a member to pointer to a member with the same hierarchy.
0 Any expression to void
0 Primary data type
0 This cast type uses information available at compile time to perform
the required type conversion
0 No runtime safety check
216
static_cast<>
217
#include <iostream.h>
#include <stdlib.h>
enum color {blue, yellow, red, green, magenta};
int main()
{
int p1 = 3;
cout<<"integer type, p1 = "<<p1<<endl;
cout<<"color c1 = static_cast<color> (p1)"<<endl;
color c1 = static_cast<color> (p1);
cout<<"enum type, c1 = "<<c1<<endl;
return 0;
}
integer type, p1 = 3
color c1 = static_cast<color> (p1)
enum type, c1 = 3
Press any key to continue . . .
Command prompt
dynamic_cast<>
218
Enable Run-Time Type Info first
dynamic_cast<>
Used with pointers and references to objects for class
hierarchy navigation
Requires the Run-Time Type Information (RTTI)
If the pointer being cast is not a pointer to a valid
complete object of the requested type, the value
returned is a NULL pointer
Used for polymorphism class
219
dynamic_cast<>
Type conversion from base class
pointer to a derived class
pointer is called downcast.
Type conversion from derived
class pointer to a base class
pointer, is called upcast.
From a class to a sibling class in
class hierarchy: crosscast
220
Class Base
Class Derive1
Class Derive2
Base
Derive1
Derive2
downcast
upcast
dynamic_cast<>
upcast
Always successful
221
Base
Derive1
Derive2
Why?
Derive class always contents valid complete base class
dynamic_cast<>
upcast multiple conversion with
multiple inheritace
CAN NOT cast directly from Derived3 to
base.
Do step by step:
Derived3 Derived2 Base
Or Derived3 Derived1 Base
222
Base
Derived 1 Derived 2
Derived 3
dynamic_cast<>
downcast
Available for polymorphism
class only
223
Base
Derive
Funct2()
Funct3()
class Base1 {
public:
virtual void funct1(){};
};
class Derived1:public Base1 {
public:
virtual void funct2(){};
};
dynamic_cast<>
downcast (cont.)
224
Base
Derive
Funct2()
Funct3()
Base* Test1 = new Derived;
Base* Test2 = new Base;
Test1
Test2
Derived* Test3 = dynamic_cast<Derived*>(Test1);
Derived* Test4 = dynamic_cast<Derived*>(Test2);
successful
fail
dynamic_cast<>
crosscast
Crosscast Base2 Derived1
225
Base2 Base
Derived 1 Derived 2
Derived 3
Base2 *p1 = new Derived3;
Derived1 *p2 = dynamic_cast<Derived1*>(p1);
Base2 *p1 = new Base2;
Derived1 *p2 = dynamic_cast<Derived1*>(p1);
Fail
OK
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Forward declaration
Standard IO Console IO & FILE
Template
Type casting
Exception handling
Endian
STL introduction
GNU GCC/G++
226
Exception Handling
Improved error recovery is one of the most powerful
ways you can increase the robustness of your code
227
throw type;
//type: user defined type or principle
type
Throw exception
try
{
// code that may generate exceptions
}
catch(type1 id1)
{
// handle exceptions of type1
}
Catch(...)
{
// catch any exception
}
Handling & catching exception
Exception example
228
class DivByZeroEx {};
void div(int num1, int num2)
{
if (num2 == 0) throw (DivByZeroEx ());
}
void main()
{
try
{
div(1, 0);
}
catch (DivByZeroEx ex)
{
printf(" DivByZero Exception ");
}
catch (...)
{
printf("Unkown exception");
}
}
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Forward declaration
Standard IO Console IO & FILE
Template
Type casting
Exception handling
Endian
STL introduction
GNU GCC/G++
229
Endian
big-endian and little-endian refer to which bytes are
most significant in multi-byte data types
For example, storing number 1025 in memory (4 bytes)
230
0000.0001 0000.0100 0000.0000 0000.0000
0000.0100 0000.0001 0000.0000 0000.0000
Little endian
Big endian
Endian - Example
Important notes:
Avoid to save/load a short/int/long array. Use char (byte)
array instead.
231
int main()
{
char num[4] = {0x00,
0x11,
0x22,
0x33};
int *val = (int*)num;
printf("val = 0x%x", *val);
}
val = 0x33221100
Command prompt
Windows 32 bits
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Forward declaration
Standard IO Console IO & FILE
Template
Type casting
Exception handling
Endian
STL introduction
GNU GCC/G++
232
STL
Standard template library
Powerful library for container and algorithms
Some basic types:
Vector
Deque
List
.
Some basic methods
push
pop
insert
copy
erase

233
STL
Container
Vector, deque, set, list, map, hash
Iterator:
an object used for selecting the elements within a
container and present them to the user
234
STL example
235
#include <cstdio>
#include <list>
using namespace std;
int main()
{
list<int> m_List;
m_List.push_back(10);
m_List.push_back(20);
//travel list
list<int>::iterator i = m_List.begin();
for (i = m_List.begin(); i != m_List.end(); i++)
{
printf("%d\n", *i);
}
return 0;
}
STL and memory management
236
class Element
{
int ID;
public:
Element(int id)
{
printf("Created %d at 0x%x\n", id, this);
ID = id;
}
~Element()
{
printf("Destroy %d at 0x%x\n", ID, this);
}
};
int main()
{
Element e1(0), e2(1);
list<Element> m_List;
//add to list
m_List.push_back(e1); m_List.push_back(e2);
//clear list
printf("-----Before clear-----\n");
m_List.clear();
printf("-----After clear-----\n");
return 0;
}
Created 0 addr 0x22cce8
Created 1 addr 0x22cce4
-----Before clear-----
Destroy 0 addr 0xc91a38
Destroy 1 addr 0xc91a48
-----After clear-----
Destroy 1 addr 0x22cce4
Destroy 0 addr 0x22cce8
Command prompt
???
Copy of Elements are created
and stored in list
STL and memory management
237
class Element
{
int ID;
public:
Element(int id)
{
printf("Created %d at 0x%x\n", id, this);
ID = id;
}
~Element()
{
printf("Destroy %d at 0x%x\n", ID, this);
}
};
int main()
{
list<Element*> m_List;
Element *e0 = new Element(0);
Element *e1 = new Element(1);
//add to list
m_List.push_back(e0); m_List.push_back(e1);
//clear list
printf("-----Before clear-----\n");
m_List.clear();
printf("-----After clear-----\n");
return 0;
}
Created 0 addr 0xa719c0
Created 1 addr 0xa81a18
-----Before clear-----
-----After clear-----
Command prompt
Memory
leak here
list
Item 0
Item 1
e0
e1
STL and memory
management (cont)
238
int main()
{
list<Element*> m_List;
Element *e0 = new Element(0);
Element *e1 = new Element(1);
//add to list
m_List.push_back(e0);
m_List.push_back(e1);
//clear list
printf("-----Before clear-----\n");
list <Element*>::iterator i;
for (i = m_List.begin(); i != m_List.end(); i++)
{
delete *i;
}
m_List.clear();
printf("-----After clear-----\n");
return 0;
}
Free data of each
element pointer
Created 0 addr 0xb61a28
Created 1 addr 0xb71a70
-----Before clear-----
Destroy 0 addr 0xb61a28
Destroy 1 addr 0xb71a70
-----After clear-----
Command prompt
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Forward declaration
Standard IO Console IO & FILE
Template
Type casting
Exception handling
Endian
STL introduction
GNU GCC/G++
239
GNU GCC
GNU compiler collection include front ends for C, C++,
Object-C,
In windows, using through Cygwin or MinGW
See http://gcc.gnu.org
Read more
makefile
Cygwin
Bash-script
Batch-script
240
Example
241
@echo off
cls
SET CYGWIN=c:\cygwin\
SET CYGWIN_BIN=%CYGWIN%\bin
SET PATH=%PATH%;%CYGWIN%;%CYGWIN_BIN%
del *.o >nul
if exist main.exe (del main.exe)>nul
%CYGWIN_BIN%\make
if exist main.exe (call main.exe)
make.bat
all: main.o MyClass1.o
g++ main.o MyClass1.o -o main.exe
main.o: main.cpp
g++ -c main.cpp
MyClass1.o: MyClass1.cpp
g++ -c MyClass1.cpp
makefile
#include <cstdio>
#include "MyClass1.h"
MyClass::MyClass()
{
printf("Hello\n");
}
MyClass1.cpp
#include "MyClass1.h"
int main()
{
MyClass *c = new MyClass();
return 1;
}
main.cpp
#ifndef __MYCLASS_H__
#define __MYCLASS_H__
class MyClass
{
public:
MyClass();
};
#endif
MyClass1.h
Introduction
Design patterns can speed up the development by
providing test, proven development paradigm
Allow developers to communicate using well-know,
well understood names for software interactions.
See http://sourcemaking.com/designed_patterns for
more detail
243
Example
Singleton Design Pattern
To Ensure a class has
only one instance, and
provide a global point
of access to it
244
class ExpensiveRes
{
public:
ExpensiveRes() {}
static ExpensiveRes* GetInstance();
private:
static ExpensiveRes* s_Instance;
};
ExpensiveRes* ExpensiveRes::s_Instance = 0;
ExpensiveRes* ExpensiveRes::GetInstance()
{
if (!s_Instance)
{
s_Instance = new ExpensiveRes();
}
return s_Instance;
}
int main()
{
ExpensiveRes::GetInstance();
}
Reference
0 From Java to C Mihai Popa Gameloft
0 Thinking in C++, 2nd Edition - Bruce Eckel, President, MindView, Inc.
0 http://en.wikipedia.org
0 http://www.learncpp.com
0 http://msdn.microsoft.com
0 http://www.cplusplus.com
0 http://en.allexperts.com
0 http://www.desy.de/gna/html/cc/Tutorial/tutorial.html
0 http://aszt.inf.elte.hu/~gsd/halado_cpp/
0 http://www.codeguru.com/forum/showthread.php
0 http://www.uow.edu.au/~nabg/ABC/ABC.html
0 http://pages.cs.wisc.edu/~hasti/cs368/CppTutorial/
0 http://www.devmaster.net
0 http://enel.ucalgary.ca/People/Normal/enel1315_winter1997/
0 http://www.cantrip.org
0 http://sourcemaking.com/designed_patterns
245

You might also like