+ All Categories
Home > Technology > Getting started cpp full

Getting started cpp full

Date post: 16-Apr-2017
Category:
Upload: vo-hoa
View: 87 times
Download: 1 times
Share this document with a friend
245
Getting Started C/C+ +
Transcript

Starting C/C++

Getting Started C/C++

OutlineC/C++

2

Outline3

Outline4

New type definitionPass-by-value vs. pass-by-referenceSize of

4

Outline5

Abstract/virtual/pure virtualInstant Object

5

Outline

6

What?Why?When?How?6

Outline7

Container and iteratorlistSTL with pointer7

Outline8

Outline9

Hello world using VS

Step 1: create new projectStep 1: create new project (cont)Step 2: add new fileStep 2.1: add cpp file10

Hello world# include

void main(){ printf("Hello world");}main.cppUse standard IO libEntry pointPrint to console screen

11

Outline12

C/C++ source filesHeader file (.h)aka include fileHold declarations for other files use (prototype)Not required#include "stdio.h"

void Todo1();void Todo2();

# include "header.h"void Todo1(){ Todo2();}void Todo2(){}void main(){ Todo1();}.h file.cpp fileSource file (.c / .cpp)Content implementationRequired13

Outline14

Entry pointRequired unique entry pointThe most common is: mainvoid main(){ // your code here}Form1.cppint main(int n, char ** args){ // your code here}Form2.cpp1>LINK : fatal error LNK1561: entry point must be definedError when no entry point is defined 15

Outline16

C/C++ standard libraryC/C++ support a set of internal basic library, such asBasic IOMathMemory handleFor using, include the header file#include #include ""#include "stdio.h"

void main(){ printf("hello");}17

C headerC++ headerContent assert macro, for debuggingFor character classification/convert functionsFor testing error numberFloating point macrosDefine range of value of common typeMathematical functionsProvide non-local jumps for flow controlControlling various exceptional conditionsStandard libStandard IOManipulating several kinds of stringConverting between time & date formats

18

C/C++ user-defined libNot C/C++ standard libCome from:Third-partyUser ownIn common, include 2 parts.h files & .lib files: for developer.dll file (dynamic library): for end-usererror LNK2019: unresolved external symbolError caused when forget to add .lib file19

C/C++ user-defined lib (cont.)For usingInclude .h filesInform .lib files to compiler

Copy all .dll file to (if any) :same folder with execute file, or to system32 (windows) not recommend20

Declare path to .lib Import user-defined libraryVisual studio21

Import user-defined libraryVisual studio

Declare .lib file22

Outline23

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

Outline25

25

Outline26

26

Variable classificationScope:Local variableGlobal variableStatic variableStorage class specifierautostaticregisterextern27

Global & localint mGlobalVar;

void Foo(){ int localVar; printf("Foo : %d %d\n", localVar, mGlobalVar);}

int main(){ int localVar = 1; printf("Main: %d %d\n", localVar, mGlobalVar); mGlobalVar = 1; Foo(); return 1;}Global variable

Available in all of programSet default value to zeroLocal variableNO default valueAvailable inside blockMain: 1 0Foo : 2280752 1Command prompt28

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 block29

Static variableAllocated when the program starts and is deallocated when the program ends.

Default value is zero (0)#include

static int s_iGlobalStatic;

void Foo(){ static int s_iLocalStatic; printf("Foo: called %d\n",s_iLocalStatic++);}

int main(){ int localVar = 1; printf("Main: %d\n", s_iGlobalStatic); Foo(); Foo(); Foo(); return 1;}

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

Register variableStored in a machine register if possibleUsually used in for iterator for improve performanceint main(){ int sum = 0; for (register int i = 0; i < 100; i++) { sum += i; } printf("Sum = %d\n", sum); return 1;}31

Extern variableSpecify that the variable is declared in a different file.

Compilerwill not allocate memory for the variable

Avoid duplicate declaration

Share (global) variable for multiple .cpp files

#include

extern int m_iExternVar;

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

return 1;}main.cppint m_iExternVar = 100;Extern.cppValue = 100Command prompt32

ConstantVariable's value is constant To prevent the programmer from modifyingint const k_Hello = 0;

int main(){ k_Hello = 10;}error C3892: 'k_Hello' : you cannot assign to a variable that is constError33

Outline34

34

Primitive data type(32bits processor)TypeSizeRangevoidn/achar1 byteunsigned char: -128 127signed char: 0255short2 bytesunsigned short: 0 (216 -1)signed short: -215 (215 1)int4 bytes-231 (231 1)unsigned int: 0 (232 -1)signed int: -231 (231 1)long4 bytes-231 (231 1)unsigned long: 0 (232 -1)signed long: -231 (231 1)long long8 bytes-263 (263 1)unsigned long long: 0 (264 -1)signed long long: -263 (263 1)bool1 byteTrue /false (non-zero / zero)float4 bytesdouble8 bytes

35

New type definitionUse typedef

36typedef int Mytype;typedef int MyArr[5];

Mytype var1;MyArr arr;

sizeof operatorReturn size (in byte) of a type, data structure, variableint sizeInt = sizeof(int);int sizeLong = sizeof(long);

char a;int sizeA = sizeof(a);Return 4Return 4Return 137

Outline38

38

ArrayUsed to store consecutive values of the same data typesint b[4] = {1, 2, 3, 4};n-dimensions arrayint b[][][]si MUST BE constantIndex of array is counted from 0 to (si-1)C/C++ do not handle out-of-range exceptionint b[4] = {1, 2, 3, 4};for (int i = 0; i < 4; i++){ printf("%d\n", b[i]);

}printf("%d\n", b[10]);b[10] = ?39

Array Assignment40int a[4] = {1, 2, 3, 4};int a[] = {1, 2, 3, 4};int a[4];a[0] = 1;a[1] = 2;a[2] = 3;a[3] = 4;int a[4] = {1};a[0], a[1], a[2], a[3] = ?int a[4];memset(a, 0, 4*sizeof(int));

Array Assignment2D Array41int a[3][2];a[0][0] = 1;a[0][1] = 2;a[1][0] = 3;a[1][1] = 4;a[2][0] = 5;a[2][1] = 6;int a[3][2] = {1, 2, 3, 4, 5, 6};int a[3][2];memset(a, 0, 6*sizeof(int));int a[][2] = {1, 2, 3, 4, 5, 6};Same as 1D. Why?int a[3][2] = { {1, 2}, {3, 4}, {5, 6} };

PointerComputer's memory is made up of bytes. Each byte has a number,an address, associated with it.

0x010x020x030x010x050x060x070x08When storing a variable, such as int i = 10x000x000x000x01

0x010x020x030x040x050x060x070x08

ii = 1&i = 0x01 & operator: get address of a variable42

Pointer (cont.)For storing address of a variable, use a special type: pointerint *pi;char *pc;float *pf;Pointer of a integer variablePointer of a char variablePointer of a float variableint *pi = &i;43int* pi;pi = &i;0x100x000x000x00

0xF10xF20xF30xF40xF50xF60xF70xF8

i&i

43

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

i = 100x2f00002c0x2f00aabbp

p =&p =*p =

*p : get value at address pointed by p440x2f00002c0x2f00aabb10?= &i;= 0x2f00002c

Pointer (cont.)Type of pointer notify that how to get the value pointed by pointerint i = 0x3f20cc01;char *p1 = (char *)&i;short *p2 = (short *)&i;int *p3 = &i;p1 is pointed to char-block. *p1 = p2 is pointed to short-block. *p2 = p3 is pointed to int-block. *p3 =P1P20x010xcc0x200x3f

0xF10xF20xF30xF40xF50xF60xF70xF8

iLittle EndianP3450x010xCC010x3f20cc01

Pointer (cont.)sizeof operatorSize of pointer is not belong to type of pointerSize of pointer depend on processor (16 bits, 32 bits, 64 bits)For windows 32 bits: size of pointer is 4 bytesint main(){char c = 0;char *p = &c;printf("size = %d", sizeof(p));}46

Pointerpointer operatorNote: each step is a distance k bytes belongs to type of pointer:byte: 1 byteShort: 2 byte.OperatordescExample+move forward n stepsp += 10;-move backward n stepp -= 1;++move forward 1 stepp++;--move backward 1 stepp--;

0x010xcc0x200x3f0x000x100xaa0x010x020x030x040x050x060x07p1p1+1p1+50x010xcc0x200x3f0x000x100xaa0x010x020x030x040x050x060x07p2p2+1p2+3char *p1;short *p2;(p1+1) (p2 + 1)*(p1+1) *(p2+1)&(p1+1) &(p2+1)47

Pointerpointer operator - Practice48char a[6] = {10, 20, 30, 40, 50, 60};char *p = a;

a0x001cff08p0x001cff04a = ?&a = ?*a = ?

p = ?&p = ?*p = ?p + 1 = ?(*p) + 1 = ?*(p + 1) = ?&p + 1;&a + 1a++; a = ?p++; p = ?

a = 0x001cff08&a = 0x001cff08*a = 10p = 0x001cff08&p = 0x001cff04*p = 10

p + 1 = 0x001cff09(*p) + 1 = 11*(p + 1) = 20&p + 1 = 0x001cff08&a + 1 = 0x001cff0Ea++: failp++: 0x001cff09

48

Pointer to pointerRecall that, a pointer variable is a variable.To store address of a pointer variable, we use pointer-to-pointer variable. 49int iVar = 10;int *p1 = &iVar;int **p2 = &p1;iVar = 10p1 = 0x100p2 = 0x2000x2000x1000x300*p1 == ?*p2 == ?*(*p2) == ?

pnx4 bytesPointerDynamic allocationStatic allocation:int a = 10;int array[1000];Variable will be allocated in stack limited sizeNumber of elements of array is constCan not clean up when they become useless

Dynamic allocationUser pointerAllocation a block of memory in heap high capacityClean up easily

Alloc n-int elements in heapint *p = new int[n];

p

Free memory block pointed by p

50delete p;How about p after deleting?

PointerDynamic allocation (cont.)There two way for dynamic allocation51Using stdlib.hUsing malloc/freeOld C styleUsing new/deleteUsing new[] / delete[]C++ styleint main(){ char *i = (char*) malloc (100);

// some code here

free(i);}int main(){ char *i = new char[100];

// some code here

delete []i;}

PointerDynamic allocation (cont.)Use delete for new, Use delete[] for new[]52struct A{public: static int count; int val; A() { printf("Created %d\n", val = count++);} ~A() { printf("Deleted %d\n", val);} };

int A::count = 0;int main(){ A *cA = new A[10]; delete cA; return 1;}Delete cA[0] onlyint main(){ A *cA = new A[10]; delete []cA; return 1;}Delete all cA

Pointer-to-pointer dynamic allocationIn common, used for allocation an 2D-array53int **p;p = new int*[2];*(p+0) = new int;*(p+1) = new int;

p

0x9000x500= 0x500

0x2000x200

0x3000x300int **p = new int*[3];p[0] = new int[4];p[1] = new int[4]; p[2] = new int[4];*(*(p + i) +j ) p[i][j]

Pointer vs. ArrayIn common, pointer could be used like arrayint main(){ int *p p[0] = 1; *(p + 1) = 12; p[2] = 5}

P

0x2f330000

0x2f3300040x2f330008

0x2f0A0000stackheap*p = *(p+0) = p[0]*(p + n) = p[n]54 new int [3];= 0x2f3300001125=

Pointer vs. ArrayArray is a pointer pointed to itselfA pointer can point to an array addr.

int main(){ char a[3] = {1, 2, 3, 4}; printf ("0x%x 0x%x %d\n", a, &a, *a);

int *p = new int[3]; p[0] = 1; p[1] = 2; p[2] = 3; printf ("0x%x 0x%x %d\n", p, &p, *p);

int *p2 = (int*)a; printf("value of p2 = 0x%x\n", *p2); }0x14fd64 0x14fd64 10x591398 0x14fd60 1Value of p2 = 0x04030201Command prompt55

Pointer vs. Arraychar a[3] = {1, 2, 3};

char *p = new char[3];p[0] = 10; p[1] = 20; p[2] = 30;

printf ("a = 0x%x p = 0x%x\n", a, p);printf ("a+1 = 0x%x p+1 = 0x%x\n", a+1, p+1);printf ("&a = 0x%x &p = 0x%x\n", &a, &p);printf ("&a+1= 0x%x &p+1 = 0x%x\n", &a+1, &p+1);a = 0x26FE6C p = 0x0E1AF0a+1 = 0x26FE6D p+1 = 0x0E1AF1&a = 0x26FE6C &p = 0x26FE70&a+1= 0x26FE6F &p+1 = 0x26FE74Command prompt1020301 a0x0E1AF0p0x0E1AF10x0E1AF20x0E1AF30x0E1AF40x26FE700x26FE710x26FE720x26FE730x26FE740x26FE6C20x26FE6D30x26FE6E0x26FE6F&p + 1&a + 156a + 1p + 1

Due to stack limited, can not create a too big arrayPointer vs. Arrayint main(){ char arr[1034996];}int main(){ char *p = new char[1034996];}FAILOKCan not delete an arrayint main(){ char arr[100]; delete arr;}int main(){ char *p = new char[1034996]; delete p;}FAILOKMemory block of array is freed automatically when out-of-scopeDynamic memory MUST be clean manually by call delete57

Pointer vs. Array2D arrayint arr[2][3]pointer-to-pointerint **p = new int*[2];p[0] = new int[3];p[1] = new int[3];[0][0][0][1][0][2][1][0][1][1][1][2]p[1]p[0]pp[0][0]p[0][1]p[0][2]p[1][0]p[1][1]p[1][2]2D array & 2D pointer could use in the same wayarr[2][2] = 5 p[2][2] = 1058[0][0][0][1][0][2][1][0][1][1][1][2]Block 0Block 1

*(*(p + i) +j ) p[i][j]

C/C++ String

59

StringNo standard string in C/C++Use char*, or char[] insteadString in C/C++ is array of byte, end with \0char *st = "String";String\0st60

String allocationStatic allocationchar *st = "String";char st2[] = "String";Dynamic allocationchar *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.)62char* GetString1(){ char *st = "String"; return st;}

char* GetString2(){ char st[] = "String"; return st;}char* GetString3(){ char *st = new char[6]; strcpy(st, "String"); return st;}

int main(){ printf("Say: %s\n", GetString1()); printf("Say: %s\n", GetString2()); printf("Say: %s\n", GetString3());}What are different?

Memory utility functionsMUST #include

void * memcpy ( void * destination, const void * source, size_t num )Copies the values ofnumbytes from the location pointed bysourcedirectly to the memory block pointed bydestination

int memcmp ( const void * ptr1, const void * ptr2, size_t num )Compare the C string pointed bysourceinto the array pointed bydestination, including the terminating null character

63

Memory utility functions

size_t strlen ( const char * str )Returns the length ofstrThe length of a C string is determined by the terminating null-characterThis 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 bysourceinto the array pointed bydestination, including the terminating null character

int strcmp ( const char * str1, const char * str2 )Compares the C stringstr1to the C stringstr2.

http://www.cplusplus.com/reference/clibrary/cstring/64

Constant pointer vs.pointer to constantConstant pointer:Address of memory stored is constantValue at address which pointed to could be changed65Pointer to constant:Value at address which pointed to is constantAddress of memory stored could be changedchar char_A = 'A'; const char * myPtr = &char_A; *myPtr = 'J'; // error - can't change value of *myPtrchar char_A = 'A';char char_B = 'B';char * const myPtr = &char_A;myPtr = &char_B; // error - can't change address of myPtr

Outline66

66

EnumUse for set up collections of named integer constantsIn traditional C way:Alternate approach#define SPRING 0#define SUMMER 1#define FALL 2#define WINTER 3enum {SPRING, SUMMER, FALL, WINTER}; 012367

Enum (cont.)DeclarationValues of enum constantsenum MyEnum {SPRING, SUMMER, FALL, WINTER};

enum MyEmum x; // C styleMyEnum y; // C++ style

int main(){ y = MyEnum::SPRING; y = FALL; y = 1; // ILLEGAL}enum MyEnum {SPRING = 0, SUMMER = 10, FALL = 11, WINTER = 100};

int main(){ y = MyEnum::SPRING; printf("%d", y);}68

UnionAllow same portion of memory to be accessed as different data typeunion MyUnion{ int iValue; char cValue; char aValue[4];};

int main(){ MyUnion mine = {0x01020304}; printf("iValue: 0x%x\n", mine.iValue); printf("iValue: 0x%x\n", mine.cValue); printf("iValue: 0x%x 0x%x 0x%x 0x%x\n", mine.aValue[0], mine.aValue[1], mine.aValue[2], mine.aValue[3]);}0x040x030x020x01iValue0x010203040x040x040x030x020x01cValueaValueMemory blocksizeof(mine) = ?69

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

val1val2val3T_MyStruct70

StructUsing 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 alignmentIs the way data is arranged and accessed in computer memory.

Consist two issue:Data alignment:Put data at memory offset equal to multiple word sizeStructure padding:Insert some meaningless bytes between the of last data structure and start of next72

Data Structure alignmentBefore compile, total memory of T_MyStruct is 8 byte

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

pad1val2val3val401234891011val14 bytes block4 bytes block4 bytes blockpad2

4 bytes alignmentsizeof(T_MyStruct) == 12 bytes73

VS Struct member alignment

74

GCC alignment75struct test_t { int a; char b; int c;}__attribute__((aligned(8)));struct test_t { int a; char b; int c;}__attribute__((__packed__));http://www.delorie.com/gnu/docs/gcc/gcc_62.html8 byte alignmentsmallest possible alignment

Struct - functionC++ only, not available in CBeside variable, struct also has had functionStruct alignment is not effected to struct-functionFunction is not counted when calculate struct sizetypedef struct T_MyStruct{ int val1; char val2; char val3[12]; void SayHello();}MyStruct;

void MyStruct::SayHello(){ printf("Hello world");}

int main(){ MyStruct myStruct; myStruct.SayHello();}76

Structconstructor / destructorC++ only, not available in CTwo special function of structConstructor: automatically call when a instant of struct is createdDestructor: automatically call when a instant of struct is destroy

typedef struct T_MyStruct{ int val1; T_MyStruct(); ~T_MyStruct();}MyStruct;

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

int main(){ MyStruct myStruct;}constructordestructorCreatedDestroyCommand prompt77

Struct and static memberStatic function & static variableStatic variable is not counted is struct alignment and struct sizetypedef struct T_MyStruct{ int val1; static char val2; static void SayHello() {}}MyStruct;

int main(){ MyStruct myStruct; printf("%d", sizeof(myStruct)); MyStruct::SayHello();}78

Struct and Access privilegeC++ only, not available in CThree access privilege methodspublic: visible for allprivate: visible inside struct onlyprotected: visible inside struct and retrieved struct (OOP)

Default is public For example: valx is public79struct MyStruct{ int valx;public: int val1;private: int val2;protected: int val3;};

int main(){ MyStruct mine; mine.val1 = 0; mine.valx = 0; mine.val2 = 0; mine.val3 = 0;}Fatal Error, val2 is privateFatal Error, val3 is protected

Outline80

80

C/C++ function function_name([ ], [])void foo() {}

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

int foo() { return 1;}

No return function

Required return

81

Default parameters#include void foo(int a, int b = 1 , int c = 2 );

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

void main(){ foo(0); foo(0, 10); foo(0, 10, 100);}

Set default valueUse b, c as default valueNo default valueUse b, c as default value0 1 20 10 20 10 100Command prompt82

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

ERRORerror C2548: 'foo' : missing default parameter for parameter 3When a parameter is set default value, the rest of next parameters MUST BE set default value tooRULES83

Variable number of parameters#include #include

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 classification85

Pages.cs.wisc.edu/~hasti/cs368/CppTutorial/NOTES/PARAMS85

Parameter classificationPass-by-valueA copy of parameter is madevoid foo(int n){ n++;}void main(){ int x = 2; foo(x); printf("%d\n", x);}x = 2

2x2x2n2x3n2x

foo86

Pages.cs.wisc.edu/~hasti/cs368/CppTutorial/NOTES/PARAMS86

Parameter classificationPass-by-referenceActually parameter itself is passedUse reference operator &void foo(int &n){ n++;}void main(){ int x = 2; foo(x); printf("%d\n", x);}x = 3

2x2xnx3n3x

foo87

Pages.cs.wisc.edu/~hasti/cs368/CppTutorial/NOTES/PARAMS87

Parameter classificationPass-by-valueA copy of parameter is made and strict as const.

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

2x2x2n2x3n

foo

88

Pages.cs.wisc.edu/~hasti/cs368/CppTutorial/NOTES/PARAMS88

Parameter classificationPass-by-refActually parameter itself is passed but avoid modifyVoid the overhead of creating a copyvoid foo(int const &n){//todo}89

Pages.cs.wisc.edu/~hasti/cs368/CppTutorial/NOTES/PARAMS89

Parameter classificationIn common, Pass-by-valueA copy of parameter is made Value of parameter is an address of a memory blockvoid foo(int *n){//todo}Value of parameter will not be change, but memory block which pointed by parameter could be modified.90

Pages.cs.wisc.edu/~hasti/cs368/CppTutorial/NOTES/PARAMS90

Pointer Parameter#include void foo(int *A, int *B){ int *tmp = A; A = B; B = tmp;}

void main(){ int A[] = {1, 2, 3}; int B[] = {10, 11}; printf("0x%x 0x%x\n", A, B); foo(A, B); printf("0x%x 0x%x\n", A, B);}ABABABABCopy value (addr. of data)foo0x29faa8 0x29faa00x29faa8 0x29faa0Command prompt91

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

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

AA[2] = 3A[2] = 10Copy value (addr. of data)92

Pointer reference parameterA special case of pointer parameterValue of pointer parameter (address of block memory) could be changedPass-by-referenceCAN NOT work with array directly#include void foo(int *&A, int *&B){ int *tmp = A; A = B; B = tmp;}void main(){ int arr1[] = {1, 2, 3}; int arr2[] = {10, 11}; int *A = arr1; int *B = arr2; printf("0x%x 0x%x\n", A, B); foo(A, B); printf("0x%x 0x%x\n", A, B);}ABABABABfoo0x31fc90 0x31fc880x31fc88 0x31fc90Command prompt93

Function overloadingC++ onlyAllow 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 PrototypeIn C/C++, functions MUST BE declare before using.To solve this problemsKeep all functions in correct orderUse prototype inside .cpp fileUse prototype inside header (.h) file -> recommend#include "header.h"void Todo1(){ Todo2();}void Todo2(){}int main(){}Main.cppvoid Todo1(){ Todo2();}void Todo2(){}int main(){}Errorerror C3861: 'Todo2': identifier not foundMain.cppheader.hvoid Todo1();void Todo2();

95

Extern functionSometimes, we need to use a function in another module (.cpp file)Header file is too complicated to use (caused error when used)#include extern void TodoExtern();

int main(){ TodoExtern(); return 1;}Main.cpp#include

void TodoExtern(){ printf("TodoExtern\n");}

Extern.cpp96

Extern CName mangling:Aka name decorationThe way of encoding additional information in a name of function, struct, classIn C++:For adapting overload, class/struct functions, name of function will be encodingint f (void) { return 1; }int f (int) { return 0; }

int __f_v (void) { return 1; }int __f_i (int) { return 0; }97

Extern CFor mixing C and C++ source (Object C also) use extern "C"

Extern C talk to compiler that use C style for its scopeNo name manglingNo overloading

Extern C is also extern function could be implement in another module#include void ExternC(){ printf("ExternC\n");}Ansi_c.cextern "C" { void ExternC(); void Todo() { printf("%d", i); }}C_plusplus.cpp98

Extern C in practice#ifdef __cplusplusextern "C" {#endif

// your code here

#ifdef __cplusplus}#endif__cplusplus: default C++ preprocessor definition99

Pointer to functionA variable store address of a functionAdvantageFlexibleUser for event handling mechanism

// C void DoIt (float a, char b, char c){}void (*pt2Function)(float, char, char) = DoIt;

// usingpt2Function(0, 0, 0); 100

Inline functionMacro: preprocessor replaces all macro calls directly with the macro code101#define NEXT(a) (a+1)int main() { printf("%d", NEXT(1));}

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

Inline function (cont)Like macro, but obeys C/C++ syntax102inline int Next(int x){ return x + 1;}

int main() { printf("%d", Next(1));}For OOP, Inline function is allowed to set access privilegeImprove performance (for short/simple inline functions)NOTE: The compiler is not forced to inline anything at all Why performance is improved?

Outline103

103

NamespaceA abstract container uses for grouping source code.In C++, a namespace is defined with a namespace blocknamespace maths {void sin() {}void cos() {}void add() {}}namespace matrix {void mult() {}void add() {}} 104

Using namespaceFor using methods, variables, of a namespace:::namespace maths { void sin() {} void cos() {} void add() {}}namespace matrix { void mult() {} void add() {}}

void main(){ maths::sin(); matrix::add();}105

Using namespaceUse 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 callMore than two definition of add functions maths::add()matrix::add()ambiguous call fatal error.

In this case, MUST BE specify namespace.namespace maths{ void add();}

namespace matrix{ void add();}

using namespace maths;using namespace matrix;

void main(){ add();}error C2668: 'matrix::add' : ambiguous call to overloaded function .\main.cpp(8): could be 'void matrix::add(void)' .\main.cpp(3): or 'void maths::add(void)'

107

Outline108

Abstract/virtual/pure virtualInstant Object

108

Outline109

Abstract/virtual/pure virtualInstant Object

109

ClassAs same as structDefault access is private110class 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

DestructorFunction (methods)

Inline methods

Class variable (property)Function implementation

Class (cont)In traditional, code of class is divided into 2 partsDeclaration: in .h fileImplementation: in .cpp file111#ifndef __CCLASS_H__#define __CCLASS_H__class CClass{ public: CClass(); ~CClass(); private: void Toso() ;};#endifAny_name.h#include "Any_name.h" void CClass::Todo(){ }CClass::~CClass(){ }

Any_name.cpp

How to use class112MyClass objA; //or MyClass objA() objA.SayHello();Create a object directlyAccess class methods, properties by using dotCreate a object through pointer.Two ways to use methods, properties(*objA). C styleobjA-> C++ styleSupported polymorphism

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

112

Access methodsAka EncapsulationPublic: allow access inside & outside classProtected: allow access inside class & in derived classPrivate : allow access inside class only

113

ConstructorShould be publicCalled when an instance is createdA class could define a set of constructors (constructor overloading)

114class MyClass{public:MyClass();

MyClass(MyClass* A);MyClass(const MyClass& A);

MyClass(int val);}Default constructorCopy constructor.

Copy constructorDefinition:A constructor with the same name as the classUsed to make a deep copy of objects (be careful if class content pointer properties)115

If no user-defined constructor is defined, compiler defines one.X (const X& copy_from_me)X (X* copy_from_me)X (X& copy_from_me)X (const X&copy_from_me, int = 10, float = 1.0 )Must be set default value

Copy constructor (cont.)Invoked whenWhen a object is created from another object of the same typeWhen an object is passed by value as parameter to functionWhen a object is return from a function116class ABC{public: ABC(){} ABC(ABC *A){printf("here1\n");} ABC(const ABC &A) { printf("here2\n"); }};void Foo1(ABC A){}ABC Foo2(){ ABC a; return a;}int main() { ABC *A = new ABC(); ABC B(A); Foo1(A); Foo2();}

Copy constructor (cont)A default copy constructor is created automatically, but it is often not what you want.

117Image(Image *img) { width = img->width; height = img->height; data = new int[width*height]; for (int i=0; idata[i];}Image(Image *img) { width = img->width; height = img->height; data = img->data;}

Automatic generated copy constructorUser-defined (expected) copy contructor

Explicit constructor"nonconverting"Explicit constructor syntax is required.118class A {public: explicit A(int) {}};

void f(A) {}

void g(){ A a1 = 37; A a2 = A(47); a1 = 67; f(77);}Without explicitWith explicit

DestructorAutomatically invoked when an object is destroy:Out of scopeOr manually free (use pointer)

Use for collect class memory119class MyClass{char m_Var;int m_pData;public: MyClass(char id) { m_Var = id; m_pData = new int[100]; }; ~MyClass() { delete m_pData; cout


Recommended