Вы находитесь на странице: 1из 245

Outline

Preparation

Getting Start

OOP

Memory management

Rest of C/C++ features

Appendix 2
Outline
Preparation
Hello world
Getting Start
C/C++ files
OOP
Entry point
Memory management
C/C++ libraries
Rest of C/C++ features
Source compile process
Appendix 3
Outline
Preparation
Variables and constant

Getting Start Primary data type

OOP Array Pointer String

Memory management Data structure: enum union - struct

Function
Rest of C/C++ features
Namespace
Appendix 4
Outline
Preparation
Class & Object
Getting Start
Inheritance
OOP
Polymorphism
Memory management
Operator overloading
Rest of C/C++ features
Class static member
Appendix 5
Outline
Preparation
Recall pointer
Getting Start
Memory leak
OOP

Memory management

Rest of C/C++ features

Appendix 6
Outline
Preparation Forward declaration

Standard IO Console IO & FILE


Getting Start
Template
OOP
Type casting

Memory management Exception handling

Endian
Rest of C/C++ features
STL introduction
Appendix GNU GCC/G++ 7
Outline
Preparation
Hello world!
Getting Start
C/C++ files

OOP Entry point

Memory management C/C++ libraries

Source compile process


Rest of C/C++ features
8
Outline
Preparation
Hello world!
Getting Start
C/C++ files
Basic Data Structure
Entry point
OOP
C/C++ libraries
Memory management
Source compile process
Rest of C/C++ features 9
Hello world using VS

10
Hello world
main.cpp
# include <stdio.h> Use standard IO lib

void main() Entry point


{
printf("Hello world"); Print to console screen
}

11
Outline
Preparation
Hello world!
Getting Start
C/C++ files

OOP Entry point

Memory management C/C++ libraries

Source compile process


Rest of C/C++ features
12
C/C++ source files
#include "stdio.h" # include "header.h"
void Todo1()
void Todo1(); {
void Todo2(); Todo2();
}
void Todo2(){}
void main()
{
Todo1();
}

Header file (.h)


aka include file
Source file (.c / .cpp)
Hold declarations for other files Content implementation
use (prototype)
Required
Not required
13
Outline
Preparation
Hello world!
Getting Start
C/C++ files

OOP Entry point

Memory management C/C++ libraries

Source compile process


Rest of C/C++ features
14
Entry point
Form1.cpp
Required unique entry point
void main()
{ The most common is: main
// your code here
}

Form2.cpp
int main(int n, char ** args)
{ Error when no entry point is defined
// your code here
} 1>LINK : fatal error LNK1561: entry point
must be defined

15
Outline
Preparation
Hello world!
Getting Start
C/C++ files

OOP Entry point

Memory management C/C++ libraries

Source compile process


Rest of C/C++ features
16
C/C++ standard library
C/C++ support a set of internal #include "stdio.h"
basic library, such as
void main()
Basic IO {
Math printf("hello");
Memory handle }


For using, include the header
file
#include <>
#include ""

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 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
C/C++ files
Getting Start
Entry point

OOP C/C++ libraries

Memory management Hello world!

Source compile process


Rest of C/C++ features
23
Process

Preprocessed
Source
preprocess source Compile
.h/.c/.cpp
(c/cpp)

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

Executable/ .o / .obj
lib Linker (object file)

24
Outline
Preparation Variables and constant

Primary data type


Getting Start
Array Pointer - String
OOP
Data structure: enum union - struct

Memory management Function

Rest of C/C++ features Namespace


25
Outline
Preparation Variables and constant

Primary data type


Getting Start
Array Pointer - String
OOP
Data structure: enum union - struct

Memory management Function

Rest of C/C++ features Namespace


26
Variable classification
Scope: Storage class specifier
Local variable auto
Global variable static
Static variable register
extern

27
Global & local
int mGlobalVar; Global variable
void Foo() Available in all of program
{
int localVar;
Set default value to zero
printf("Foo : %d %d\n",
localVar, mGlobalVar);
} Local variable
NO default value
int main() Available inside block
{
int localVar = 1;
printf("Main: %d %d\n",
localVar, mGlobalVar);
mGlobalVar = 1; Command prompt
Foo();
Main: 1 0
return 1;
} 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>
Allocated when the program
static int s_iGlobalStatic; starts and is deallocated when
void Foo()
the program ends.
{
static int s_iLocalStatic;
printf("Foo: called %d\n",
Default value is zero (0)
s_iLocalStatic++);
}

int main()
{
int localVar = 1; Command prompt
printf("Main: %d\n",
s_iGlobalStatic); Main: 0
Foo(); Foo: called 0
Foo(); Foo: called 1
Foo();
return 1; Foo: called 2
} 30
Register variable
int main() Stored in a machine register if
{ possible
int sum = 0;
for (register int i = 0; Usually used in for iterator
i < 100; for improve performance
i++)
{
sum += i;
}
printf("Sum = %d\n", sum);

return 1;
}

31
Extern variable
Extern.cpp
Specify that the variable is
int m_iExternVar = 100; declared in a different file.

main.cpp Compiler will not allocate


#include <cstdio> memory for the variable

extern int m_iExternVar; Avoid duplicate declaration

int main() Share (global) variable for


{ multiple .cpp files
printf("Value = %d\n",
m_iExternVar);
Command prompt
return 1;
} 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 Variables and constant

Primary data type


Getting Start
Array Pointer - String
OOP
Data structure: enum union - struct

Memory management Function

Rest of C/C++ features 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 (216 -1)
signed short: -215 (215 1)
int 4 bytes unsigned int: 0 (232 -1)
-231 (231 1) signed int: -231 (231 1)
long 4 bytes unsigned long: 0 (232 -1)
-231 (231 1) signed long: -231 (231 1)
long long 8 bytes unsigned long long: 0 (264 -1)
-263 (263 1) signed long long: -263 (263 1)
bool 1 byte True /false (non-zero / zero)

float 4 bytes

double 8 bytes 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

Return 4
int sizeInt = sizeof(int);
int sizeLong = sizeof(long); Return 4

char a;
int sizeA = sizeof(a); Return 1

37
Outline
Preparation Variables and constant

Primary data type


Getting Start
Array Pointer - String
OOP
Data structure: enum union - struct

Memory management Function

Rest of C/C++ features 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>] si MUST BE constant

Index of array is counted from 0 to (si-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]); b[10] = ?

}
printf("%d\n", b[10]); 39
Array Assignment
int a[4] = {1, 2, 3, 4}; a[0], a[1],
a[2], a[3] = ?
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));
40
Array Assignment
2D Array Same as
1D. Why?

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


a[0][0] = 1;
a[0][1] = 2; int a[][2] = {1, 2, 3, 4, 5, 6};
a[1][0] = 3;
a[1][1] = 4;
a[2][0] = 5; int a[3][2];
a[2][1] = 6; 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


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

0x10 0x00 0x00 0x00 int *pi = &i;


0xF1 0xF2 0xF3 0xF4 0xF5 0xF6 0xF7 0xF8
i int* pi;
pi = &i; 43
&i
Pointer (cont.)
Pointer is also a variable its stored in memory

int i = 10;
int *p = &i;
0x2f00002c i = 10

p = 0x2f00002c
0x2f00aabb 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
int i = 0x3f20cc01;
0x01 0xcc 0x20 0x3f
char *p1 = (char *)&i;
0xF1 0xF2 0xF3 0xF4 0xF5 0xF6 0xF7 0xF8 short *p2 = (short *)&i;
i Little Endian
int *p3 = &i;

P1 P2 P3

p1 is pointed to char-block. *p1 = 0x01


p2 is pointed to short-block. *p2 = 0xCC01
p3 is pointed to int-block. *p3 = 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 desc Example Note: each step is a distance k bytes
or
belongs to type of pointer:
+ move forward n steps p += 10;
byte: 1 byte
- move backward n step p -= 1; Short: 2 byte
(p1+1) (p2 + 1)
++ move forward 1 step p++; . *(p1+1) *(p2+1)
&(p1+1) &(p2+1)
-- move backward 1 step p--;

0x01 0xcc 0x20 0x3f 0x00 0x10 0xaa 0x01 0xcc 0x20 0x3f 0x00 0x10 0xaa

0x01 0x02 0x03 0x04 0x05 0x06 0x07 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};
0x001cff04 p
char *p = a;
0x001cff08
a
a = ? p + 1 = ?
&a = ? (*p) + 1 = ?
*a = ? *(p + 1) = ?
&p + 1;
p = ? &a + 1
&p = ? a++; a = ?
*p = ? 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; 0x100 iVar = 10


int *p1 = &iVar;
int **p2 = &p1;

*p1 == ? 0x200 p1 = 0x100


*p2 == ?
*(*p2) == ? 0x300 p2 = 0x200

49
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
How about
Dynamic allocation
User pointer p after
Allocation a block of memory in heap high capacity deleting?
Clean up easily

int *p = new int[n]; delete p;


Alloc n-int elements in heap Free memory block pointed by p

nx4 bytes
p p 50
Pointer
Dynamic allocation (cont.)
There two way for dynamic allocation

Old C style C++ style


Using stdlib.h Using new/delete
Using malloc/free Using new[] / delete[]
int main() int main()
{ {
char *i = (char*) malloc (100); char *i = new char[100];

// some code here // some code here

free(i); delete []i;


} }

51
Pointer
Dynamic allocation (cont.)
Use delete for new,
Use delete[] for new[]
struct A int main()
{ {
public: A *cA = new A[10];
static int count; delete cA;
int val; return 1;
A() }
{
printf("Created %d\n", Delete cA[0] only
val = count++);}
~A() int main()
{ {
printf("Deleted %d\n", A *cA = new A[10];
val);} delete []cA;
}; return 1;
}
int A::count = 0;
Delete all cA 52
Pointer-to-pointer dynamic
allocation
0x200

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

0x900 p = 0x500

In common, used for allocation an 2D-array


int **p = new int*[3]; *(*(p + i) +j ) p[i][j]
p[0] = new int[4];
p[1] = new int[4];
p[2] = new int[4]; 53
Pointer vs. Array
In common, pointer could be used like array
*p = *(p+0) = p[0]
stack
*(p + n) = p[n]
0x2f0A0000 P = 0x2f330000

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

5 0x2f330008

54
Pointer vs. Array
int main()
{ Array is a pointer
char a[3] = {1, 2, 3, 4};
printf ("0x%x 0x%x %d\n", a, &a, *a); pointed to itself
int *p = new int[3]; A pointer can point to
p[0] = 1; p[1] = 2; p[2] = 3;
printf ("0x%x 0x%x %d\n", p, &p, *p);
an array addr.
int *p2 = (int*)a;
printf("value of p2 = 0x%x\n", *p2);

Command prompt
0x14fd64 0x14fd64 1
0x591398 0x14fd60 1
Value of p2 = 0x04030201
55
Pointer vs. Array
char a[3] = {1, 2, 3}; 0x0E1AF0 10
0x0E1AF1 20 p+1
char *p = new char[3]; 0x0E1AF2 30
p[0] = 10; p[1] = 20; p[2] = 30; 0x0E1AF3
0x0E1AF4
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);

0x26FE6C 1 a
0x26FE6D 2 a+1
&a + 1 0x26FE6E 3
0x26FE6F
Command prompt 0x26FE70
0x26FE71
a = 0x26FE6C p = 0x0E1AF0 0x26FE72 p
a+1 = 0x26FE6D p+1 = 0x0E1AF1 0x26FE73
&a = 0x26FE6C &p = 0x26FE70 0x26FE74

&a+1= 0x26FE6F &p+1 = 0x26FE74


&p + 1 56
Pointer vs. Array
Due to stack limited, can not create a too big array
int main() FAIL int main() OK
{ {
char arr[1034996]; char *p = new char[1034996];
} }

0 Can not delete an array


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

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 pointer-to-pointer
int arr[2][3] int **p = new int*[2];
p[0] = new int[3];
[0][0] [0][1] [0][2] [1][0] [1][1] [1][2]
p[1] = new int[3];

Block 0 Block 1

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

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


[1][0] [1][1] [1][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
*(*(p + i) +j ) p[i][j] 58
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* GetString3()
{ {
char *st = "String"; char *st = new char[6];
return st; strcpy(st, "String");
} return st;
}
char* GetString2()
{
char 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.

64
http://www.cplusplus.com/reference/clibrary/cstring/
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 Variables and constant

Primary data type


Getting Start
Array Pointer - String
OOP
Data structure: enum union - struct

Memory management Function

Rest of C/C++ features Namespace


66
Enum
Use for set up collections of named integer constants
In traditional C way:

#define SPRING 0
#define SUMMER 1
#define FALL 2
#define WINTER 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; // C style


MyEnum y; // 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
{ Memory block 0x04 0x03 0x02 0x01
int iValue;
char cValue;
char aValue[4];
iValue 0x01020304
};
cValue 0x04
int main()
{ aValue 0x04 0x03 0x02 0x01
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],
sizeof(mine) = ?
mine.aValue[3]);
} 69
Struct
Define a structure type and/or a variable of a
structure type.
struct T_MyStruct T_MyStruct
{
int val1; val1
char val2;
char val3[5]; val2
};
struct T_MyStruct myStruct; 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
{
0 Before compile, total memory
char val1; of T_MyStruct is 8 byte
short val2;
int val3; val1 val2 val3 val4
char val4;
0 1 3 7
};
4 bytes alignment
char: 1 byte aligned
short: 2 byte aligned
int : 4 byte aligned pad
val1
1
val2 val3 val4 pad2

0 1 2 3 4 8 9 10 11

4 bytes block 4 bytes block 4 bytes block


sizeof(T_MyStruct) == 12 bytes 73
VS Struct member alignment

74
GCC alignment
struct test_t
{
int a;
char b;
int c;
}__attribute__((aligned(8))); 8 byte alignment

struct test_t
{
int a;
char b;
int c;
}__attribute__((__packed__)); smallest possible alignment

http://www.delorie.com/gnu/docs/gcc/gcc_62.html 75
Struct - function
typedef struct T_MyStruct
{
C++ only, not available
int val1; in C
char val2;
char val3[12]; Beside variable, struct
void SayHello();
also has had function
}MyStruct; Struct alignment is not
void MyStruct::SayHello() effected to struct-
{
printf("Hello world");
function
} Function is not counted
int main() when calculate struct
{
MyStruct myStruct;
size
myStruct.SayHello();
}
76
Struct
constructor / destructor
typedef struct T_MyStruct
{
C++ only, not available in C
int val1; constructor Two special function of struct
T_MyStruct();
Constructor: automatically call
~T_MyStruct(); when a instant of struct is created
}MyStruct;
destructor
Destructor: automatically call
T_MyStruct::T_MyStruct() when a instant of struct is destroy
{
printf("Created\n");
}
T_MyStruct::~T_MyStruct()
{ Command prompt
printf("Destroy\n");
} Created
Destroy
int main()
{
MyStruct myStruct;
} 77
Struct and static member
typedef struct T_MyStruct
{ Static function & static
int val1;
static char val2;
variable
static void SayHello() {} Static variable is not
}MyStruct;
counted is struct
int main() alignment and struct
{
MyStruct myStruct; size
printf("%d", sizeof(myStruct));
MyStruct::SayHello();
}

78
Struct and Access privilege
struct MyStruct
{ C++ only, not available in C
int valx; Three access privilege methods
public: public: visible for all
int val1; private: visible inside struct only
private: protected: visible inside struct and
int val2; retrieved struct (OOP)
protected:
Default is public
int val3;
o For example: valx is public
};

int main()
{
MyStruct mine;
mine.val1 = 0; Fatal Error, val2 is private
mine.valx = 0;
mine.val2 = 0;
mine.val3 = 0; Fatal Error, val3 is protected 79
}
Outline
Preparation Variables and constant

Primary data type


Getting Start
Array Pointer - String
OOP
Data structure: enum union - struct

Memory management Function

Rest of C/C++ features 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 );
Set default value

void foo(int a, int b, int c) Command prompt


printf("%d %d %d\n",
a, b, c);
0 1 2
} 0 10 2
0 10 100
void main()
{ Use b, c as default value
foo(0);
foo(0, 10);
foo(0, 10, 100); 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 RULES
error C2548: 'foo' : missing default When a parameter is set default value, the
parameter for parameter 3 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)
Reference parameter {
n++;
}
void main()
{ x=2
Constant parameter int x = 2;
foo(x);
printf("%d\n", x);
}
Const Reference
parameter
x 2 x 2
x 2 x 2
Pointer parameter n 2 n 3
86
foo
Parameter classification
Pass-by-reference
Value parameter Actually parameter itself is passed
Use reference operator &
void foo(int &n)
Reference parameter {
n++;
}
void main()
{ x=3
Constant parameter int x = 2;
foo(x);
printf("%d\n", x);
}
Const Reference
parameter
x x
x 2 2 3 x 3
Pointer parameter n n
87
foo
Parameter classification
Pass-by-value
Value parameter A copy of parameter is made and
strict as const.
void foo(int cont n)
Reference parameter {
n++; Fail, can not
}
void main() modified
{ const value
Constant parameter int x = 2;
foo(x);
printf("%d\n", x);
}
Const Reference
parameter
x 2 x 2
x 2
Pointer parameter n 2 n 3
88
foo
Parameter classification
Pass-by-ref
Value parameter
Actually parameter itself is passed but
avoid modify
Void the overhead of creating a copy
Reference parameter

Constant parameter void foo(int const &n)


{
//todo
Const Reference }
parameter

Pointer parameter
89
Parameter classification
In common, Pass-by-value
Value parameter
A copy of parameter is made
Value of parameter is an address of a
Reference parameter memory block
void foo(int *n)
{
Constant parameter
//todo
}
Const Reference
parameter
Value of parameter will not be
change,
Pointer parameter
but memory block which pointed
by parameter could be modified.
90
Pointer Parameter
A
#include <cstdio> Copy value
B
void foo(int *A, int *B) (addr. of data)
{
foo
int *tmp = A; A
A = B;
B
B = tmp;
}
A
void main()
B
{
int A[] = {1, 2, 3};
A
int B[] = {10, 11};
printf("0x%x 0x%x\n", A, B); B
foo(A, B);
printf("0x%x 0x%x\n", A, B);
}
Command prompt

0x29faa8 0x29faa0
0x29faa8 0x29faa0 91
Pointer Parameter
A[2] = 3
#include <cstdio> A
void foo(int *A) Copy value
{ (addr. of data)
A[2] = 10; foo
} A 1
2
void main()
{
A[2] = 10 3 10
int A[] = {1, 2, 3};
printf(%d\n", A[2]);
foo(A); A
printf(%d\n", A[2]);
} 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> foo A


void foo(int *&A, int *&B) B
{
int *tmp = A; A = B; B = tmp;
} A
void main() B
{
int arr1[] = {1, 2, 3}; A
int arr2[] = {10, 11}; B
int *A = arr1;
int *B = arr2;
printf("0x%x 0x%x\n", A, B);
Command prompt
foo(A, B); 0x31fc90 0x31fc88
printf("0x%x 0x%x\n", A, B); 93
}
0x31fc88 0x31fc90
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

header.h
Main.cpp void Todo1();
void Todo1() void Todo2();
{
Todo2(); Error Main.cpp
} error C3861: #include "header.h"
void Todo2() 'Todo2': identifier void Todo1()
{} not found {
int main() Todo2();
{} }
void Todo2(){} 95
int main(){}
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 Main.cpp
#include <cstdio> #include <cstdio>
extern void TodoExtern();
void TodoExtern()
{ int main()
printf("TodoExtern\n"); {
} 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 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

Ansi_c.c C_plusplus.cpp
#include <stdio.h> extern "C"
void ExternC() {
{ void ExternC();
printf("ExternC\n");
} 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() int main()
{ {
printf("%d", NEXT(1)); printf("%d", (a + 1));
} }

101
Inline function (cont)
Like macro, but obeys C/C++ syntax
inline int Next(int x)
{
return x + 1; Why
} performance is
improved?
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

102
Outline
Preparation Variables and constant

Primary data type


Getting Start
Array Pointer - String
OOP
Data structure: enum union - struct

Memory management Function

Rest of C/C++ features 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 More than two definition of
{ add functions
void add();
} maths::add()
namespace matrix matrix::add()
{
void add();
ambiguous call fatal error.
}

using namespace maths; In this case, MUST BE specify


using namespace matrix;
namespace.
void main()
{ error C2668: 'matrix::add' : ambiguous call to overloaded function
add(); .\main.cpp(8): could be 'void matrix::add(void)'
} .\main.cpp(3): or 'void maths::add(void)'
107
Outline
Preparation Class & Object
Getting Start Inheritance

OOP Polymorphism

Memory management Operator overloading

Class static member


Rest of C/C++ features
108
Outline
Preparation Class & Object
Getting Start Inheritance

OOP Polymorphism

Memory management Operator overloading

Class static member


Rest of C/C++ features
109
Class
As same as struct
Class name
Default access is private
class MyClass
Access methods
{
public:
MyClass(); Constructor
~MyClass();
Destructor
protected:
int GetVal() {return m_Var;}
Function (methods)
void Todo();
private:
int m_Var; Inline methods
void SayHello();
}; Class variable (property)
void MyClass::Todo()
{
Function implementation
110
//some code here
}
Class (cont)
In traditional, code of class is divided into 2 parts
Declaration: in .h file
Implementation: in .cpp file

Any_name.h Any_name.cpp
#ifndef __CCLASS_H__ #include "Any_name.h"
#define __CCLASS_H__ void CClass::Todo()
{
class CClass
{ }
public: CClass::~CClass()
CClass(); {
~CClass();
private: }
void Toso() ;
};
#endif
111
How to use class
Create a object directly
MyClass objA; //or MyClass objA()
Access class methods,
objA.SayHello();
properties by using dot

MyClass *ObjB = new MyClass; Create a object through pointer.


//or MyClass *ObjB = new MyClass(); Two ways to use methods,
(*objA).SayHello(); properties
objA->SayHello(); 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(); Default constructor

MyClass(MyClass* A);
MyClass(const MyClass& A); Copy constructor.

MyClass(int val);
} 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 (const X& copy_from_me)


X (X* copy_from_me)
X (X& copy_from_me)
X (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(){} Invoked when
ABC(ABC *A){printf("here1\n");}
ABC(const ABC &A) When a object is created
{ from another object of
printf("here2\n");
} the same type
};
void Foo1(ABC A){} When an object is
ABC Foo2() passed by value as
{
ABC a; parameter to function
return a;
} When a object is return
int main() from a function
{
ABC *A = new ABC();
ABC B(A);
Foo1(A);
Foo2(); 116
}
Copy constructor (cont)
A default copy constructor is created automatically,
but it is often not what you want.

Automatic generated copy constructor User-defined (expected) copy contructor


Image(Image *img) { Image(Image *img) {
width = img->width; width = img->width;
height = img->height; height = img->height;
data = img->data; 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() Without explicit With explicit


{
A a1 = 37;

A a2 = A(47);

a1 = 67;

f(77);
}

"nonconverting"
Explicit constructor syntax is required.
118
Destructor
class MyClass
{
char m_Var; Automatically invoked when
int m_pData;
public: an object is destroy:
MyClass(char id) { Out of scope
m_Var = id;
m_pData = new int[100]; Or manually free (use
}; pointer)
~MyClass() {
delete m_pData;

}
cout<<"Destroyed "<<m_Var<<endl; Use for collect class memory
};
Command prompt
int main()
{ ---Alloc A---
cout << "---Alloc A---"<<endl; ---Free A---
MyClass *A = new MyClass('A');
cout << "---Free A---"<<endl; Destroyed A
delete A; ---Create B---
cout << "---Create B---"<<endl;
MyClass B('B'); ---End---
cout << "---End---"<<endl; Destroyed B
return 1;
} 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), Setup value of properties
m_pVar3(0)
{
}
121
Outline
Preparation Class & Object
Getting Start Inheritance

OOP Polymorphism

Memory management Operator overloading

Class static member


Rest of C/C++ features
122
Inheritance
Code reuse:
Composition: create objects of existing class inside the
new class class NewClass
Existing class {
public:
ExistingClass *m_member;
New class };

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


class

Base class class Derive: public Base


{
Hierarchy model };
Derive class
123
Inheritance syntax
class Base class Derive: public Base
{ {
public: public:
Base() {}
void publicFunc() {}
Derive():Base() {}
void Todo() {} void Todo();
protected: }; Constructor init
void protectedFunc() {}
private: void Derive::Todo()
void privateFunc() {} {
}; this->protectedFunc();
this->publicFunc();

FAIL: cannot access private member this->privateFunc();

Access bases method (same name) Base::Todo();


}
124
Inheritance access
Base access Inherit access Derive access
Public Public
Protected Public Protected
Private Private
Public Protected
Protected Protected
Private
Private
Public
Protected Private private
Private

125
Inheritance access
Example
class CAnimal void main()
{
public:
{
void Drink(); CRabbit rab;
protected: rab.Drink();
void Run(); rab.Eat();
private:
void 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: Human Musician Worker
Musician(int instrument, int year){}
};

class Worker
{
public:
Base2(int level){} StreetMusician
};

class StreetMusician: public Human,


protected Musician,
private Worker
{
public:
StreetMusician(): Human(),
Musician(1, 1),
Worker(10) {} 128
};
Inheritance
Ambiguous access
class CBase1 class CDerive: CBase1, CBase2
{ {
public: public:
CDerive(): CBase1(), CBase2()
void Hello();
{
}; Hello();
}
class CBase2 };
{
public:
void Hello(); Ambiguous access of 'Hello
};
How to CBase1::Hello()
solve? CBase2::Hello()

129
Outline
Preparation Class & Object
Getting Start Inheritance

OOP Polymorphism

Memory management Operator overloading

Class static member


Rest of C/C++ features
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: Overriding: override a
virtual void Eat(){}
void Run(){}
bases virtual or non-
}; virtual methods
class Cat: public Animal
{
public:
Overloading: several
//overiding methods with the same
void Eat(){}
void Run(){}
name which differ from
parameters
//overloading
void Jump();
void Jump(int distance);
};
133
class Animal
{
Virtual Overriding vs.
public:
virtual void Eat()
non-virtual Overriding
{
cout<<Animal:Eat"<<endl;
}
void Run()
{
cout<<Animal:Run"<<endl;
}
};
Obj is a Animal pointer, but
class Cat: public Animal really a Cat instant
{
public:
void Eat()
{ Without virtual (early binding),
cout<<Cat:Eat"<<endl;
} Animal:Run was called instead
void Run()
{
of Cat::Run
cout<<Cat:Run"<<endl;
}
};

int main()
{
Animal *obj = new Cat(); Command prompt
obj->Eat();
obj->Run(); Cat:Eat
} Animal:Run
134
class Base
{
public:
Virtual
~Base()
{
cout<<"Destroy Base"<<endl;
destructor
}
};

class Derive: public Base When obj is freed, both


{
public: itself and base MUST BE
~Derive()
{
deleted
cout<<"Destroy Derive"<<endl;
}
};
Its ok for obj1, but
int main()
{
problem for obj2
Derive *obj1 = new Derive();
Base *obj2 = new Derive();
cout<<"--Free obj1--"<<endl; Command prompt
delete obj1; --Free obj1--
cout<<"--Free obj2--"<<endl;
delete obj2; Destroy Derive
} Destroy Base
--Free obj2--
135
Destroy Base
class Base
{ Virtual destructor
public:
virtual
{
~Base() (cont)
cout<<"Destroy Base"<<endl;
}
};

class Derive: public Base To solve this problem,


{
public: use virtual destructor
~Derive()
{
cout<<"Destroy Derive"<<endl;
}
};

int main()
{ Command prompt
Derive *obj1 = new Derive(); --Free obj1--
Base *obj2 = new Derive(); Destroy Derive
cout<<"--Free obj1--"<<endl;
delete obj1; Destroy Base
cout<<"--Free obj2--"<<endl; --Free obj2
delete obj2; Destroy Derive
}
Destroy Base
136
Pure virtual function
Pure virtual class
class Base Pure virtual function:
{
public: Virtual function with no body
virtual void Todo() = 0;
}; Pure virtual class:
Class content pure virtual function
class Derive: public Base
{
void Todo() {}
} 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 Class & Object
Getting Start Inheritance

OOP Polymorphism

Memory management Operator overloading

Class static member


Rest of C/C++ features
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
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; This implementation make user confused
}
};

int main()
{
Integer ii(1), jj(2), kk(3);
kk += ii + jj;
cout << "Value = " << kk.i << endl; 140
}
Outline
Preparation Class & Object
Getting Start Inheritance

OOP Polymorphism

Memory management Operator overloading

Class static member


Rest of C/C++ features
141
Static function
class MyClass Allow user invokes
{
public: without creating an
static void Todo(); instance
};
Declaration with static
void MyClass::Todo() keyword
{
//implemetation
No need to create
} object, but must be
declared class name
int main()
{
MyClass::Todo();
}
142
Static variable
class MyClass { Same as static function
public:
static int s_Var; Value of static variable
}; MUST BE set outside
int MyClass::s_Var = 99;
class declaration.

int main()
{
printf("%d",
MyClass::s_Var);
}

143
Lazy initialization
class ExpensiveRes
{
public:
ExpensiveRes() {}
void todo1();
0 The tactic of delaying the
static ExpensiveRes* GetInstance(); creation of an object,
private:
static ExpensiveRes* s_Instance; calculation of a value, or
};
ExpensiveRes* ExpensiveRes::s_Instance = 0;
some other expensive
ExpensiveRes* ExpensiveRes::GetInstance() process until the first
{
if (!s_Instance) time it is need.
{
s_Instance = new ExpensiveRes();
}
return s_Instance;
}

int main()
{
ExpensiveRes::GetInstance()->todo1();
ExpensiveRes::GetInstance()->todo1(); 144
}
Outline
Preparation Recall pointer
Getting Start Memory leak
OOP

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)
Code segment:
Global area
where the compiled program sits in
memory
Stack segment Global area:
store global variables
Stack segment:
where parameters and local variables are
allocated
Heap Segment Heap segment:
where dynamically allocated variables are
allocated

149
Stack
Text segment
(Code segment)
Parameters
Return Address Global area Where parameters and local
where to begin execution
when function exits
variables are allocated
Stack frame
Dynamic link Limited size Stack
pointer to caller's stack
frame overflow
Static link
pointer to lexical parent
Memory use in stack is
(for nested functions)
temporary and auto release
Return value
Fast processing/low size
Local variables Stack frame

Concept Stack frame Heap Segment

150
Heap
Text segment
(Code segment)
Parameters
Large pool of memory
Return Address Global area
where to begin execution Dynamic allocation
when function exits

Dynamic link
Stack frame Stays allocated until
pointer to caller's stack specifically deallocated
frame
leak !
Static link
pointer to lexical parent Must be accessed through a
(for nested functions)
pointer
Return value Large arrays, structures, or
Local variables Stack frame classes should be stored
Heap why?
Concept Stack frame Heap Segment Large & dynamic

151
Heap vs Stack
Stack
int _array[10]; stored in stack

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

Value of:
Stack Heap _array : address where int point into in heap (0x00FF)

(*_array): value at it's address on heap (10)


0x00FF 10 (&_array): address of the memory which used for stored pointer

_array in stack (0x0005)


_array
0x0005 0x00FF

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]; 4000 bytes
// some code here
// ...
// without delete A
//
return; 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 Button is
No GC mechanic supported pressed

Save current floor


Leaking
here
On target
Finished Memory
floor ?
True
Wait until lift is idle

Go to required
floor
Release memory used to
save current floor 158
C/C++ Example 1
void Fa()
{ Leak memory
caused by
}

void Fb()
{}

void Leak() Leak !


lacking of release
{
int *a = new int[10]; dynamic memory
Fa();
Fb();
return;
}
Solution
void main()
{
Leak(); 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;

}
Solution
Leak !
for (int i = 0; i < 10; i++)
delete list; {
delete list[i];
return;
}
} delete list; 160
C/C++ Example 3
char* GenString() Leak memory when
{
char *a = new char[10];
using pointer-return-
a[9] = '\0'; type
return a;
}

void Leak()
{
char *str = GenString();
printf("%s\n", str);
printf("%s\n", GenString()); 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() Stack


{
Heap
int* a = new int[100];
a = new int[1000];
} Leak! A
LEAK!
void Foo1()
{
int* a = new int[100];
int* b = new int[1000];
a = b;
}
162
C/C++ Example 5
Misunderstand free memory method
void main() in C/C++
{ NULL
Stack
Classname *A = new A();
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 Command prompt
{ Created 0 addr 0xa719c0
int ID;
public: Created 1 addr 0xa81a18
Element(int id) -----Before clear-----
{ -----After clear-----
printf("Created %d at 0x%x\n", id, this);
ID = id;
} Memory
~Element()
{ leak here
printf("Destroy %d at 0x%x\n", ID, this);
}
};
int main() e0
{
list<Element*> m_List; Item 0
Element *e0 = new Element(0);
Item 1
Element *e1 = new Element(1); e1
//add to list
m_List.push_back(e0); m_List.push_back(e1); list
//clear list
printf("-----Before clear-----\n");
m_List.clear();
printf("-----After clear-----\n");
return 0; 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);
//add to list Destroy 0 addr 0xb61a28
m_List.push_back(e0); Destroy 1 addr 0xb71a70
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 { class CA {
public: public:
CB(){ CA(){ B
m_iVal = 0; m_pB = 0;
} }
~CB(){} ~CA(){
int m_iVal; delete m_pB;
}; m_pB = 0; m_pB
} A
CB *m_pB;
};
int main()
{
CB *B = new CB; Access violation Try to
CA *A = new CA(); reading location remove
A->m_pB = B; . delete m_pB
delete(A);
printf("%d", B->m_iVal);

} 166
Example 7 (cont.)
Leak

class CB { class CA {
public: public:
CB(){ CA(){
m_iVal = 0; m_pB = 0;
Delete or not?
} }
~CB(){} ~CA(){
int m_iVal; delete m_pB;
}; m_pB = 0; m_pB
} A
CB *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() Memory leak caused by
{
public :
misunderstanding finalization
cA() {m_pdata = new int[100];} method
virtual ~cA() {delete[]
m_pdata;}
int *m_pdata;
}; Without virtual, in this case,
m_pdata is not deleted leak
class cB: public cA()
{
public
cB():cA() {m_pdata2 = new
int[100];}
~cB() {delete []m_pdata2;}
int *m_pdata2;
}
Solution
void main() Be careful with virtual for
{ finalization method
cA *A = new cB();
delete A;
}
168
C/C++ Example 9
class MyClass Using new vs free. No
{
public destructor will be invoked
MyClass() after free
{
m_pdata2 = new int[100];
}
~ MyClass()
{
delete []m_pdata2;
}
int *m_pdata2;
}

void main()
{
MyClass* p = new MyClass();
free(p); 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
{
Reference counter:
public: Simple method for
IShareMem():m_iRefCounter(1){}
virtual ~IShareMem(){}
memory conflict
static resolution
IShareMem* SetReference(IShareMem* src)
{
src->m_iRefCounter++;
return src; Algorithms:
}
void Release() Increase counter when
{ use as reference
m_iRefCounter--;
if (m_iRefCounter <= 0) Decrease when release
{
delete this;
Delete memory of
} counter is zero
}
private:
int m_iRefCounter;
}; 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

Alloc
A 0 E Which is really needed? Do I alloc some-
where without
Alloc release?
B 1

Alloc Somethings else


D 2
is pointed
to an object
..
Alloc
Z .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 Forward declaration

Standard IO Console IO & FILE


Getting Start
Template

Type casting
OOP
Exception handling

Memory management Endian

STL introduction
Rest of C/C++ features GNU GCC/G++ 184
Outline
Preparation Forward declaration

Standard IO Console IO & FILE

Getting Start Template

Type casting
OOP Exception handling

Endian
Memory management Bit processing

STL introduction
Rest of C/C++ features
GNU GCC/G++ 185
Forward declaration
Declaration of a identifier which not completed
definition
For C/C++, aka function prototype (for function)
int second(int x);
int first(int x) { int first(int x) {
if (x == 0) if (x == 0)
return 1; return 1;

return second(x-1); return second(x-1);


} }

int second(int x) { int second(int x) {


if (x == 0) if (x == 0)
return 0; return 0;

return first(x-1); return first(x-1);


} } 186
Forward declaration
ClassA.h ClassB.h
#ifndef _CLASSA_H_ #ifndef _CLASSB_H_
#define _CLASSA_H_ #define _CLASSB_H_
#include "ClassB.h" #include "ClassA.h"

class ClassB; class ClassA; Class forward declaration


class ClassA class ClassB
{ {
public: public:
ClassA(); ClassB(); Must be pointer
ClassB* m_pB; ClassA* m_pA;
}; };

#endif #endif
ClassA.cpp ClassB.cpp
#include "ClassA.h" #include "ClassB.h"
187
ClassA::ClassA(){} ClassB::ClassB(){}
Outline
Preparation Forward declaration

Standard IO Console IO & FILE

Getting Start Template

Type casting
OOP Exception handling

Endian
Memory management Bit processing

STL introduction
Rest of C/C++ features
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 ("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");

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

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

int fclose ( FILE * stream ); Close a file

size_t fwrite ( const void * ptr, size_t size, size_t count, Write block of data to stream
FILE * stream );
size_t fread ( void * ptr, size_t size, size_t count, FILE * Read a block data from stream
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

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 Forward declaration

Standard IO Console IO & FILE


Getting Start
Template

Type casting
OOP
Exception handling

Memory management Endian

STL introduction
Rest of C/C++ features 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 prefix
template <class T> T mypair<T>::getmax ()
{
T retval; Class prefix
retval = a>b? a : b;
return retval;
}
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
when a specific type is passed as template parameter
// class template: // class template specialization:
template <class T> template <>
class mycontainer class mycontainer <char>
{ {
T element; char element;
public: public:
mycontainer (T arg) mycontainer (char arg)
{ {
element=arg; element=arg;
} }
T increase () {return ++element;} 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 Forward declaration

Standard IO Console IO & FILE


Getting Start
Template

Type casting
OOP
Exception handling

Memory management Endian

STL introduction
Rest of C/C++ features 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; Implicit casting
float d = float(a);
Explicit casting
Functional notation

208
Numeric overflow

void main() c = -56 ?


{
int a = 200;
char c = a;
}

209
Float to int casting

i is equal
void main() to or ?
{
float f = 2.7;
int i = f;
}

210
Bool & bool casting
Bool have two values:
void main() b = true
True { c = false

False int i = 10;


bool b = i;
bool c = !i;
}
In C/C++:
False is zero
True is non-zero

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 Unrelated_class*, which are
inherently unsafe.

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 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<>
#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
pointer to a derived class
Class Derive1
pointer is called downcast.
downcast
Class Derive2
Type conversion from derived
class pointer to a base class
pointer, is called upcast.
Base
From a class to a sibling class in
Derive1 class hierarchy: crosscast

Derive2
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

CAN NOT cast directly from Derived3 to


Base base.

Do step by step:
Derived 1 Derived 2 Derived3 Derived2 Base
Or Derived3 Derived1 Base

Derived 3

222
dynamic_cast<>
downcast
Base Available for polymorphism
class only
Funct2()

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

class Derived1:public Base1 {


public:
virtual void funct2(){};
};
223
dynamic_cast<>
downcast (cont.)
Base
Test2
Funct2()
Test1
Derive
Funct3()

Base* Test1 = new Derived;


Base* Test2 = new Base; successful

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


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

224
dynamic_cast<>
crosscast
Crosscast Base2 Derived1

Base Base2

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

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

225
Outline
Preparation Forward declaration

Standard IO Console IO & FILE


Getting Start
Template

Type casting
OOP
Exception handling

Memory management Endian

STL introduction
Rest of C/C++ features 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 Throw exception


try throw type;
{
// code that may generate exceptions //type: user defined type or principle
} type
catch(type1 id1)
{
// handle exceptions of type1
}
Catch(...)
{
// catch any exception
}

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 Forward declaration

Standard IO Console IO & FILE


Getting Start
Template

Type casting
OOP
Exception handling

Memory management Endian

STL introduction
Rest of C/C++ features 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 0000.0000 0000.0000 0000.0100 0000.0001

Little endian 0000.0001 0000.0100 0000.0000 0000.0000

230
Endian - Example
int main() Command prompt
{
val = 0x33221100
char num[4] = {0x00,
0x11, Windows 32 bits
0x22,
0x33};
int *val = (int*)num;
printf("val = 0x%x", *val);
}
Important notes:
Avoid to save/load a short/int/long array. Use char (byte)
array instead.

231
Outline
Preparation Forward declaration

Standard IO Console IO & FILE


Getting Start
Template

Type casting
OOP
Exception handling

Memory management Endian

STL introduction
Rest of C/C++ features 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
#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 Command prompt
{
int ID;
Created 0 addr 0x22cce8
public: Created 1 addr 0x22cce4
Element(int id) -----Before clear-----
{ Destroy 0 addr 0xc91a38
printf("Created %d at 0x%x\n", id, this);
ID = id; Destroy 1 addr 0xc91a48
} -----After clear-----
~Element() Destroy 1 addr 0x22cce4
{
printf("Destroy %d at 0x%x\n", ID, this);
Destroy 0 addr 0x22cce8
}
};
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"); Copy of Elements are created
m_List.clear(); and stored in list
printf("-----After clear-----\n");
return 0;
} 236
STL and memory management
class Element Command prompt
{ Created 0 addr 0xa719c0
int ID;
public: Created 1 addr 0xa81a18
Element(int id) -----Before clear-----
{ -----After clear-----
printf("Created %d at 0x%x\n", id, this);
ID = id;
} Memory
~Element()
{ leak here
printf("Destroy %d at 0x%x\n", ID, this);
}
};
int main() e0
{
list<Element*> m_List; Item 0
Element *e0 = new Element(0);
Item 1
Element *e1 = new Element(1); e1
//add to list
m_List.push_back(e0); m_List.push_back(e1); list
//clear list
printf("-----Before clear-----\n");
m_List.clear();
printf("-----After clear-----\n");
return 0; 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);
//add to list Destroy 0 addr 0xb61a28
m_List.push_back(e0); Destroy 1 addr 0xb71a70
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 Forward declaration

Standard IO Console IO & FILE


Getting Start
Template

Type casting
OOP
Exception handling

Memory management Endian

STL introduction
Rest of C/C++ features 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 makefile
@echo off all: main.o MyClass1.o
cls g++ main.o MyClass1.o -o main.exe
SET CYGWIN=c:\cygwin\ main.o: main.cpp
SET CYGWIN_BIN=%CYGWIN%\bin g++ -c main.cpp
SET PATH=%PATH%;%CYGWIN%;%CYGWIN_BIN% MyClass1.o: MyClass1.cpp
g++ -c MyClass1.cpp
del *.o >nul
if exist main.exe (del main.exe)>nul MyClass1.h
%CYGWIN_BIN%\make #ifndef __MYCLASS_H__
if exist main.exe (call main.exe) #define __MYCLASS_H__
class MyClass
{
public:
MyClass();
};
main.cpp #endif
#include "MyClass1.h"
MyClass1.cpp
int main() #include <cstdio>
{ #include "MyClass1.h"
MyClass *c = new MyClass(); MyClass::MyClass()
return 1; {
} 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
{ To Ensure a class has
public:
ExpensiveRes() {}
only one instance, and
static ExpensiveRes* GetInstance(); provide a global point
private:
static ExpensiveRes* s_Instance; of access to it
};
ExpensiveRes* ExpensiveRes::s_Instance = 0;
ExpensiveRes* ExpensiveRes::GetInstance()
{
if (!s_Instance)
{
s_Instance = new ExpensiveRes();
}
return s_Instance;
}

int main()
{
ExpensiveRes::GetInstance();
} 244
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

Вам также может понравиться