Getting Started Cpp

882 views

Published on

Published in: Technology, Education
1 Comment
0 Likes
Statistics
Notes
  • Be the first to like this

No Downloads
Views
Total views
882
On SlideShare
0
From Embeds
0
Number of Embeds
8
Actions
Shares
0
Downloads
61
Comments
1
Likes
0
Embeds 0
No embeds

No notes for slide

Getting Started Cpp

  1. 1. Outline Preparation Getting Start OOP Memory management Rest of C/C++ features Appendix 2
  2. 2. Outline Preparation Getting Start OOP Memory management Rest of C/C++ features Appendix Hello world C/C++ files Entry point C/C++ libraries Source compile process 3
  3. 3. Outline Preparation Getting Start Variables and constant Primary data type OOP Array – Pointer – String Memory management Data structure: enum – union - struct Rest of C/C++ features Appendix Function Namespace 4
  4. 4. Outline Preparation Getting Start OOP Memory management Rest of C/C++ features Appendix Class & Object Inheritance Polymorphism Operator overloading Class’ static member 5
  5. 5. Outline Preparation Getting Start Recall pointer Memory leak OOP Memory management Rest of C/C++ features Appendix 6
  6. 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
  7. 7. Outline Preparation Getting Start OOP Memory management Rest of C/C++ features Hello world! C/C++ files Entry point C/C++ libraries Source compile process 8
  8. 8. Outline Preparation Getting Start Basic Data Structure OOP Memory management Rest of C/C++ features Hello world! C/C++ files Entry point C/C++ libraries Source compile process 9
  9. 9. Hello world using VS 10
  10. 10. Hello world main.cpp # include <stdio.h> void main() { printf("Hello world"); } Use standard IO lib Entry point Print to console screen 11
  11. 11. Outline Preparation Getting Start OOP Memory management Rest of C/C++ features Hello world! C/C++ files Entry point C/C++ libraries Source compile process 12
  12. 12. C/C++ source files #include "stdio.h" void Todo1(); void Todo2(); Header file (.h)  aka include file  Hold declarations for other files use (prototype)  Not required # include "header.h" void Todo1() { Todo2(); } void Todo2(){} void main() { Todo1(); } Source file (.c / .cpp)  Content implementation  Required 13
  13. 13. Outline Preparation Getting Start OOP Memory management Rest of C/C++ features Hello world! C/C++ files Entry point C/C++ libraries Source compile process 14
  14. 14. Entry point Form1.cpp void main() { // your code here } Required unique entry point The most common is: main Form2.cpp int main(int n, char ** args) { // your code here } Error when no entry point is defined 1>LINK : fatal error LNK1561: entry point must be defined 15
  15. 15. Outline Preparation Getting Start OOP Memory management Rest of C/C++ features Hello world! C/C++ files Entry point C/C++ libraries Source compile process 16
  16. 16. C/C++ standard library C/C++ support a set of internal basic library, such as • • • • Basic IO Math Memory handle … #include "stdio.h" void main() { printf("hello"); } For using, include the header file #include <…> #include "…" 17
  17. 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
  18. 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
  19. 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
  20. 20. Import user-defined library Visual studio Declare path to .lib 21
  21. 21. Import user-defined library Visual studio Declare .lib file 22
  22. 22. Outline Preparation Getting Start OOP Memory management Rest of C/C++ features C/C++ files Entry point C/C++ libraries Hello world! Source compile process 23
  23. 23. Process Source .h/.c/.cpp preprocess Preprocessed source Compile Tools: • Visual Studio: cl.exe (Press F7 / F5) • GNU GCC: gcc/ g++ Executable/ lib Linker .o / .obj (object file) 24
  24. 24. Outline Preparation Getting Start Variables and constant Primary data type Array – Pointer - String OOP Data structure: enum – union - struct Memory management Rest of C/C++ features Function Namespace 25
  25. 25. Outline Preparation Getting Start Variables and constant Primary data type Array – Pointer - String OOP Data structure: enum – union - struct Memory management Rest of C/C++ features Function Namespace 26
  26. 26. Variable classification Scope: • Local variable • Global variable • Static variable Storage class specifier • auto • static • register • extern 27
  27. 27. Global & local int mGlobalVar; void Foo() { int localVar; printf("Foo : %d %dn", localVar, mGlobalVar); } int main() { int localVar = 1; printf("Main: %d %dn", 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
  28. 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
  29. 29. Static variable #include <cstdio> static int s_iGlobalStatic; void Foo() { static int s_iLocalStatic; printf("Foo: called %dn", s_iLocalStatic++); } int main() { int localVar = 1; printf("Main: %dn", 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
  30. 30. Register variable int main() { int sum = 0; for (register int i = 0; i < 100; i++) { sum += i; } printf("Sum = %dn", sum);  Stored in a machine register if possible  Usually used in “for iterator” for improve performance return 1; } 31
  31. 31. Extern variable Extern.cpp int m_iExternVar = 100;  Specify that the variable is declared in a different file. main.cpp #include <cstdio>  Compiler will not allocate extern int m_iExternVar;  Avoid duplicate declaration int main() { printf("Value = %dn", m_iExternVar);  Share (global) variable for return 1; } memory for the variable multiple .cpp files Command prompt Value = 100 32
  32. 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
  33. 33. Outline Preparation Getting Start Variables and constant Primary data type Array – Pointer - String OOP Data structure: enum – union - struct Memory management Rest of C/C++ features Function Namespace 34
  34. 34. Primitive data type (32bits processor) Type Size Range void n/a char 1 byte unsigned char: -128 … 127 signed char: 0…255 short 2 bytes unsigned short: 0 … (216 -1) signed short: -215 … (215 – 1) int 4 bytes -231 … (231 – 1) unsigned int: 0 … (232 -1) signed int: -231 … (231 – 1) long 4 bytes -231 … (231 – 1) unsigned long: 0 … (232 -1) signed long: -231 … (231 – 1) long long 8 bytes -263 … (263 – 1) unsigned long long: 0 … (264 -1) signed long long: -263 … (263 – 1) bool 1 byte True /false (non-zero / zero) float 4 bytes double 8 bytes 35
  35. 35. New type definition Use typedef typedef int Mytype; typedef int MyArr[5]; Mytype var1; MyArr arr; 36
  36. 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
  37. 37. Outline Preparation Getting Start Variables and constant Primary data type Array – Pointer - String OOP Data structure: enum – union - struct Memory management Rest of C/C++ features Function Namespace 38
  38. 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("%dn", b[i]); } printf("%dn", b[10]); b[10] = ? 39
  39. 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
  40. 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
  41. 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 0x01 0x02 o i = 1 o &i = 0x01 0x00 i 0x01 0x03 0x04 0x05 0x06 0x07 0x08 & operator: get address of a variable 42
  42. 42. Pointer (cont.) For storing address of a variable, use a special type: pointer int *pi; char *pc; Pointer of a integer variable 0x10 0x00 0xF1 0xF2 &i 0x00 i Pointer of a char variable Pointer of a float variable int *pi = &i; 0x00 0xF3 0xF4 0xF5 float *pf; 0xF6 0xF7 0xF8 int* pi; pi = &i; 43
  43. 43. Pointer (cont.) Pointer is also a variable  it’s stored in memory 0x2f00002c i = 10 0x2f00aabb p = 0x2f00002c int i = 10; int *p = &i; p = 0x2f00002c &p = 0x2f00aabb *p = 10 *p : get value at address pointed by p 44
  44. 44. Pointer (cont.) Type of pointer notify that how to get the value pointed by pointer 0x01 0xcc 0xF1 0xF2 P1 P2 0x20 i 0x3f 0xF3 0xF4 0xF5 0xF6 0xF7 0xF8 Little Endian int i = 0x3f20cc01; char *p1 = (char *)&i; short *p2 = (short *)&i; int *p3 = &i; 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
  45. 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
  46. 46. Pointer pointer operator Operat or desc Example + move forward n steps p += 10; - move backward n step p -= 1; • Short: 2 byte ++ move forward 1 step p++; • …. -- move backward 1 step p--; 0x01 0x01 p1 0xcc 0x02 0x3f 0x00 0x10 0xaa 0x03 0x04 0x05 0x06 0x07 0x20 p1+1 char *p1; p1+5  Note: each step is a distance k bytes belongs to type of pointer: • byte: 1 byte 0x01 0xcc 0x01 0x02 p2 0x20 (p1+1) (p2 + 1) *(p1+1) *(p2+1) &(p1+1) &(p2+1) 0x3f 0x00 0x03 0x04 0x05 p2+1 short *p2; 0x10 0xaa 0x06 0x07 p2+3 47
  47. 47. 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
  48. 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; *p1 == ? *p2 == ? *(*p2) == ? 0x100 iVar = 10 0x200 p1 = 0x100 0x300 p2 = 0x200 49
  49. 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 “p” after deleting?  Dynamic allocation • User pointer • Allocation a block of memory in heap  high capacity • Clean up easily int *p = new int[n]; Alloc n-int elements in heap delete p; Free memory block pointed by p nx4 bytes p p 50
  50. 50. Pointer Dynamic allocation (cont.) There two way for dynamic allocation Old C style C++ style • Using stdlib.h • Using malloc/free • Using new/delete • Using new[] / delete[] int main() { char *i = (char*) malloc (100); int main() { char *i = new char[100]; // some code here // some code here free(i); } delete []i; } 51
  51. 51. Pointer Dynamic allocation (cont.)  Use delete for new,  Use delete[] for new[] struct A { public: static int count; int val; A() { printf("Created %dn", val = count++);} ~A() { printf("Deleted %dn", 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
  52. 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
  53. 53. Pointer vs. Array In common, pointer could be used like array *p = *(p+0) = p[0] *(p + n) = p[n] stack 0x2f0A0000 int main() { int *p = new int [3]; p[0] = 1; *(p + 1) = 12; p[2] = 5 } P = 0x2f330000 heap 1 12 0x2f330000 5 0x2f330008 0x2f330004 54
  54. 54. Pointer vs. Array int main() { char a[3] = {1, 2, 3, 4}; printf ("0x%x 0x%x %dn", a, &a, *a); int *p = new int[3]; p[0] = 1; p[1] = 2; p[2] = 3; printf ("0x%x 0x%x %dn", p, &p, *p); Array is a pointer pointed to itself A pointer can point to an array addr. int *p2 = (int*)a; printf("value of p2 = 0x%xn", *p2); } Command prompt 0x14fd64 0x14fd64 1 0x591398 0x14fd60 1 Value of p2 = 0x04030201 55
  55. 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%xn", 0x%xn", 0x%xn", 0x%xn", a, p); a+1, p+1); &a, &p); &a+1, &p+1); &a + 1 Command prompt a = a+1 = &a = &a+1= 0x26FE6C 0x26FE6D 0x26FE6C 0x26FE6F p p+1 &p &p+1 = = = = 0x0E1AF0 0x0E1AF1 0x26FE70 0x26FE74 0x0E1AF0 0x0E1AF1 0x0E1AF2 0x0E1AF3 0x0E1AF4 10 20 30 0x26FE6C 0x26FE6D 0x26FE6E 0x26FE6F 1 a 0x26FE70 0x26FE71 0x26FE72 0x26FE73 0x26FE74 &p + 1 2 3 p+1 a+1 p 56
  56. 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]; } 0 Can not delete an array int main() { char arr[100]; delete arr; } FAIL int main() { char *p = new char[1034996]; delete p; } OK OK Memory block of array is freed automatically when out-of- scope Dynamic memory MUST be clean manually by call “delete” 57
  57. 57. Pointer vs. Array 2D array int arr[2][3] [0][0] pointer-to-pointer int **p = new int*[2]; p[0] = new int[3]; p[1] = new int[3]; [0][1] [0][2] [1][0] Block 0 [1][1] [1][2] Block 1 p [0][0] [0][1] [0][2] [1][0] [1][1] p[0] p[0][0] p[0][1] p[0][2] p[1][0] p[1][1] p[1][2] p[1] [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
  58. 58. C/C++ String 59
  59. 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
  60. 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
  61. 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
  62. 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
  63. 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
  64. 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
  65. 65. Outline Preparation Getting Start Variables and constant Primary data type Array – Pointer - String OOP Data structure: enum – union - struct Memory management Rest of C/C++ features Function Namespace 66
  66. 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
  67. 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
  68. 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 0x02 0x01 0x01020304 iValue cValue int main() { MyUnion mine = {0x01020304}; printf("iValue: 0x%xn", mine.iValue); printf("iValue: 0x%xn", mine.cValue); printf("iValue: 0x%x 0x%x 0x%x 0x%xn", mine.aValue[0], mine.aValue[1], mine.aValue[2], mine.aValue[3]); } 0x03 0x04 aValue 0x04 0x03 0x02 0x01 sizeof(mine) = ? 69
  69. 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
  70. 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
  71. 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
  72. 72. Data Structure alignment struct T_MyStruct { char val1; short val2; int val3; char val4; }; 0 Before compile, total memory of T_MyStruct is 8 byte val2 val1 1 0 val3 val4 3 7 4 bytes alignment • char: 1 byte aligned • short: 2 byte aligned • int : 4 byte aligned • … val1 0 pad 1 1 val2 2 4 bytes block val3 3 4 val4 8 4 bytes block sizeof(T_MyStruct) == 12 bytes pad2 9 10 11 4 bytes block 73
  73. 73. VS Struct member alignment 74
  74. 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
  75. 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
  76. 76. Struct constructor / destructor typedef struct T_MyStruct { int val1; constructor T_MyStruct(); ~T_MyStruct(); }MyStruct; destructor T_MyStruct::T_MyStruct() { printf("Createdn"); } T_MyStruct::~T_MyStruct() { printf("Destroyn"); } int main() { MyStruct myStruct; }  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 77
  77. 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
  78. 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
  79. 79. Outline Preparation Getting Start Variables and constant Primary data type Array – Pointer - String OOP Data structure: enum – union - struct Memory management Rest of C/C++ features Function Namespace 80
  80. 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
  81. 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 %dn", 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
  82. 82. Default parameters (cont.) void foo(int a, int b = 1, int c ) { printf("%d %d %dn", 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
  83. 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("%dn", sum(1, 10)); printf("%dn", sum(3, 1, 2, 3)); } 84
  84. 84. Parameter classification Value parameter Reference parameter Constant parameter Const Reference parameter Pointer parameter 85
  85. 85. Parameter classification Value parameter Reference parameter Constant parameter Const Reference parameter Pointer parameter Pass-by-value A copy of parameter is made void foo(int n) { n++; } void main() { int x = 2; foo(x); printf("%dn", x); } x 2 x=2 x 2 x 2 n 2 n 3 foo x 2 86
  86. 86. Parameter classification Value parameter Reference parameter Constant parameter Const Reference parameter Pointer 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("%dn", x); } x 2 x n x=3 x 2 n foo 3 x 3 87
  87. 87. Parameter classification Value parameter  Pass-by-value  A copy of parameter is made and strict as const. Reference parameter Constant parameter Const Reference parameter void foo(int cont n) { n++; Fail, can not } modified void main() { const value int x = 2; foo(x); printf("%dn", x); } x Pointer parameter 2 x 2 x 2 n 2 n 3 foo 88
  88. 88. Parameter classification Value parameter Reference parameter Constant parameter Const Reference parameter  Pass-by-ref  Actually parameter itself is passed but avoid modify  Void the overhead of creating a copy void foo(int const &n) { //todo } Pointer parameter 89
  89. 89. Parameter classification Value parameter Reference parameter Constant parameter Const Reference parameter Pointer 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 } Value of parameter will not be change, but memory block which pointed by parameter could be modified. 90
  90. 90. Pointer Parameter #include <cstdio> void foo(int *A, int *B) { int *tmp = A; A = B; B = tmp; } Copy value (addr. of data) foo A B A’ B’ A’ void main() { int A[] = {1, 2, 3}; int B[] = {10, 11}; printf("0x%x 0x%xn", A, B); foo(A, B); printf("0x%x 0x%xn", A, B); } B’ A B Command prompt 0x29faa8 0x29faa0 0x29faa8 0x29faa0 91
  91. 91. Pointer Parameter A[2] = 3 #include <cstdio> void foo(int *A) { A[2] = 10; } void main() { int A[] = {1, 2, 3}; printf(“%dn", A[2]); foo(A); printf(“%dn", A[2]); } A Copy value (addr. of data) foo A’ A’[2] = 10 1 2 3 10 A A[2] = 10 92
  92. 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%xn", A, B); foo(A, B); printf("0x%x 0x%xn", A, B); } foo A B A B A B Command prompt 0x31fc90 0x31fc88 0x31fc88 0x31fc90 93
  93. 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
  94. 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
  95. 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("TodoExternn"); } Main.cpp #include <cstdio> extern void TodoExtern(); int main() { TodoExtern(); return 1; } 96
  96. 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
  97. 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("ExternCn"); } C_plusplus.cpp extern "C" { void ExternC(); void Todo() { printf("%d", i); } } 98
  98. 98. Extern “C” in practice #ifdef __cplusplus extern "C" { #endif // your code here #ifdef __cplusplus } #endif __cplusplus: default C++ preprocessor definition 99
  99. 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
  100. 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
  101. 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
  102. 102. Outline Preparation Getting Start Variables and constant Primary data type Array – Pointer - String OOP Data structure: enum – union - struct Memory management Rest of C/C++ features Function Namespace 103
  103. 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
  104. 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
  105. 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
  106. 106. Namespace – ambiguous call namespace maths { void add(); } namespace matrix { void add(); } using namespace maths; using namespace matrix; void main() { add(); } 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
  107. 107. Outline Preparation Getting Start OOP Memory management Rest of C/C++ features Class & Object Inheritance Polymorphism Operator overloading Class’ static member 108
  108. 108. Outline Preparation Getting Start OOP Memory management Rest of C/C++ features Class & Object Inheritance Polymorphism Operator overloading Class’ static member 109
  109. 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
  110. 110. 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
  111. 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
  112. 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
  113. 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); Default constructor Copy constructor. MyClass(int val); } 114
  114. 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
  115. 115. Copy constructor (cont.) class ABC { public: ABC(){} ABC(ABC *A){printf("here1n");} ABC(const ABC &A) { printf("here2n"); } }; 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
  116. 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
  117. 117. Explicit constructor class A { public: explicit A(int) {} }; void f(A) {} void g() { A a1 = 37; Without explicit With explicit A a2 = A(47); a1 = 67; f(77); }  "nonconverting"  Explicit constructor syntax is required. 118
  118. 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: • Out of scope • Or manually free (use pointer)  Use for collect class memory Command prompt ---Alloc A-----Free A--Destroyed A ---Create B-----End--Destroyed B 119
  119. 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
  120. 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
  121. 121. Outline Preparation Getting Start OOP Memory management Rest of C/C++ features Class & Object Inheritance Polymorphism Operator overloading Class’ static member 122
  122. 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 class Derive: public Base { }; Base class Hierarchy model Derive class 123
  123. 123. 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(); FAIL: cannot access private member this->privateFunc(); Access base’s method (same name) Base::Todo(); } 124
  124. 124. Inheritance access Base access Inherit access Public Protected Derive access Public Public Protected Private Private Public Protected Protected Protected Private Private Public Protected Private private Private 125
  125. 125. Inheritance access Example class CAnimal { public: void Drink(); protected: void Run(); private: void Eat(); }; class CRabbit: private CAnimal { public: CRabbit() { Run(); Eat(); Drink(); } }; void main() { CRabbit rab; rab.Drink(); rab.Eat(); rab.Run(); } Why? 126
  126. 126. Constructor – Destructor – Inheritance Lion *theLion = new Lion() Animal() Animal ~Animal() Mammal() Mammal ~Mammal() Lion() Lion ~Lion() delete theLion; 127
  127. 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
  128. 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
  129. 129. Outline Preparation Getting Start OOP Memory management Rest of C/C++ features Class & Object Inheritance Polymorphism Operator overloading Class’ static member 130
  130. 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
  131. 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
  132. 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); Overriding: override a base’s virtual or nonvirtual methods Overloading: several methods with the same name which differ from parameters }; 133
  133. 133. 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
  134. 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 It’s ok for obj1, but problem for obj2 Command prompt --Free obj1-Destroy Derive Destroy Base --Free obj2-Destroy Base 135
  135. 135. class Base { public: virtual ~Base() { Virtual destructor (cont) 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; } To solve this problem, use virtual destructor Command prompt --Free obj1-Destroy Derive Destroy Base --Free obj2— Destroy Derive Destroy Base 136
  136. 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
  137. 137. Outline Preparation Getting Start OOP Memory management Rest of C/C++ features Class & Object Inheritance Polymorphism Operator overloading Class’ static member 138
  138. 138. Operator overloading Another way to make a function call Define function of operator such as : +, -, *, /, … WARNING: Not recommend to use. It’s easy to read, but hard to debug ! 139
  139. 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; This implementation make user confused return *this; } }; int main() { Integer ii(1), jj(2), kk(3); kk += ii + jj; cout << "Value = " << kk.i << endl; } 140
  140. 140. Outline Preparation Getting Start OOP Memory management Rest of C/C++ features Class & Object Inheritance Polymorphism Operator overloading Class’ static member 141
  141. 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
  142. 142. Static variable class MyClass { public: static int s_Var; }; int MyClass::s_Var = 99; Same as static function Value of static variable MUST BE set outside class declaration. int main() { printf("%d", MyClass::s_Var); } 143
  143. 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
  144. 144. Outline Preparation Getting Start Recall pointer Memory leak OOP Memory management Rest of C/C++ features 145
  145. 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
  146. 146. What does “memory leak” mean ? First, How is memory structure ? 147
  147. 147. How is memory structure ? STACK vs HEAP 148
  148. 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
  149. 149. Stack Parameters Return Address Text segment (Code segment) Global area where to begin execution when function exits Dynamic link Stack frame pointer to caller's stack frame Static link pointer to lexical parent (for nested functions) Return value Local variables “Concept” Stack frame Stack frame Where parameters and local variables are allocated Limited size  Stack overflow Memory use in stack is temporary and auto release Fast processing/low size Heap Segment 150
  150. 150. Heap Parameters Return Address Text segment (Code segment) Global area where to begin execution when function exits Dynamic link Stack frame pointer to caller's stack frame Static link pointer to lexical parent (for nested functions) Return value Local variables “Concept” Stack frame Stack frame Heap Segment Large pool of memory Dynamic allocation Stays allocated until specifically deallocated  leak ! Must be accessed through a pointer Large arrays, structures, or classes should be stored Heap  why? Large & dynamic 151
  151. 151. Heap vs Stack int _array[10];  stored in stack int *_array = new int[n] Stack _array • Pointer _array is stored in Stack • Data of array is stored in Heap Heap Stack 0x00FF 0x0005 _array 10 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) 0x00FF 152
  152. 152. FAQ Why we use • Classname *Obj = new Classname(); instead of • Classname Obj; 153
  153. 153. Memory leak overview 154
  154. 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
  155. 155. What does its consequences ? Application gets slow fps Application is crashed Device has been freeze, restarted 156
  156. 156. Why does “memory leak” happen? First, Let's see some examples 157
  157. 157. Example 0  Forget to release resources – No GC mechanic supported Button is pressed Save current floor Leaking here Finished On target floor ? Memory True Wait until lift is idle Go to required floor Release memory used to save current floor 158
  158. 158. C/C++ Example 1 ● Leak ! Leak memory caused by lacking of release dynamic memory Solution … delete a[]; return; 159
  159. 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
  160. 160. C/C++ Example 3 char* GenString() { char *a = new char[10]; a[9] = '0'; return a; } void Leak() { char *str = GenString(); printf("%sn", str); printf("%sn", GenString()); } Leak memory when using pointer-returntype Solution delete []str; Avoid to call directly GenString() 161
  161. 161. C/C++ Example 4 Leak memory when using pointer as a parameter Stack Heap Leak! A LEAK! Solution  Well control with reference variables  Check if a pointer is allocated memory yet! 162
  162. 162. C/C++ Example 5 Misunderstand free memory method in C/C++ void main() { Stack Classname *A = new A(); 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;}}
  163. 163. Example 6 class CB { public: CB(){ m_iVal = 0; } ~CB(){} int m_iVal; }; class CA { public: CA(){ m_pB = 0; } ~CA(){ delete m_pB; m_pB = 0; } CB *m_pB; }; int main() { CB *B = new CB; CA *A = new CA(); A->m_pB = B; delete(A); printf("%d", B->m_iVal); } B m_pB A Access violation reading location …. Try to remove delete m_pB 164
  164. 164. Example 6 (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 A int main() { CA *A = new CA(); A->m_pB = new CB() delete(A); } Solution Use manual delocate m_pB 165
  165. 165. C/C++ Example 7 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 166
  166. 166. What are reasons of memory leak? Forget/ misunderstand C/C++ mechanism Out-of-Control (logic) 167
  167. 167. 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++ 168
  168. 168. Current Solutions Disadvantage Garbage collectors generally can do nothing about logical memory leaks A B D Z Alloc Alloc Alloc Alloc 0 1 2 .. .n E Which is really needed? Do I alloc somewhere without release? Somethings else is pointed to an object 169
  169. 169. C/C++ How to avoid, detect? Rule: • Remember to release dynamic data (pointer) • Keep our resource in well controlled Detect • By phenomenon on device ? not exactly • By review source ? too hard • By tool Too hard o VC++ memory leak debugging o External tool 170
  170. 170. C/C++ How to solve? Depend on kind of memory leak Experience: Improve C/C++ skill Organize source and keep it in control • Such as a document about resource ?!? 171
  171. 171. Detect Memory Leak 172
  172. 172. Debug in Visual studio 173
  173. 173. VLD Tool 0 http://www.codeproject.com/KB/applications/visualleakdetector.aspx 174
  174. 174. Outline Preparation Forward declaration Standard IO – Console IO & FILE Getting Start OOP Template Type casting Exception handling Memory management Endian STL introduction Rest of C/C++ features GNU GCC/G++ 175
  175. 175. Outline Preparation Forward declaration Standard IO – Console IO & FILE Getting Start Template Type casting OOP Exception handling Endian Memory management Rest of C/C++ features Bit processing STL introduction GNU GCC/G++ 176
  176. 176. 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; int second(int x); int first(int x) { if (x == 0) return 1; return second(x-1); return second(x-1); } } int second(int x) { if (x == 0) return 0; int second(int x) { if (x == 0) return 0; return first(x-1); } return first(x-1); } 177
  177. 177. Forward declaration ClassA.h ClassB.h #ifndef _CLASSA_H_ #define _CLASSA_H_ #ifndef _CLASSB_H_ #define _CLASSB_H_ #include "ClassB.h" #include "ClassA.h" class ClassB; class ClassA; Class forward declaration class ClassA { public: ClassA(); ClassB* m_pB; }; class ClassB { public: ClassB(); ClassA* m_pA; }; Must be pointer #endif #endif ClassA.cpp ClassB.cpp #include "ClassA.h" ClassA::ClassA(){} #include "ClassB.h" ClassB::ClassB(){} 178
  178. 178. Outline Preparation Forward declaration Standard IO – Console IO & FILE Getting Start Template Type casting OOP Exception handling Endian Memory management Rest of C/C++ features Bit processing STL introduction GNU GCC/G++ 179
  179. 179. 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 %ldn", 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"); 180
  180. 180. 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); 181
  181. 181. 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:tt" << (float) 5/8 << endl; "And a very very big number:t" << (double) 7000 * 7000 << endl; "I am a C++ programmer!n"; 182
  182. 182. 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"; 183
  183. 183. 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, FILE * stream ); Write block of data to stream size_t fread ( void * ptr, size_t size, size_t count, FILE * stream ); Read a block data from stream int fscanf ( FILE * stream, const char * format, ... ); Read formatted data from stream int fprintf ( FILE * stream, const char * format, ... ); Write formatted output to stream int fseek ( FILE * stream, long int offset, int origin ); Reposition stream position indicator Origin: • SEEK_SET : beginning of gfile • SEEK_END: end of file • SEEK_CUR: current position long int ftell ( FILE * stream ); Get current position in stream void rewind ( FILE * stream ); Set position indicator to the beginning 184
  184. 184. 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; } 185
  185. 185. Outline Preparation Forward declaration Standard IO – Console IO & FILE Getting Start OOP Template Type casting Exception handling Memory management Endian STL introduction Rest of C/C++ features GNU GCC/G++ 186
  186. 186. 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; 187
  187. 187. 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; } 188
  188. 188. 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; } 189
  189. 189. 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'); } 190
  190. 190. 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; } Template prefix mypair<T>::getmax () int main () { mypair <int> myobject (100, 75); cout << myobject.getmax(); return 0; } Class prefix Return type 191
  191. 191. Class template. Template specialization Define a different implementation for a template when a specific type is passed as template parameter // class template: template <class T> class mycontainer { T element; public: mycontainer (T arg) { element=arg; } T increase () {return ++element;} }; // class template specialization: template <> class mycontainer <char> { char element; public: mycontainer (char arg) { element=arg; } char uppercase () { if ((element>='a')&&(element<='z')) element+='A'-'a'; return element; } 192 };
  192. 192. 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 193
  193. 193. Mixin We can implement inheritance delaying the definition of the base. template <class Base> class Mixin : public Base {}; class Base {}; 194
  194. 194. 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! 195
  195. 195. 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 196
  196. 196. 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; } 197
  197. 197. Outline Preparation Forward declaration Standard IO – Console IO & FILE Getting Start OOP Template Type casting Exception handling Memory management Endian STL introduction Rest of C/C++ features GNU GCC/G++ 198
  198. 198. 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 199
  199. 199. Numeric overflow void main() { int a = 200; char c = a; } c = -56 ? 200
  200. 200. Float to int casting void main() { float f = 2.7; int i = f; } i is equal to or ? 201
  201. 201. 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 202
  202. 202. C++ type casting Beside basic implicit and explicit type casting, C++ also supported: • dynamic_cast<> • static_cast<> • const_cast<> • reinterpret_cast<> 203
  203. 203. 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); } 204
  204. 204. 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 205
  205. 205. 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; } 206
  206. 206. 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 207
  207. 207. 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 . . . 208
  208. 208. dynamic_cast<> Enable Run-Time Type Info first 209
  209. 209. 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 210
  210. 210. dynamic_cast<> Class Base upcast Class Derive1 downcast Class Derive2  Type conversion from base class pointer to a derived class pointer is called downcast.  Type conversion from derived class pointer to a base class pointer, is called upcast. Base Derive1  From a class to a sibling class in class hierarchy: crosscast Derive2 211
  211. 211. dynamic_cast<> upcast Always successful Why? Base Derive1 Derive2 Derive class always “contents” valid complete base class 212
  212. 212. dynamic_cast<> upcast – multiple conversion with multiple inheritace  CAN NOT cast directly from Derived3 to base. Base Derived 1 Derived 2  Do step by step: • Derived3  Derived2  Base • Or Derived3  Derived1  Base Derived 3 213
  213. 213. dynamic_cast<> downcast Available for polymorphism Base Funct2() Derive Funct3() class only class Base1 { public: virtual void funct1(){}; }; class Derived1:public Base1 { public: virtual void funct2(){}; }; 214
  214. 214. dynamic_cast<> downcast (cont.) Base Funct2() Test2 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); 215
  215. 215. dynamic_cast<> crosscast Crosscast Base2  Derived1 Base Derived 1 Base2 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); 216
  216. 216. Outline Preparation Forward declaration Standard IO – Console IO & FILE Getting Start OOP Template Type casting Exception handling Memory management Endian STL introduction Rest of C/C++ features GNU GCC/G++ 217
  217. 217. 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 } catch(type1 id1) { // handle exceptions of type1 } Catch(...) { // catch any exception } //type: user defined type or principle type 218
  218. 218. 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"); } } 219
  219. 219. Outline Preparation Forward declaration Standard IO – Console IO & FILE Getting Start OOP Template Type casting Exception handling Memory management Endian STL introduction Rest of C/C++ features GNU GCC/G++ 220
  220. 220. 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 221
  221. 221. 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. 222
  222. 222. Outline Preparation Forward declaration Standard IO – Console IO & FILE Getting Start OOP Template Type casting Exception handling Memory management Endian STL introduction Rest of C/C++ features GNU GCC/G++ 223
  223. 223. STL  Standard template library  Powerful library for container and algorithms  Some basic types: • • • • Vector Deque List ….  Some basic methods • • • • • • push pop insert copy erase … 224
  224. 224. 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 225
  225. 225. 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("%dn", *i); } return 0; } 226
  226. 226. STL and memory management class Element { int ID; public: Element(int id) { printf("Created %d at 0x%xn", id, this); ID = id; } ~Element() { printf("Destroy %d at 0x%xn", 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 227
  227. 227. STL and memory management class Element { int ID; public: Element(int id) { printf("Created %d at 0x%xn", id, this); ID = id; } ~Element() { printf("Destroy %d at 0x%xn", 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 e1 list 228
  228. 228. 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; } 229
  229. 229. Outline Preparation Forward declaration Standard IO – Console IO & FILE Getting Start OOP Template Type casting Exception handling Memory management Endian STL introduction Rest of C/C++ features GNU GCC/G++ 230
  230. 230. 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 231
  231. 231. 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) main.cpp #include "MyClass1.h" int main() { MyClass *c = new MyClass(); return 1; } 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 MyClass1.cpp #include <cstdio> #include "MyClass1.h" MyClass::MyClass() { printf("Hellon"); } 232
  232. 232. 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 234
  233. 233. 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; } int main() { ExpensiveRes::GetInstance(); } To Ensure a class has only one instance, and provide a global point of access to it 235
  234. 234. 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 236

×