Você está na página 1de 245

Outline

Preparation
Getting Start

OOP
Memory management Rest of C/C++ features Appendix
2

Outline
Preparation
Getting Start

Hello world C/C++ files Entry point C/C++ libraries Source compile process
3

OOP
Memory management Rest of C/C++ features Appendix

Outline
Preparation
Getting Start
Variables and constant
Primary data type Array Pointer String

OOP
Memory management Rest of C/C++ features Appendix

Data structure: enum union - struct


Function Namespace
4

Outline
Preparation
Getting Start

Class & Object


Inheritance Polymorphism Operator overloading

OOP
Memory management Rest of C/C++ features Appendix

Class static member


5

Outline
Preparation
Getting Start

Recall pointer
Memory leak

OOP
Memory management Rest of C/C++ features Appendix
6

Outline
Preparation
Getting Start
Forward declaration Standard IO Console IO & FILE Template

OOP
Memory management Rest of C/C++ features Appendix

Type casting Exception handling

Endian STL introduction GNU GCC/G++


7

Outline
Preparation Getting Start OOP

Hello world! C/C++ files Entry point C/C++ libraries Source compile process
8

Memory management
Rest of C/C++ features

Outline
Preparation
Getting Start

Hello world! C/C++ files Entry point C/C++ libraries Source compile process
9

Basic Data Structure OOP


Memory management

Rest of C/C++ features

Hello world using VS

10

Hello world
main.cpp # include <stdio.h> void main() { printf("Hello world"); }

Use standard IO lib


Entry point Print to console screen

11

Outline
Preparation Getting Start OOP

Hello world! C/C++ files Entry point C/C++ libraries Source compile process
12

Memory management
Rest of C/C++ features

C/C++ source files


#include "stdio.h" void Todo1(); void Todo2(); # include "header.h" void Todo1() { Todo2(); } void Todo2(){} void main() { Todo1(); }

Header file (.h)


aka include file Hold declarations for other files

Source file (.c / .cpp)


Content implementation
Required
13

use (prototype) Not required

Outline
Preparation Getting Start OOP

Hello world! C/C++ files Entry point C/C++ libraries Source compile process
14

Memory management
Rest of C/C++ features

Entry point
Form1.cpp void main() { // your code here } Form2.cpp
int main(int n, char ** args) { // your code here }

Required unique entry point


The most common is: main

Error when no entry point is defined

1>LINK : fatal error LNK1561: entry point must be defined

15

Outline
Preparation Getting Start OOP

Hello world! C/C++ files Entry point C/C++ libraries Source compile process
16

Memory management
Rest of C/C++ features

C/C++ standard library


C/C++ support a set of internal
#include "stdio.h" void main() { printf("hello"); }

basic library, such as


Basic IO Math Memory handle

For using, include the header

file #include <> #include ""

17

C header
<assert.h>
<Ctype.h> <Errno.h> <float.h> <limits.h>

C++ header
<cassert>
<cctype> <cerrno> <cfloat> <climits>

Content assert macro, for debugging


For character classification/convert functions For testing error number Floating point macros Define range of value of common type

<math.h>
<setjmp.h> <signal.h> <stdlib.h> <stddef.h> <stdarg.h>

<cmath>
<csetjmp> <csignal> <cstdlib> <cstddef> <cstdarg>

Mathematical functions
Provide non-local jumps for flow control Controlling various exceptional conditions Standard lib

<stdio.h>
<string.h> <time.h> <wchar.h> <wctype>

<cstdio>
<cstring> <ctime> <cwchar> <cwctype>

Standard IO
Manipulating several kinds of string Converting between time & date formats
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 caused when forget to add .lib file error LNK2019: unresolved external symbol

19

C/C++ user-defined lib (cont.)


For using Include .h files Inform .lib files to compiler
Copy all .dll file to (if any) : o same folder with execute file, or o to system32 (windows) not recommend

20

Import user-defined library Visual studio

Declare path to .lib

21

Import user-defined library Visual studio

Declare .lib file

22

Outline
Preparation Getting Start OOP

C/C++ files Entry point C/C++ libraries Hello world! Source compile process
23

Memory management
Rest of C/C++ features

Process
Source .h/.c/.cpp preprocess Preprocessed source Compile

Tools: Visual Studio: cl.exe (Press F7 / F5) GNU GCC: gcc/ g++
.o / .obj (object file)

Executable/ lib

Linker

24

Outline
Preparation Getting Start OOP
Data structure: enum union - struct Variables and constant
Primary data type Array Pointer - String

Memory management
Rest of C/C++ features

Function Namespace
25

Outline
Preparation Getting Start OOP
Data structure: enum union - struct Variables and constant
Primary data type Array Pointer - String

Memory management
Rest of C/C++ features

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

Command prompt Main: 1 0 Foo : 2280752 1


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
#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; }

Allocated when the program

starts and is deallocated when the program ends.

Default value is zero (0)

Command prompt Main: 0 Foo: called 0 Foo: called 1 Foo: called 2


30

Register variable
int main() { int sum = 0; for (register int i = 0; i < 100; i++) { sum += i; } printf("Sum = %d\n", sum); return 1; }

Stored in a machine register if

possible Usually used in for iterator for improve performance

31

Extern variable
Extern.cpp int m_iExternVar = 100; main.cpp #include <cstdio> Specify that the variable is

declared in a different file. memory for the variable

Compiler will not allocate Avoid duplicate declaration Share (global) variable for

extern int m_iExternVar;


int main() { printf("Value = %d\n", m_iExternVar); return 1; }

multiple .cpp files

Command prompt
Value = 100
32

Constant
Variable's value is constant
To prevent the programmer from modifying
int const k_Hello = 0; int main() { k_Hello = 10; } Error error C3892: 'k_Hello' : you cannot assign to a variable that is const

33

Outline
Preparation Getting Start OOP
Data structure: enum union - struct Variables and constant
Primary data type Array Pointer - String

Memory management
Rest of C/C++ features

Function Namespace
34

Primitive data type (32bits processor)


Type void char short int Size n/a 1 byte 2 bytes 4 bytes -231 (231 1) unsigned char: -128 127 signed char: 0255 unsigned short: 0 (216 -1) signed short: -215 (215 1) unsigned int: 0 (232 -1) signed int: -231 (231 1) Range

long
long long bool float double

4 bytes -231 (231 1)


8 bytes -263 (263 1) 1 byte 4 bytes 8 bytes

unsigned long: 0 (232 -1) signed long: -231 (231 1)


unsigned long long: 0 (264 -1) signed long long: -263 (263 1) True /false (non-zero / zero)

35

New type definition


Use typedef

typedef int Mytype; typedef int MyArr[5]; Mytype var1; MyArr arr;

36

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
Data structure: enum union - struct Variables and constant
Primary data type Array Pointer - String

Memory management
Rest of C/C++ features

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[<s1>][<s2>][<sn>]
Index of array is counted from 0 to (si-1) C/C++ do not handle out-of-range exception

si MUST BE constant

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
int a[4] = {1, 2, 3, 4}; int a[4] = {1}; int a[] = {1, 2, 3, 4}; int a[4]; a[0] = 1; a[1] = 2; a[2] = 3; a[3] = 4; int a[4]; memset(a, 0, 4*sizeof(int)); a[0], a[1], a[2], a[3] = ?

40

Array Assignment 2D Array


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;

Same as 1D. Why?

int a[3][2] = {1, 2, 3, 4, 5, 6};

int a[][2] = {1, 2, 3, 4, 5, 6};


int a[3][2]; memset(a, 0, 6*sizeof(int)); int a[3][2] = { {1, 2}, {3, 4}, {5, 6} };
41

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

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;
Pointer of a integer variable

char *pc;
Pointer of a char variable

float *pf;
Pointer of a float variable

0x10

0x00

0x00

0x00

int *pi = &i;


0xF6 0xF7 0xF8

0xF1 0xF2

0xF3 0xF4 0xF5

&i

int* pi; pi = &i;

43

Pointer (cont.)
Pointer is also a variable its stored in memory
int i = 10; int *p = &i;

0x2f00002c

i = 10

0x2f00aabb p = 0x2f00002c

p = 0x2f00002c &p = 0x2f00aabb *p = 10


*p : get value at address pointed by p
44

Pointer (cont.)
Type of pointer notify that how to get the value

pointed by pointer
0x01 0xcc 0x20 0x3f

0xF1 0xF2

0xF3 0xF4 0xF5

0xF6 0xF7 0xF8

Little Endian

int i = 0x3f20cc01; char *p1 = (char *)&i; short *p2 = (short *)&i; int *p3 = &i;

P1

P2

P3

p1 is pointed to char-block. *p1 = p2 is pointed to short-block. *p2 = p3 is pointed to int-block. *p3 =

0x01 0xCC01 0x3f20cc01

45

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


Operat or + ++ -desc move forward n steps move backward n step move forward 1 step move backward 1 step Example p += 10; p -= 1; p++; p--;

Note: each step is a distance k bytes belongs to type of pointer:


byte: 1 byte

Short: 2 byte
.

(p1+1) (p2 + 1) *(p1+1) *(p2+1) &(p1+1) &(p2+1)

0x01

0xcc

0x20

0x3f

0x00 0x05

0x10 0x06

0xaa 0x07

0x01

0xcc

0x20

0x3f

0x00

0x10

0xaa

0x01

0x02

0x03 0x04

0x01 0x02

0x03 0x04 0x05

0x06 0x07

p1

p1+1

p1+5

p2

p2+1

p2+3
47

char *p1;

short *p2;

Pointer pointer operator - Practice


char a[6] = {10, 20, 30, 40, 50, 60}; char *p = a; 0x001cff04 0x001cff08 p a a = ? &a = ? *a = ? p = ? &p = ? *p = ? p + 1 = ? (*p) + 1 = ? *(p + 1) = ? &p + 1; &a + 1 a++; a = ? p++; p = ?

48

Pointer to pointer
Recall that, a pointer variable is a variable. To store address of a pointer variable, we use pointer-

to-pointer variable.
int iVar = 10; int *p1 = &iVar; int **p2 = &p1;

0x100

iVar = 10

*p1 == ? *p2 == ? *(*p2) == ?

0x200

p1 = 0x100 p2 = 0x200
49

0x300

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

How about p after deleting? delete p;

int *p = new int[n];


Alloc n-int elements in heap

Free memory block pointed by p

nx4 bytes

50

Pointer Dynamic allocation (cont.)


There two way for dynamic allocation
Old C style C++ style

Using stdlib.h Using malloc/free


int main() { char *i = (char*) malloc (100); // some code here free(i); }

Using new/delete Using new[] / delete[]


int main() { char *i = new char[100]; // some code here delete []i; }

51

Pointer Dynamic allocation (cont.)


Use delete for new, Use delete[] for new[]
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

52

Pointer-to-pointer dynamic allocation


0x200

int **p; p = new int*[2]; *(p+0) = new int; *(p+1) = new int;

0x300

0x500

0x200 0x300

0x900

p = 0x500

In common, used for allocation an 2D-array


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]
53

Pointer vs. Array


In common, pointer could be used like array
*p = *(p+0) = p[0] *(p + n) = p[n]
0x2f0A0000

stack
P = 0x2f330000

int main() { int *p = new int [3]; p[0] = 1; *(p + 1) = 12; p[2] = 5 }

heap

1 12
5

0x2f330000 0x2f330004 0x2f330008

54

Pointer vs. Array


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); }

Array is a pointer

pointed to itself A pointer can point to an array addr.

Command prompt 0x14fd64 0x14fd64 1 0x591398 0x14fd60 1 Value of p2 = 0x04030201


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 printf printf printf ("a = ("a+1 = ("&a = ("&a+1= 0x%x 0x%x 0x%x 0x%x p p+1 &p &p+1 = = = = 0x%x\n", 0x%x\n", 0x%x\n", 0x%x\n", a, p); a+1, p+1); &a, &p); &a+1, &p+1); 0x0E1AF0 0x0E1AF1 0x0E1AF2 0x0E1AF3 0x0E1AF4

10 20 30

p+1

&a + 1

0x26FE6C 0x26FE6D 0x26FE6E 0x26FE6F 0x26FE70 0x26FE71 0x26FE72 0x26FE73 0x26FE74

1 a
2 3

a+1

Command prompt a = a+1 = &a = &a+1= 0x26FE6C 0x26FE6D 0x26FE6C 0x26FE6F p p+1 &p &p+1 = = = = 0x0E1AF0 0x0E1AF1 0x26FE70 0x26FE74

&p + 1

56

Pointer vs. Array


Due to stack limited, can not create a too big array
int main() { char arr[1034996]; }

FAIL

int main() { char *p = new char[1034996]; }

OK

0 Can not delete an array


int main() { char arr[100]; delete arr; }

FAIL

int main() { char *p = new char[1034996]; delete p; }

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]
[0][0] [0][1] [0][2] [1][0] [1][1] [1][2]

pointer-to-pointer
int **p = new int*[2]; p[0] = new int[3]; p[1] = new int[3];

Block 0

Block 1

p
[0][0] [1][0] [0][1]
[1][1]

p[0]

p[0][0]

p[0][1]

p[0][2]

[0][2] [1][2]

p[1]
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

*(*(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"; st S t r i n g \0

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.)


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; }

What are different?

int main() { printf("Say: %s", GetString1()); printf("Say: %s", GetString2()); printf("Say: %s", GetString3()); }

62

Memory utility functions


MUST #include <string.h>
void * memcpy ( void * destination, const void * source, size_t num )

Copies the values of num bytes 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
char char_A = 'A'; char char_B = 'B'; char * const myPtr = &char_A; myPtr = &char_B; // error - can't change address of myPtr

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

65

Outline
Preparation Getting Start OOP
Data structure: enum union - struct Variables and constant
Primary data type Array Pointer - String

Memory management
Rest of C/C++ features

Function Namespace
66

Enum
Use for set up collections of named integer constants
In traditional C way:
#define #define #define #define SPRING SUMMER FALL WINTER 0 1 2 3

Alternate approach
enum {SPRING, SUMMER, FALL, WINTER}; 0 1 2 3

67

Enum (cont.)
Declaration
enum MyEnum {SPRING, SUMMER, FALL, WINTER}; enum MyEmum x; MyEnum y; // C style // C++ style

int main() { y = MyEnum::SPRING; y = FALL; y = 1; // ILLEGAL }

Values of enum constants


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]; };

Memory block

0x04

0x03

0x02

0x01

iValue cValue
0x04 0x04

0x01020304

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]); }

aValue

0x03

0x02

0x01

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; T_MyStruct
val1

val2
val3

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:
o Put data at memory offset equal to multiple word size

Structure padding: o Insert some meaningless bytes between the of last data structure and start of next

72

Data Structure alignment


struct T_MyStruct { char val1; short val2; int val3; char val4; };
char: 1 byte aligned

0 Before compile, total memory

of T_MyStruct is 8 byte
val1 0 1

val2
3

val3

val4 7

4 bytes alignment
pad 1 1

short: 2 byte aligned


int : 4 byte aligned
val1 0

val2
2 3 4

val3

val4 8 9

pad2 10 11

4 bytes block

4 bytes block

4 bytes block
73

sizeof(T_MyStruct) == 12 bytes

VS Struct member alignment

74

GCC alignment
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

75

Struct - function
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(); }

C++ only, not available

in C Beside variable, struct also has had function Struct alignment is not effected to structfunction Function is not counted when calculate struct size
76

Struct constructor / destructor


typedef struct T_MyStruct { int val1; constructor T_MyStruct();

~T_MyStruct();
}MyStruct;

destructor

T_MyStruct::T_MyStruct() { printf("Created\n"); } T_MyStruct::~T_MyStruct() { printf("Destroy\n"); }

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

Command prompt Created Destroy

int main() { MyStruct myStruct; }

77

Struct and static member


typedef struct T_MyStruct { int val1; static char val2; static void SayHello() {} }MyStruct; int main() { MyStruct myStruct; printf("%d", sizeof(myStruct)); MyStruct::SayHello(); }

Static function & static

variable Static variable is not counted is struct alignment and struct size

78

Struct and Access privilege


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; } 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

Fatal Error, val2 is private Fatal Error, val3 is protected

79

Outline
Preparation Getting Start OOP
Data structure: enum union - struct Variables and constant
Primary data type Array Pointer - String

Memory management
Rest of C/C++ features

Function Namespace
80

C/C++ function
<return-type> function_name([<type> <param>], [])

No return function

void foo() {} void foo(int a, int b, char c) {}

Required return

int foo() { return 1; }


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 Command prompt 0 1 2 0 10 2 0 10 100 Use b, c as default value Use b, c as default value No default value
82

Default parameters (cont.)


void foo(int a, int b = 1, int c ) { printf("%d %d %d\n", a, b, c); }

ERROR
error C2548: 'foo' : missing default parameter for parameter 3

RULES
When a parameter is set default value, the rest of next parameters MUST BE set default value too
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
Value parameter

Pass-by-value A copy of parameter is made


void foo(int n) { n++; } void main() { int x = 2; foo(x); printf("%d\n", x); }

Reference parameter

Constant parameter
Const Reference parameter Pointer parameter

x=2

x n

2 2

x
n

2 3

2
86

foo

Parameter classification
Value parameter
Pass-by-reference Actually parameter itself is passed Use reference operator &
void foo(int &n) { n++; } void main() { int x = 2; foo(x); printf("%d\n", x); }

Reference parameter

Constant parameter
Const Reference parameter Pointer parameter

x=3

x n

x
n

3
87

foo

Parameter classification
Value parameter

Pass-by-value A copy of parameter is made and

strict as const.

Reference parameter

Constant parameter
Const Reference parameter Pointer parameter

void foo(int cont n) { n++; Fail, can not } modified void main() { const value int x = 2; foo(x); printf("%d\n", x); }

x n

2 2 foo

2
3
88

Parameter classification
Value parameter
Pass-by-ref Actually parameter itself is passed but avoid modify

Reference parameter

Void the overhead of creating a copy

Constant parameter
Const Reference parameter Pointer parameter

void foo(int const &n) { //todo }

89

Parameter classification
Value parameter

In common, Pass-by-value
A copy of parameter is made
Value of parameter is an address of a memory block void foo(int *n) { //todo }

Reference parameter

Constant parameter
Const Reference parameter Pointer parameter

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); } Copy value (addr. of data)
foo A B A B

A B A B

Command prompt 0x29faa8 0x29faa0 0x29faa8 0x29faa0

91

Pointer Parameter
A[2] = 3
#include <cstdio> void foo(int *A) { A[2] = 10; }
A

Copy value (addr. of data)


foo A

void main() { int A[] = {1, 2, 3}; printf(%d\n", A[2]); foo(A); printf(%d\n", A[2]); }

A[2] = 10

1 2 3

10

A[2] = 10

92

Pointer reference parameter


A special case of pointer parameter Value of pointer parameter (address of block memory) could be changed Pass-by-reference A CAN NOT work with array directly B
#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); }
foo A B A B A B

Command prompt 0x31fc90 0x31fc88 0x31fc88 0x31fc90


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

Main.cpp
void Todo1() { Todo2(); Error } error C3861: void Todo2() 'Todo2': identifier {} not found int main() {}

header.h
void Todo1(); void Todo2();

Main.cpp
#include "header.h" void Todo1() { Todo2(); } void Todo2(){} int main(){}

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)
Extern.cpp
#include <cstdio> void TodoExtern() { printf("TodoExtern\n"); }

Main.cpp
#include <cstdio> extern void TodoExtern(); int main() { TodoExtern(); return 1; }
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 int f (void) { return 1; } f (int) { return 0; }

int int

__f_v (void) { return 1; } __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

Ansi_c.c
#include <stdio.h> void ExternC() { printf("ExternC\n"); }

C_plusplus.cpp
extern "C" { void ExternC(); void Todo() { printf("%d", i); } }

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


#define NEXT(a) (a+1) int main() { printf("%d", NEXT(1)); }
int main() { printf("%d", (a + 1)); }

101

Inline function (cont)


Like macro, but obeys C/C++ syntax
inline int Next(int x) { return x + 1; } int main() { printf("%d", Next(1)); }

Why performance is improved?

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


102

Outline
Preparation Getting Start OOP
Data structure: enum union - struct Variables and constant
Primary data type Array Pointer - String

Memory management
Rest of C/C++ features

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


namespace maths { void add(); } namespace matrix { void add(); } using namespace maths; using namespace matrix;

More than two definition of

add functions

maths::add()

matrix::add()

ambiguous call fatal error.

In this case, MUST BE specify

namespace.
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

void main() { add(); }

Outline
Preparation Getting Start OOP

Class & Object


Inheritance Polymorphism Operator overloading

Memory management
Rest of C/C++ features

Class static member


108

Outline
Preparation Getting Start OOP

Class & Object


Inheritance Polymorphism Operator overloading

Memory management
Rest of C/C++ features

Class static member


109

Class
As same as struct Default access is private
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)
110 Function implementation

Class (cont)
In traditional, code of class is divided into 2 parts Declaration: in .h file Implementation: in .cpp file
Any_name.h
#ifndef __CCLASS_H__ #define __CCLASS_H__ class CClass { public: CClass(); ~CClass(); private: void Toso() ; }; #endif

Any_name.cpp
#include "Any_name.h" void CClass::Todo() { } CClass::~CClass() { }

111

How to use class


MyClass objA; //or MyClass objA() objA.SayHello(); MyClass *ObjB = new MyClass; //or MyClass *ObjB = new MyClass(); (*objA).SayHello(); 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

Recommend! MyClass *ObjB = new MyClass; objA->SayHello();


112

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)

class MyClass { public: MyClass(); MyClass(MyClass* A); MyClass(const MyClass& A); MyClass(int val); }

Default constructor
Copy constructor.

114

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)
X X X X (const X& copy_from_me) (X* copy_from_me) (X& copy_from_me) (const X&copy_from_me, int = 10, float = 1.0 ) Must be set default value

If no user-defined constructor is defined, compiler defines

one.

115

Copy constructor (cont.)


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(); }

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

Copy constructor (cont)


A default copy constructor is created automatically,

but it is often not what you want.

Automatic generated copy constructor


Image(Image *img) { width = img->width; height = img->height; data = img->data; }

User-defined (expected) copy contructor


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]; }

117

Explicit constructor
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

"nonconverting" Explicit constructor syntax is required.

118

Destructor
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; }

Automatically invoked when

an object is destroy:
pointer)

Out of scope Or manually free (use

Use for collect class memory


Command prompt

---Alloc A-----Free A--Destroyed A ---Create B-----End--Destroyed B


119

this pointer
A special pointer point to class instance itself
Used inside class, for access class methods, properties
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'); }
};

120

Member initialization
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

121

Outline
Preparation Getting Start OOP

Class & Object


Inheritance Polymorphism Operator overloading

Memory management
Rest of C/C++ features

Class static member


122

Inheritance
Code reuse: Composition: create objects of existing class inside the new class class NewClass
Existing class New class
{ public: ExistingClass *m_member; };

Inheritance: create a new class as a type of an existing

class
Base class Hierarchy model Derive class
123

class Derive: public Base { };

Inheritance syntax
class Base { public: Base() {} void publicFunc() {} void Todo() {} protected: void protectedFunc() {} private: void privateFunc() {} };

class Derive: public Base { public: Derive():Base() {} void Todo(); }; Constructor init void Derive::Todo() { this->protectedFunc(); this->publicFunc(); this->privateFunc();

FAIL: cannot access private member Access bases method (same name)
}

Base::Todo();
124

Inheritance access
Base access Public Protected Private Public Protected Private Public Protected Private
125

Inherit access

Derive access Public Protected Private Protected

Public

Protected

Private

Private

private

Inheritance access Example


class CAnimal { public: void Drink(); protected: void Run(); private: void Eat(); };

void main() { CRabbit rab; rab.Drink(); rab.Eat(); rab.Run(); }

Why?

class CRabbit: private CAnimal { public: CRabbit() { Run(); Eat(); Drink(); } };

126

Constructor Destructor Inheritance


Lion *theLion = new Lion() Animal() Animal ~Animal()

Mammal()

Mammal

~Mammal()

Lion()

Lion

~Lion()

delete theLion;
127

Multiple inheritance
A class could be inherit from multiple base class
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) {} };

Human

Musician

Worker

StreetMusician

128

Inheritance Ambiguous access


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?

CBase1::Hello() CBase2::Hello()
129

Outline
Preparation Getting Start OOP

Class & Object


Inheritance Polymorphism Operator overloading

Memory management
Rest of C/C++ features

Class static member


130

Polymorphism
Implemented in C++ with virtual functions Virtual function Pure virtual function Pure virtual class (abstract class / base 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


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); };
133

Overriding: override a

bases virtual or nonvirtual methods


Overloading:

several methods with the same name which differ from parameters

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(); }

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

Command prompt Cat:Eat Animal:Run

134

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 destructor
When obj is freed, both

itself and base MUST BE deleted


Its ok for obj1, but

problem for obj2


Command prompt --Free obj1-Destroy Derive Destroy Base --Free obj2-Destroy Base

135

class Base { public: { }

virtual

~Base()

Virtual destructor (cont)


To solve this problem,

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; }

use virtual destructor

Command prompt --Free obj1-Destroy Derive Destroy Base --Free obj2 Destroy Derive Destroy Base
136

Pure virtual function Pure virtual class


class Base { public: virtual void Todo() = 0; }; class Derive: public Base { void Todo() {} }

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

Outline
Preparation Getting Start OOP

Class & Object


Inheritance Polymorphism Operator overloading

Memory management
Rest of C/C++ features

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

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; This implementation make user confused return *this; } }; int main() { Integer ii(1), jj(2), kk(3); kk += ii + jj; cout << "Value = " << kk.i << endl; }

Operator overloading example

140

Outline
Preparation Getting Start OOP

Class & Object


Inheritance Polymorphism Operator overloading

Memory management
Rest of C/C++ features

Class static member


141

Static function
class MyClass { public: static void Todo(); }; void MyClass::Todo() { //implemetation } int main() { MyClass::Todo(); }

Allow user invokes

without creating an instance Declaration with static keyword No need to create object, but must be declared class name

142

Static variable
class MyClass { public: static int s_Var; }; int MyClass::s_Var = 99; int main() { printf("%d", MyClass::s_Var); }

Same as static function


Value of static variable

MUST BE set outside class declaration.

143

Lazy initialization
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(); }

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

Outline
Preparation Getting Start OOP

Recall pointer
Memory leak

Memory management
Rest of C/C++ features

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
Text segment (Code segment)

Global area

Stack segment

Heap Segment

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

Stack
Parameters
where to begin execution when function exits

Text segment (Code segment)

Return Address Dynamic link Static link

Global area
Stack frame

Where parameters and local

pointer to caller's stack frame

pointer to lexical parent (for nested functions)

Return value Local variables Concept Stack frame Stack frame Heap Segment

variables are allocated Limited size Stack overflow Memory use in stack is temporary and auto release Fast processing/low size

150

Heap
Parameters
where to begin execution when function exits

Text segment (Code segment)

Return Address Dynamic link Static link

Global area
Stack frame

Large pool of memory Dynamic allocation Stays allocated until

pointer to caller's stack frame

pointer to lexical parent (for nested functions)

Return value Local variables Concept Stack frame Stack frame Heap Segment

specifically deallocated leak ! Must be accessed through a pointer Large arrays, structures, or classes should be stored Heap why? Large & dynamic
151

Heap vs Stack
int _array[10]; stored in stack
int *_array = new int[n]
Pointer _array is stored in Stack
Data of array is stored in Heap
Stack _array

Stack
0x00FF 0x0005

Heap 10

_array
0x00FF

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)

152

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

void Leak() { int *A = new int[1000]; // some code here // ... // without delete A // return; }

4000 bytes

Return without free A Leak

155

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


Leaking here

Finished

On target floor ? True Wait until lift is idle Go to required floor Release memory used to save current floor

Memory

158

C/C++ Example 1
void Fa() { } void Fb() {}

Leak void Leak() { int *a = new int[10]; Fa(); Fb(); return; }


void main() { Leak(); }

Leak memory caused by lacking of release dynamic memory


Solution

delete a[]; return;


159

C/C++ Example 2
void leak() {

Allocation a series, delete only one unit

int **list = new int*[10];


for (int i = 0; i < 10; i++) { list[i] = new int; }

Leak !
delete list; return; }

Solution for (int i = 0; i < 10; i++) { delete list[i]; } delete list; 160

C/C++ Example 3
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()); }

Leak memory when using pointer-returntype

Solution delete []str; Avoid to call directly GenString()


161

C/C++ Example 4
Leak memory because of misunderstanding = operator in C++
#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; }

Stack
Heap Leak! A LEAK!

162

C/C++ Example 5
void main() { Classname *A = new A(); ... ...

Misunderstand free memory method in C/C++


Stack NULL Heap A LEAK!

//free A
A = NULL; }

Solution Keep in mind we are using C/C++ Use MACRO for safe deallocating

#define SAFE_DEL(a) {if(a){delele a;a =163 0;}}

C/C++ Example 6 - STL


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; }

Command prompt Created 0 addr 0xa719c0 Created 1 addr 0xa81a18 -----Before clear---------After clear----Memory leak here

e0 Item 0 Item 1 list e1

164

C/C++ Example 6 STL (cont.)


Command prompt
int main() Created 0 addr 0xb61a28 { list<Element*> m_List; Created 1 addr 0xb71a70 Element *e0 = new Element(0); -----Before clear----Element *e1 = new Element(1); Destroy 0 addr 0xb61a28 //add to list Destroy 1 addr 0xb71a70 m_List.push_back(e0); m_List.push_back(e1); -----After clear----//clear list printf("-----Before clear-----\n"); list <Element*>::iterator i; for (i = m_List.begin(); i != m_List.end(); i++) Free data of each { element pointer delete *i; } m_List.clear(); printf("-----After clear-----\n"); return 0; } 165

Example 7
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; };

m_pB

int main() { CB *B = new CB; CA *A = new CA(); A->m_pB = B; delete(A); printf("%d", B->m_iVal); }

Access violation reading location .

Try to remove delete m_pB

166

Example 7 (cont.)
Leak class CB { public: CB(){ m_iVal = 0; } ~CB(){} int m_iVal; }; class CA { public: CA(){ Delete or not? m_pB = 0; } ~CA(){ delete m_pB; m_pB = 0; } CB *m_pB; };

m_pB

int main() { CA *A = new CA(); A->m_pB = new CB() delete(A); }

Solution Use manual delocate m_pB

167

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

Solution Be careful with virtual for finalization method


168

C/C++ Example 9
class MyClass { public MyClass() { m_pdata2 = new int[100]; } ~ MyClass() { delete []m_pdata2; } int *m_pdata2; } void main() { MyClass* p = new MyClass(); free(p); }

Using new vs free. No destructor will be invoked after free

Leak here

169

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
o Reference Counting

Automatic memory management o Tracing Garbage Collection (GC): Java , C #

No GC mechanic for C/C++

171

Reference Counter: Good or bad ?


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:

Simple method for memory conflict resolution

Algorithms: Increase counter when use as reference Decrease when release Delete memory of counter is zero
172

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


A B D Alloc Alloc Alloc

0
1 2

Which is really needed?

Do I alloc somewhere without release? Somethings else is pointed to an object

Alloc

.. .n

174

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
#include "vld.h" #pragma comment(lib, "vld.lib")
181

VLD Tool
0 After finish application normally, memory leak

information will be display in output

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


182

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
Forward declaration Standard IO Console IO & FILE Template Type casting Exception handling

Memory management
Rest of C/C++ features

Endian STL introduction GNU GCC/G++


184

Outline
Preparation Getting Start OOP
Forward declaration
Standard IO Console IO & FILE Template Type casting Exception handling Endian

Memory management
Rest of C/C++ features

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)


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);

186

Forward declaration
ClassA.h
#ifndef _CLASSA_H_ #define _CLASSA_H_

ClassB.h
#ifndef _CLASSB_H_ #define _CLASSB_H_

#include "ClassB.h" class ClassB;


class ClassA { public: ClassA(); ClassB* m_pB; };

#include "ClassA.h" class ClassA;


class ClassB { public: ClassB(); ClassA* m_pA; };

Class forward declaration

Must be pointer

#endif

#endif

ClassA.cpp
#include "ClassA.h" ClassA::ClassA(){}

ClassB.cpp
#include "ClassB.h" ClassB::ClassB(){}
187

Outline
Preparation Getting Start OOP
Forward declaration
Standard IO Console IO & FILE Template Type casting Exception handling Endian

Memory management
Rest of C/C++ features

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
printf printf printf printf printf printf printf printf ("Characters: %c %c \n", 'a', 65); ("Decimals: %d %ld\n", 1977, 650000L); ("Preceding with blanks: %10d \n", 1977); ("Preceding with zeros: %010d \n", 1977); ("Some different radixes: %d %x %o %#x %#o \n", 100, 100, 100, 100, 100); ("floats: %4.2f %+.0e %E \n", 3.1416, 3.1416, 3.1416); ("Width trick: %*d \n", 5, 10); ("%s \n", "A string");

189

Standard IO
stdio.h

int scanf( const char * format, ... );


Format: %[flags][width][.precision][length]specifier

Reads data from stdin and store

int n; scanf ("%d",&n);

190

Standard IO
<iostream>

std::cout
an object of class ostream that represents the standard

output stream
cout cout cout cout cout cout cout cout << << << << << << << << "Hello there.\n"; "Here is 5: " << 5 << "\n"; "The manipulator endl writes a new line to the screen." << endl; "Here is a very big number:\t" << 70000 << endl; "Here is the sum of 8 and 5:\t" << 8+5 << endl; "Here's a fraction:\t\t" << (float) 5/8 << endl; "And a very very big number:\t" << (double) 7000 * 7000 << endl; "I am a C++ programmer!\n";

191

Standard IO
0 <iostream>

std::cin
an object of class istream that represents the standard

input stream

int input = 0; cout << "Enter a number here: "; cin >> input; cout << "You entered the number " << input << ".\n";

192

File <stdio.h>
FILE * fopen ( const char * filename, const char * mode ); int fclose ( FILE * stream ); size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream ); size_t fread ( void * ptr, size_t size, size_t count, FILE * stream ); int fscanf ( FILE * stream, const char * format, ... ); int fprintf ( FILE * stream, const char * format, ... ); int fseek ( FILE * stream, long int offset, int origin ); Open file Close a file Write block of data to stream Read a block data from stream Read formatted data from stream Write formatted output to stream Reposition stream position indicator Origin: SEEK_SET : beginning of gfile SEEK_END: end of file SEEK_CUR: current position Get current position in stream Set position indicator to the beginning

long int ftell ( FILE * stream ); void rewind ( FILE * stream );

193

File <stdio.h>
#include <stdio.h> int main () { FILE * pFile; pFile = fopen ("myfile.txt","w"); if (pFile!=NULL) { fprintf (pFile, "example"); fclose (pFile); } return 0; }

194

Outline
Preparation Getting Start OOP
Forward declaration Standard IO Console IO & FILE Template Type casting Exception handling

Memory management
Rest of C/C++ features

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 slow down compiling process
template <class identifier> function_declaration; template <typename identifier> function_declaration;

196

Function template Example 1


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; }
197

Function template Example 2


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; }
198

Class template
A class can have members that use template

parameters as types
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'); }

199

Class template
Function member outside the declaration of the class template, we

must always precede that definition with the template <...> prefix

template <class T> class mypair { T a, b; public: mypair (T first, T second) {a=first; b=second;} T getmax (); }; template <class T> T { T retval; retval = a>b? a : b; return retval; } mypair<T>::getmax ()

Template prefix Class prefix Return type

int main () { mypair <int> myobject (100, 75); cout << myobject.getmax(); return 0; }

200

Class template. Template specialization


Define a different implementation for a template
// class template: template <class T> class mycontainer { T element; public: mycontainer (T arg) { element=arg; } T increase () {return ++element;} };

when a specific type is passed as template parameter


// 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; } 201 };

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.

template <class Base> class Mixin : public Base


class Base {};

{};

203

Mixin issue
template <class Base> class Mixin : public Base { public: void Todo() {Base::Do();} };

class Base {};

If the client never calls Todo there is no error

message!
204

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
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; }

206

Outline
Preparation Getting Start OOP
Forward declaration Standard IO Console IO & FILE Template Type casting Exception handling

Memory management
Rest of C/C++ features

Endian STL introduction GNU GCC/G++


207

Type casting
0 Convert from specific type to another type
Explicit casting c-like casting notation

char a = 10; int b = (int) a; bool c = a; float d = float(a);

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


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); } 213

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 inherently unsafe.

Unrelated_class*,

which

are

Can not cast away the const, volatile

214

reinterpret_cast<> Example
// 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; }
215

static_cast<>
0 Allows casting
0 0 0 0 0 0 0

a pointer of a derived class to its base class and vice versa int to enum Reference of type &p to &q Object type P to Object type Q Pointer to a member to pointer to a member with the same hierarchy. Any expression to void 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<>
#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; }

Command prompt integer type, p1 = 3 color c1 = static_cast<color> (p1) enum type, c1 = 3 Press any key to continue . . .
217

dynamic_cast<>

Enable Run-Time Type Info first

218

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<>
Class Base upcast

Type conversion from base class

Class Derive1 downcast Class Derive2

pointer to a derived class pointer is called downcast.


Type conversion from derived

class pointer to a base class pointer, is called upcast.


Base

From a class to a sibling class in

Derive1
Derive2

class hierarchy: crosscast

220

dynamic_cast<> upcast
Always successful
Why?

Base Derive1 Derive2 Derive class always contents valid complete base class
221

dynamic_cast<>
upcast multiple conversion with multiple inheritace
Base
CAN NOT cast directly from Derived3 to base. Do step by step: Derived3 Derived2 Base Or Derived3 Derived1 Base

Derived 1

Derived 2

Derived 3

222

dynamic_cast<> downcast
Base Funct2() Derive Funct3()

Available for polymorphism

class only
class Base1 { public: virtual void funct1(){}; };

class Derived1:public Base1 { public: virtual void funct2(){}; };


223

dynamic_cast<> downcast (cont.)


Base Funct2() Derive Funct3() Test2 Test1

Base* Test1 = new Derived; Base* Test2 = new Base;


Derived* Test3 = dynamic_cast<Derived*>(Test1);

successful

fail Derived* Test4 = dynamic_cast<Derived*>(Test2);


224

dynamic_cast<> crosscast
Crosscast Base2 Derived1
Base Derived 1 Derived 2 Fail
Base2 *p1 = new Base2; Derived1 *p2 = dynamic_cast<Derived1*>(p1);

Base2

Derived 3

OK
Base2 *p1 = new Derived3; Derived1 *p2 = dynamic_cast<Derived1*>(p1);

225

Outline
Preparation Getting Start OOP
Forward declaration Standard IO Console IO & FILE Template Type casting Exception handling

Memory management
Rest of C/C++ features

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


Handling & catching exception
try { // code that may generate exceptions } catch(type1 id1) { // handle exceptions of type1 } Catch(...) { // catch any exception }

Throw exception
throw type; //type: user defined type or principle type

227

Exception example
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"); } } 228

Outline
Preparation Getting Start OOP
Forward declaration Standard IO Console IO & FILE Template Type casting Exception handling

Memory management
Rest of C/C++ features

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)


Big endian
Little endian 0000.0000 0000.0000 0000.0100 0000.0001

0000.0001

0000.0100

0000.0000

0000.0000

230

Endian - Example
int main() { char num[4] = {0x00, 0x11, 0x22, 0x33}; int *val = (int*)num; printf("val = 0x%x", *val); }
Command prompt
val = 0x33221100 Windows 32 bits

Important notes: Avoid to save/load a short/int/long array. Use char (byte) array instead.
231

Outline
Preparation Getting Start OOP
Forward declaration Standard IO Console IO & FILE Template Type casting Exception handling

Memory management
Rest of C/C++ features

Endian STL introduction GNU GCC/G++


232

STL
Standard template library Powerful library for container and algorithms Some basic types:

Vector Deque List . push pop insert copy erase


233

Some basic methods

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
#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; }

235

STL and memory management


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; }

Command prompt 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

???

Copy of Elements are created and stored in list


236

STL and memory management


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; }

Command prompt Created 0 addr 0xa719c0 Created 1 addr 0xa81a18 -----Before clear---------After clear----Memory leak here

e0 Item 0 Item 1 list e1

237

STL and memory management (cont)


Command prompt
int main() Created 0 addr 0xb61a28 { list<Element*> m_List; Created 1 addr 0xb71a70 Element *e0 = new Element(0); -----Before clear----Element *e1 = new Element(1); Destroy 0 addr 0xb61a28 //add to list Destroy 1 addr 0xb71a70 m_List.push_back(e0); m_List.push_back(e1); -----After clear----//clear list printf("-----Before clear-----\n"); list <Element*>::iterator i; for (i = m_List.begin(); i != m_List.end(); i++) Free data of each { element pointer delete *i; } m_List.clear(); printf("-----After clear-----\n"); return 0; } 238

Outline
Preparation Getting Start OOP
Forward declaration Standard IO Console IO & FILE Template Type casting Exception handling

Memory management
Rest of C/C++ features

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
make.bat
@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)

makefile
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

MyClass1.h
#ifndef __MYCLASS_H__ #define __MYCLASS_H__ class MyClass { public: MyClass(); }; #endif

main.cpp
#include "MyClass1.h" int main() { MyClass *c = new MyClass(); return 1; }

MyClass1.cpp
#include <cstdio> #include "MyClass1.h" MyClass::MyClass() { printf("Hello\n"); }

241

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


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; }

To Ensure a class has

only one instance, and provide a global point of access to it

int main() { ExpensiveRes::GetInstance(); }

244

Reference
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

From Java to C Mihai Popa Gameloft Thinking in C++, 2nd Edition - Bruce Eckel, President, MindView, Inc. http://en.wikipedia.org http://www.learncpp.com http://msdn.microsoft.com http://www.cplusplus.com http://en.allexperts.com http://www.desy.de/gna/html/cc/Tutorial/tutorial.html http://aszt.inf.elte.hu/~gsd/halado_cpp/ http://www.codeguru.com/forum/showthread.php http://www.uow.edu.au/~nabg/ABC/ABC.html http://pages.cs.wisc.edu/~hasti/cs368/CppTutorial/ http://www.devmaster.net http://enel.ucalgary.ca/People/Normal/enel1315_winter1997/ http://www.cantrip.org http://sourcemaking.com/designed_patterns

245

Você também pode gostar