gettingstartedcpp - full.pdf
TRANSCRIPT
-
7/23/2019 GettingStartedCpp - Full.pdf
1/245
-
7/23/2019 GettingStartedCpp - Full.pdf
2/245
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Appendix2
-
7/23/2019 GettingStartedCpp - Full.pdf
3/245
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
-
7/23/2019 GettingStartedCpp - Full.pdf
4/245
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Appendix
Variables and constant
Primary data type
Array Pointer String
Data structure: enum union - struct
Function
Namespace
4
-
7/23/2019 GettingStartedCpp - Full.pdf
5/245
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Appendix
Class & Object
Inheritance
Polymorphism
Operator overloading
Class static member5
-
7/23/2019 GettingStartedCpp - Full.pdf
6/245
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Appendix
Recall pointer
Memory leak
6
-
7/23/2019 GettingStartedCpp - Full.pdf
7/245
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Appendix
Forward declaration
Standard IO Console IO & FILE
Template
Type casting
Exception handling
Endian
STL introduction
GNU GCC/G++ 7
-
7/23/2019 GettingStartedCpp - Full.pdf
8/245
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
-
7/23/2019 GettingStartedCpp - Full.pdf
9/245
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
-
7/23/2019 GettingStartedCpp - Full.pdf
10/245
Hello world using VS
10
-
7/23/2019 GettingStartedCpp - Full.pdf
11/245
Hello world
# include
void main()
{
printf("Hello world");
}
main.cpp
Use standard IO lib
Entry point
Print to console screen
11
-
7/23/2019 GettingStartedCpp - Full.pdf
12/245
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
-
7/23/2019 GettingStartedCpp - Full.pdf
13/245
C/C++ source files
Header file (.h) aka include file
Hold declarations for other filesuse (prototype)
Not required
#include"stdio.h"
void Todo1();
void Todo2();
# include"header.h"
void Todo1()
{
Todo2();
}
void Todo2(){}
void main()
{
Todo1();
}
Source file (.c / .cpp)Content implementation
Required
13
-
7/23/2019 GettingStartedCpp - Full.pdf
14/245
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
-
7/23/2019 GettingStartedCpp - Full.pdf
15/245
Entry point
Required unique entry point
The most common is: mainvoid main()
{
// your code here
}
Form1.cpp
int main(int n, char ** args)
{
// your code here}
Form2.cpp
1>LINK : fatal error LNK1561: entry point
must be defined
Error when no entry point is defined
15
-
7/23/2019 GettingStartedCpp - Full.pdf
16/245
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
-
7/23/2019 GettingStartedCpp - Full.pdf
17/245
C/C++ standard library
C/C++ support a set of internalbasic library, such as
Basic IO
Math
Memory handle
For using, include the header
file#include
#include ""
#include"stdio.h"
void main()
{
printf("hello");
}
17
-
7/23/2019 GettingStartedCpp - Full.pdf
18/245
C header C++ header
Content assert macro, for debugging
For character classification/convert functions
For testing error number Floating point macros
Define range of value of common type
Mathematical functions
Provide non-local jumps for flow control
Controlling various exceptional conditions
Standard lib
Standard IO
Manipulating several kinds of string
Converting between time & date formats
18
-
7/23/2019 GettingStartedCpp - Full.pdf
19/245
C/C++ user-defined lib
Not C/C++ standard lib
Come from:
Third-party User own
In common, include 2 parts
.h files & .lib files: for developer
.dll file (dynamic library): for end-user
error LNK2019: unresolved external symbol
Error caused when forget to add .lib file
19
-
7/23/2019 GettingStartedCpp - Full.pdf
20/245
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
-
7/23/2019 GettingStartedCpp - Full.pdf
21/245
Declare path to .lib
Import user-defined library
Visual studio
21
-
7/23/2019 GettingStartedCpp - Full.pdf
22/245
Import user-defined library
Visual studio
Declare .lib file
22
-
7/23/2019 GettingStartedCpp - Full.pdf
23/245
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
-
7/23/2019 GettingStartedCpp - Full.pdf
24/245
Process
Source
.h/.c/.cpppreprocess
Preprocessedsource
Compile
.o / .obj
(object file)LinkerExecutable/
lib
Tools:
Visual Studio: cl.exe (Press F7 / F5)
GNU GCC: gcc/ g++
24
-
7/23/2019 GettingStartedCpp - Full.pdf
25/245
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Variables and constant
Primary data type
Array Pointer - String
Data structure: enum union - struct
Function
Namespace
25
-
7/23/2019 GettingStartedCpp - Full.pdf
26/245
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Variables and constant
Primary data type
Array Pointer - String
Data structure: enum union - struct
Function
Namespace
26
-
7/23/2019 GettingStartedCpp - Full.pdf
27/245
Variable classification
Scope:
Local variable
Global variable
Static variable
Storage class specifier
auto
static
register
extern
27
-
7/23/2019 GettingStartedCpp - Full.pdf
28/245
Global & localintmGlobalVar;
void Foo()
{
intlocalVar;printf("Foo : %d %d\n",
localVar, mGlobalVar);
}
int main()
{
intlocalVar = 1;
printf("Main: %d %d\n",localVar, mGlobalVar);
mGlobalVar = 1;Foo();
return 1;
}
Global variable
Available in all of program
Set default value to zero
Local variable
NO default value
Available inside block
Main: 1 0
Foo : 2280752 1
Command prompt
28
-
7/23/2019 GettingStartedCpp - Full.pdf
29/245
Auto variable
As default, a variable is a auto variable
intmyVar auto int myVar
Go out of scope once the program exits from the
current block
29
-
7/23/2019 GettingStartedCpp - Full.pdf
30/245
Static variable
Allocated when the programstarts and is deallocated whenthe program ends.
Default value is zero (0)
#include
staticints_iGlobalStatic;
void Foo()
{
staticints_iLocalStatic;printf("Foo: called %d\n",
s_iLocalStatic++);}
int main()
{
int localVar = 1;printf("Main: %d\n",
s_iGlobalStatic);Foo();
Foo();
Foo();
return 1;
}
Main: 0
Foo: called 0
Foo: called 1
Foo: called 2
Command prompt
30
-
7/23/2019 GettingStartedCpp - Full.pdf
31/245
Register variable
Stored in a machine register if
possible
Usually used in for iterator
for improve performance
int main()
{
int sum = 0;
for (registerint i = 0;
i < 100;i++)
{
sum += i;
}
printf("Sum = %d\n", sum);
return 1;
}
31
-
7/23/2019 GettingStartedCpp - Full.pdf
32/245
Extern variable
Specify that the variable isdeclared in a different file.
Compiler will not allocate
memory for the variable
Avoid duplicate declaration
Share (global) variable formultiple .cpp files
#include
externint m_iExternVar;
int main()
{
printf("Value = %d\n",m_iExternVar);
return 1;
}
main.cpp
int m_iExternVar = 100;
Extern.cpp
Value = 100
Command prompt
32
-
7/23/2019 GettingStartedCpp - Full.pdf
33/245
Constant
Variable's value is constant
To prevent the programmer from modifying
intconst k_Hello = 0;
int main()
{
k_Hello = 10;
}
error C3892: 'k_Hello' : you cannot assign to
a variable that is const
Error
33
-
7/23/2019 GettingStartedCpp - Full.pdf
34/245
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Variables and constant
Primary data type
Array Pointer - String
Data structure: enum union - struct
Function
Namespace
34
-
7/23/2019 GettingStartedCpp - Full.pdf
35/245
Primitive data type
(32bits processor)Type Size Range
void n/a
char 1 byte unsigned char: -128 127
signed char: 0255
short 2 bytes unsigned short: 0 (216 -1)
signed short: -215 (215 1)
int 4 bytes
-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
-
7/23/2019 GettingStartedCpp - Full.pdf
36/245
New type definition
Use typedef
36
typedefint Mytype;
typedefint MyArr[5];
Mytype var1;MyArr arr;
-
7/23/2019 GettingStartedCpp - Full.pdf
37/245
sizeof operator
0Return 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
-
7/23/2019 GettingStartedCpp - Full.pdf
38/245
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Variables and constant
Primary data type
Array Pointer - String
Data structure: enum union - struct
Function
Namespace
38
-
7/23/2019 GettingStartedCpp - Full.pdf
39/245
Array
Used to store consecutive values of the same data types
int b[4] = {1, 2, 3, 4};
n-dimensions array
int b[][][] si MUST BE constant
Index of array is counted from 0 to (si-1)
C/C++ do not handle out-of-range exception
int b[4] = {1, 2, 3, 4};
for (int i = 0; i < 4; i++){
printf("%d\n", b[i]);
}
printf("%d\n", b[10]);
b[10] = ?
39
-
7/23/2019 GettingStartedCpp - Full.pdf
40/245
Array Assignment
40
int a[4] = {1, 2, 3, 4};
int a[] = {1, 2, 3, 4};
int a[4];
a[0] = 1;
a[1] = 2;
a[2] = 3;a[3] = 4;
int a[4] = {1};
a[0], a[1],
a[2], a[3] = ?
int a[4];
memset(a, 0, 4*sizeof(int));
-
7/23/2019 GettingStartedCpp - Full.pdf
41/245
Array Assignment
2D Array
41
int a[3][2];
a[0][0] = 1;
a[0][1] = 2;
a[1][0] = 3;
a[1][1] = 4;
a[2][0] = 5;
a[2][1] = 6;
int a[3][2] = {1, 2, 3, 4, 5, 6};
int a[3][2];
memset(a, 0, 6*sizeof(int));
int a[][2] = {1, 2, 3, 4, 5, 6};
Same as
1D. Why?
int a[3][2] = {
{1, 2},
{3, 4},
{5, 6}
};
-
7/23/2019 GettingStartedCpp - Full.pdf
42/245
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 inti = 1
0x00 0x00 0x00 0x01
0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08
i
o i = 1
o &i = 0x01 & operator: get address of a variable
42
http://augustcouncil.com/~tgibson/tutorial/addressDef.htmlhttp://augustcouncil.com/~tgibson/tutorial/addressDef.html -
7/23/2019 GettingStartedCpp - Full.pdf
43/245
Pointer (cont.)
For storing address of a variable, use a special type:
pointer
int *pi; char *pc; float *pf;
Pointer of a
integer variablePointer of a
char variable
Pointer of a
float variable
int *pi = &i;
43
int* pi;
pi = &i;
0x10 0x00 0x00 0x00
0xF1 0xF2 0xF3 0xF4 0xF5 0xF6 0xF7 0xF8
i
&i
-
7/23/2019 GettingStartedCpp - Full.pdf
44/245
Pointer (cont.)
Pointer is also a variableits stored in memory
int i = 10;int *p
i = 100x2f00002c
0x2f00aabb p
p =
&p =
*p =
*p : get value at address pointed by p
44
0x2f00002c
0x2f00aabb
10
= &i;
= 0x2f00002c
-
7/23/2019 GettingStartedCpp - Full.pdf
45/245
Pointer (cont.)
Type of pointer notify that how to get the value
pointed by pointer
int i = 0x3f20cc01;char *p1 = (char *)&i;
short *p2 = (short *)&i;
int *p3 = &i;
p1 is pointed to char-block. *p1 =
p2 is pointed to short-block. *p2 =
p3 is pointed to int-block. *p3 =
P1 P2
0x01 0xcc 0x20 0x3f
0xF1 0xF2 0xF3 0xF4 0xF5 0xF6 0xF7 0xF8
iLittle Endian
P3
45
0x01
0xCC01
0x3f20cc01
-
7/23/2019 GettingStartedCpp - Full.pdf
46/245
Pointer (cont.)
sizeof operatorSize of pointer is not belong to type of pointer
Size of pointer depend on processor (16 bits, 32 bits, 64bits)
For windows 32 bits: size of pointer is 4 bytes
int main()
{
char c = 0;
char *p = &c;
printf("size = %d", sizeof(p));
}
46
-
7/23/2019 GettingStartedCpp - Full.pdf
47/245
Pointer
pointer operatorNote: each step is a distance k bytes
belongs to type of pointer:
byte: 1 byte
Short: 2 byte .
Operat
or
desc Example
+ move forward n steps p += 10;
- move backward n step p -= 1;
++ move forward 1 step p++;
-- move backward 1 step p--;
0x01 0xcc 0x20 0x3f 0x00 0x10 0xaa
0x01 0x02 0x03 0x04 0x05 0x06 0x07
p1 p1+1 p1+5
0x01 0xcc 0x20 0x3f 0x00 0x10 0xaa
0x01 0x02 0x03 0x04 0x05 0x06 0x07
p2 p2+1 p2+3
char *p1; short *p2;
(p1+1) (p2 + 1)*(p1+1) *(p2+1)
&(p1+1) &(p2+1)
47
-
7/23/2019 GettingStartedCpp - Full.pdf
48/245
Pointer
pointer operator - Practice
48
char a[6] = {10, 20, 30, 40, 50, 60};
char *p = a;
a
0x001cff08
p0x001cff04
a = ?
&a = ?
*a = ?
p = ?&p = ?
*p = ?
p + 1 = ?
(*p) + 1 = ?
*(p + 1) = ?
&p + 1;
&a + 1a++; a = ?
p++; p = ?
-
7/23/2019 GettingStartedCpp - Full.pdf
49/245
Pointer to pointer
Recall that, a pointer variable is a variable.
To store address of a pointer variable, we use pointer-to-pointer variable.
49
int iVar = 10;
int *p1 = &iVar;
int **p2 = &p1;
iVar = 10
p1 = 0x100
p2 = 0x200
0x200
0x100
0x300
*p1 == ?
*p2 == ?
*(*p2) == ?
-
7/23/2019 GettingStartedCpp - Full.pdf
50/245
p
nx4 bytes
Pointer
Dynamic allocation Static allocation:
int a = 10;
int array[1000];
Variable will be allocated in stack limited size
Number of elements of array is const
Can not clean up when they become useless
Dynamic allocation User pointer
Allocation a block of memory in heap high capacity
Clean up easily
Alloc n-int elements in heap
int *p = newint[n];
p
Free memory block pointed by p
50
delete p;
How about
p after
deleting?
-
7/23/2019 GettingStartedCpp - Full.pdf
51/245
Pointer
Dynamic allocation (cont.)There two way for dynamic allocation
51
Using stdlib.h Using malloc/free
Old C style
Using new/delete Using new[] / delete[]
C++ style
int main()
{
char *i = (char*) malloc (100);
// some code here
free(i);
}
int main()
{
char *i = new char[100];
// some code here
delete []i;
}
-
7/23/2019 GettingStartedCpp - Full.pdf
52/245
Pointer
Dynamic allocation (cont.)Use delete for new,
Use delete[] for new[]
52
struct A
{
public:staticint count;
int val;
A()
{
printf("Created %d\n",
val = count++);}
~A(){
printf("Deleted %d\n",
val);}
};
int A::count = 0;
int main()
{
A *cA = new A[10];delete cA;
return 1;
}
Delete cA[0] only
int main(){
A *cA = new A[10];
delete []cA;
return 1;
}
Delete all cA
-
7/23/2019 GettingStartedCpp - Full.pdf
53/245
Pointer-to-pointer dynamic
allocation
In common, used for allocation an 2D-array
53
int **p;
p = new int*[2];
*(p+0) = new int;
*(p+1) = new int;
p0x900
0x500
= 0x500
0x200
0x200
0x300
0x300
int **p = newint*[3];
p[0] = newint[4];
p[1] = newint[4];
p[2] = new int[4];
*(*(p + i) +j ) p[i][j]
-
7/23/2019 GettingStartedCpp - Full.pdf
54/245
Pointer vs. Array
In common, pointer could be used like array
int main()
{
int *p
p[0] = 1;
*(p + 1) = 12;
p[2] = 5}
P
0x2f330000
0x2f330004
0x2f330008
0x2f0A0000
stack
heap
*p = *(p+0) = p[0]
*(p + n) = p[n]
54
newint [3];
= 0x2f330000
112
5
=
-
7/23/2019 GettingStartedCpp - Full.pdf
55/245
Pointer vs. Array
Array is a pointer
pointed to itself
A pointer can point to
an array addr.
int main()
{
char a[3] = {1, 2, 3, 4};
printf ("0x%x 0x%x %d\n", a, &a, *a);
int *p = newint[3];
p[0] = 1; p[1] = 2; p[2] = 3;
printf ("0x%x 0x%x %d\n", p, &p, *p);
int *p2 = (int*)a;
printf("value of p2 = 0x%x\n", *p2);
}
0x14fd64 0x14fd64 1
0x591398 0x14fd60 1
Value of p2 = 0x04030201
Command prompt
55
-
7/23/2019 GettingStartedCpp - Full.pdf
56/245
Pointer vs. Array
char a[3] = {1, 2, 3};
char *p = newchar[3];
p[0] = 10; p[1] = 20; p[2] = 30;
printf ("a = 0x%x p = 0x%x\n", a, p);
printf ("a+1 = 0x%x p+1 = 0x%x\n", a+1, p+1);
printf ("&a = 0x%x &p = 0x%x\n", &a, &p);
printf ("&a+1= 0x%x &p+1 = 0x%x\n", &a+1, &p+1);
a = 0x26FE6C p = 0x0E1AF0
a+1 = 0x26FE6D p+1 = 0x0E1AF1
&a = 0x26FE6C &p = 0x26FE70
&a+1= 0x26FE6F &p+1 = 0x26FE74
Command prompt
10
2030
1 a
0x0E1AF0
p
0x0E1AF1
0x0E1AF2
0x0E1AF3
0x0E1AF4
0x26FE70
0x26FE71
0x26FE72
0x26FE73
0x26FE74
0x26FE6C
20x26FE6D
30x26FE6E
0x26FE6F
&p + 1
&a + 1
56
a + 1
p + 1
-
7/23/2019 GettingStartedCpp - Full.pdf
57/245
Due to stack limited, can not create a too big array
Pointer vs. Array
int main()
{
char arr[1034996];
}
int main()
{
char *p = new char[1034996];
}
FAIL OK
0Can not delete an arrayint main()
{
char arr[100];
delete arr;
}
int main()
{
char *p = new char[1034996];
delete p;
}
FAIL OK
Memory block of array is freed automatically when out-of-scope
Dynamic memory MUST be clean manually by call delete57
-
7/23/2019 GettingStartedCpp - Full.pdf
58/245
Pointer vs. Array2D array
int arr[2][3]
pointer-to-pointerint **p = newint*[2];
p[0] = newint[3];
p[1] = newint[3];
[0][0] [0][1] [0][2]
[1][0] [1][1] [1][2]
p[1]
p[0]p p[0][0] p[0][1] p[0][2]
p[1][0] p[1][1] p[1][2]
02D array & 2D pointer could use in the same way
arr[2][2] = 5 p[2][2] = 10
58
[0][0] [0][1] [0][2] [1][0] [1][1] [1][2]
Block 0 Block 1
*(*(p + i) +j ) p[i][j]
-
7/23/2019 GettingStartedCpp - Full.pdf
59/245
C/C++ String
59
-
7/23/2019 GettingStartedCpp - Full.pdf
60/245
String
No standard string in C/C++
Use char*, or char[] instead
String in C/C++ is array of byte, end with \0
char *st = "String";
S t r i n g \0st
60
-
7/23/2019 GettingStartedCpp - Full.pdf
61/245
String allocation
Static allocation
char *st = "String";
char st2[] = "String";
Dynamic allocation
char *st3 = newchar[6];
st3[0] = 's';
st3[1] = 't';
st3[2] = 'i';st3[3] = 'n';
st3[4] = 'g';
st3[5] = '\0';
61
-
7/23/2019 GettingStartedCpp - Full.pdf
62/245
String allocation (cont.)
62
char* GetString1(){
char *st = "String";
return st;
}
char* GetString2(){
char st[] = "String";
return st;
}
char* GetString3(){
char *st = newchar[6];
strcpy(st, "String");
return st;
}
int main(){
printf("Say: %s", GetString1());
printf("Say: %s", GetString2());
printf("Say: %s", GetString3());
}
What are
different?
-
7/23/2019 GettingStartedCpp - Full.pdf
63/245
Memory utility functions
MUST #include
void * memcpy ( void * destination, const void * source, size_t num )
Copies the values ofnum 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
-
7/23/2019 GettingStartedCpp - Full.pdf
64/245
Memory utility functions
size_t strlen ( const char * str ) Returns the length ofstr
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 thestring
char * strcpy ( char * destination, const char * source )
Copies the C string pointed by source into the array pointedby 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
http://www.cplusplus.com/reference/clibrary/cstring/http://www.cplusplus.com/reference/clibrary/cstring/ -
7/23/2019 GettingStartedCpp - Full.pdf
65/245
Constant pointer vs.
pointer to constantConstant pointer:
Address of memory stored is constant
Value at address which pointed to could be changed
65
Pointer to constant: Value at address which pointed to is constant Address of memory stored could be changed
char char_A = 'A';
constchar * myPtr = &char_A;
*myPtr = 'J'; // error - can't change value of *myPtr
char char_A = 'A';
char char_B = 'B';
char * const myPtr = &char_A;
myPtr = &char_B; // error - can't change address of myPtr
-
7/23/2019 GettingStartedCpp - Full.pdf
66/245
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Variables and constant
Primary data type
Array Pointer - String
Data structure: enum union - struct
Function
Namespace
66
-
7/23/2019 GettingStartedCpp - Full.pdf
67/245
Enum
Use for set up collections of named integer constants
In traditional C way:
Alternate approach
#define SPRING 0
#define SUMMER 1
#define FALL 2
#define WINTER 3
enum {SPRING, SUMMER, FALL, WINTER};
0 1 2 367
-
7/23/2019 GettingStartedCpp - Full.pdf
68/245
Enum (cont.)Declaration
Values of enum constants
enum MyEnum{SPRING, SUMMER, FALL, WINTER};
enumMyEmum x; // C style
MyEnum y; // C++ style
int main(){
y = MyEnum::SPRING;
y = FALL;
y = 1; // ILLEGAL}
enum MyEnum{SPRING = 0, SUMMER = 10, FALL = 11, WINTER = 100};
int main()
{
y = MyEnum::SPRING;
printf("%d", y);
} 68
-
7/23/2019 GettingStartedCpp - Full.pdf
69/245
Union
Allow 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]);
}
0x04 0x03 0x02 0x01
iValue 0x01020304
0x04
0x04 0x03 0x02 0x01
cValue
aValue
Memory block
sizeof(mine) = ?
69
-
7/23/2019 GettingStartedCpp - Full.pdf
70/245
Struct
Define a structure type and/or a variable of a
structure type.
struct T_MyStruct
{int val1;
char val2;
char val3[5];
};
struct T_MyStruct myStruct;
val1
val2
val3
T_MyStruct
70
-
7/23/2019 GettingStartedCpp - Full.pdf
71/245
Struct
Using struct:typedefstruct 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
-
7/23/2019 GettingStartedCpp - Full.pdf
72/245
Data Structure alignment
Is the way data is arranged and accessed in computer
memory.
Consist two issue:
Data alignment:
oPut data at memory offset equal to multiple word size
Structure padding:
o Insert some meaningless bytes between the of last datastructure and start of next
72
-
7/23/2019 GettingStartedCpp - Full.pdf
73/245
Data Structure alignment
0Before compile, total memory
of T_MyStruct is 8 byte
struct T_MyStruct
{
char val1;
short val2;
int val3;char val4;
};
char: 1 byte aligned
short: 2 byte aligned
int : 4 byte aligned
val1 val2 val3 val4
0 1 3 7
pad
1val2 val3 val4
0 1 2 3 4 8 9 10 11
val1
4 bytes block 4 bytes block 4 bytes block
pad2
4 bytes alignment
sizeof(T_MyStruct) == 12 bytes73
-
7/23/2019 GettingStartedCpp - Full.pdf
74/245
VS Struct member alignment
74
-
7/23/2019 GettingStartedCpp - Full.pdf
75/245
GCC alignment
75
struct test_t
{
int a;
char b;
int c;}__attribute__((aligned(8)));
struct test_t
{
int a;
char b;int c;
}__attribute__((__packed__));
http://www.delorie.com/gnu/docs/gcc/gcc_62.html
8 byte alignment
smallest possible alignment
http://www.delorie.com/gnu/docs/gcc/gcc_62.htmlhttp://www.delorie.com/gnu/docs/gcc/gcc_62.html -
7/23/2019 GettingStartedCpp - Full.pdf
76/245
Struct - function
C++ only, not availablein C
Beside variable, struct
also has had functionStruct alignment is not
effected to struct-function
Function is not countedwhen calculate structsize
typedefstruct 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
S
-
7/23/2019 GettingStartedCpp - Full.pdf
77/245
Struct
constructor / destructorC++ only, not available in C
Two special function of struct
Constructor: automatically callwhen a instant of struct is created
Destructor: automatically callwhen a instant of struct is destroy
typedefstruct T_MyStruct
{
int val1;T_MyStruct();
~T_MyStruct();
}MyStruct;
T_MyStruct::T_MyStruct()
{
printf("Created\n");
}
T_MyStruct::~T_MyStruct()
{
printf("Destroy\n");}
int main()
{
MyStruct myStruct;
}
constructor
destructor
Created
Destroy
Command prompt
77
-
7/23/2019 GettingStartedCpp - Full.pdf
78/245
Struct and static member
Static function & static
variable
Static variable is not
counted is structalignment and struct
size
typedefstruct T_MyStruct
{
int val1;
staticchar val2;
staticvoid SayHello() {}
}MyStruct;
int main()
{
MyStruct myStruct;
printf("%d", sizeof(myStruct));
MyStruct::SayHello();
}
78
-
7/23/2019 GettingStartedCpp - Full.pdf
79/245
Struct and Access privilege
C++ only, not available in CThree access privilege methods
public: visible for allprivate: visible inside struct onlyprotected: visible inside struct and
retrieved struct (OOP)
Default ispublico For example: valx is public
79
struct MyStruct
{int valx;
public:
int val1;
private:
int val2;
protected:int val3;
};
int main()
{
MyStruct mine;mine.val1 = 0;
mine.valx = 0;
mine.val2 = 0;
mine.val3 = 0;
}
Fatal Error, val2 is private
Fatal Error, val3 is protected
-
7/23/2019 GettingStartedCpp - Full.pdf
80/245
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Variables and constant
Primary data type
Array Pointer - String
Data structure: enum union - struct
Function
Namespace
80
-
7/23/2019 GettingStartedCpp - Full.pdf
81/245
C/C++ function
function_name([ ], [])
voidfoo() {}
voidfoo(int a, int b, char c){}
intfoo()
{return 1;
}
No return function
Required return
81
-
7/23/2019 GettingStartedCpp - Full.pdf
82/245
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 value
Use b, c as default value
No default value
Use b, c as default value
0 1 2
0 10 2
0 10 100
Command prompt
82
-
7/23/2019 GettingStartedCpp - Full.pdf
83/245
void foo(int a, int b = 1, int c )
{
printf("%d %d %d\n", a, b, c);
}
Default parameters (cont.)
ERROR
error C2548: 'foo' : missing default
parameter for parameter 3
When a parameter is set default value, the
rest of next parameters MUST BE set
default value too
RULES
83
V i bl b f
-
7/23/2019 GettingStartedCpp - Full.pdf
84/245
Variable number of
parameters#include#include
int sum(int num_param, ... ){
int sum = 0, val = 0;
va_listmarker;va_start(marker, num_param);for (registerint 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
-
7/23/2019 GettingStartedCpp - Full.pdf
85/245
Parameter classification
Value parameter
Reference parameter
Constantparameter
Const Referenceparameter
Pointer parameter
85
-
7/23/2019 GettingStartedCpp - Full.pdf
86/245
Parameter classification
Pass-by-value
A copy of parameter is madeValue parameter
Reference parameter
Constant parameter
Const Referenceparameter
Pointer parameter
void foo(int n)
{
n++;
}
void main()
{
int x = 2;
foo(x);
printf("%d\n", x);
}
x = 2
2x2x
2n
2x
3n2x
foo86
-
7/23/2019 GettingStartedCpp - Full.pdf
87/245
Parameter classification
Pass-by-reference
Actually parameter itself is passed
Use reference operator &
Value parameter
Reference parameter
Constant parameter
Const Referenceparameter
Pointer parameter
void foo(int&n){
n++;
}
void main()
{
int x = 2;
foo(x);
printf("%d\n", x);
}
x = 3
2x 2x
n
x3
n3x
foo87
-
7/23/2019 GettingStartedCpp - Full.pdf
88/245
Parameter classification
Pass-by-value
A copy of parameter is made andstrict as const.
Value parameter
Reference parameter
Constant parameter
Const Referenceparameter
Pointer parameter
void foo(int cont n)
{
n++;
}
void main()
{
int x = 2;
foo(x);
printf("%d\n", x);
}
Fail, can not
modified
const value
2x2x
2n
2x
3n
foo88
-
7/23/2019 GettingStartedCpp - Full.pdf
89/245
Parameter classification
Pass-by-ref
Actually parameter itself is passed but
avoid modify
Void the overhead of creating a copy
Value parameter
Reference parameter
Constant parameter
Const Referenceparameter
Pointer parameter
void foo(int const &n)
{
//todo
}
89
-
7/23/2019 GettingStartedCpp - Full.pdf
90/245
Parameter classification
In common, Pass-by-value
A copy of parameter is madeValue of parameter is an address of a
memory block
Value parameter
Reference parameter
Constant parameter
Const Referenceparameter
Pointer parameter
void foo(int *n)
{
//todo
}
Value of parameter will not bechange,
but memory block which pointed
by parameter could be modified.90
-
7/23/2019 GettingStartedCpp - Full.pdf
91/245
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);
}
A
B
A
B
A
B
A
B
Copy value
(addr. of data)
foo
0x29faa8 0x29faa00x29faa8 0x29faa0
Command prompt
91
-
7/23/2019 GettingStartedCpp - Full.pdf
92/245
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]);
}
A
A
foo
12
3A[2] = 10 10
A
A[2] = 3
A[2] = 10
Copy value
(addr. of data)
92
-
7/23/2019 GettingStartedCpp - Full.pdf
93/245
Pointer reference parameter
A special case of pointer parameter
Value of pointer parameter (address of block memory) could be changed
Pass-by-reference
CAN NOT work with array directly
#include
void foo(int*&A, int*&B){
int *tmp = A; A = B; B = tmp;
}
void main()
{
int arr1[] = {1, 2, 3};int arr2[] = {10, 11};
int *A = arr1;
int *B = arr2;
printf("0x%x 0x%x\n", A, B);
foo(A, B);
printf("0x%x 0x%x\n", A, B);
}
A
B
A
B
A
B
A
B
foo
0x31fc90 0x31fc880x31fc88 0x31fc90
Command prompt
93
-
7/23/2019 GettingStartedCpp - Full.pdf
94/245
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
-
7/23/2019 GettingStartedCpp - Full.pdf
95/245
Function Prototype
In C/C++, functions MUST BE declare before using.
To solve this problems Keep all functions in correct order
Use prototype inside .cpp file
Use prototype inside header (.h) file -> recommend
#include"header.h"void Todo1()
{
Todo2();
}
void Todo2(){}
int main(){}
Main.cpp
void Todo1()
{
Todo2();
}void Todo2()
{}
int main()
{}
Error
error C3861:'Todo2': identifier
not found
Main.cppheader.h
void Todo1();
void Todo2();
95
-
7/23/2019 GettingStartedCpp - Full.pdf
96/245
Extern function
Sometimes, we need to use a function in another
module (.cpp file)
Header file is too complicated to use (caused error
when used)
#include
externvoid TodoExtern();
int main(){
TodoExtern();
return 1;
}
Main.cpp
#include
void TodoExtern()
{printf("TodoExtern\n");
}
Extern.cpp
96
-
7/23/2019 GettingStartedCpp - Full.pdf
97/245
Extern C
Name mangling:
Aka name decoration
The way of encoding additional information in a name offunction, struct, class
In C++:
For adapting overload, class/struct functions, name offunction will be encoding
int f (void) { return 1; }
int f (int) { return 0; }
int __f_v (void) { return 1; }
int __f_i (int) { return 0; }97
-
7/23/2019 GettingStartedCpp - Full.pdf
98/245
Extern C
For mixing C and C++ source (Object C also) use extern"C"
Extern C talk to compiler that use C style for its scope No name mangling
No overloading
Extern C is also extern function could be implement in another module
#include
void ExternC()
{printf("ExternC\n");
}
Ansi_c.cextern"C"
{
void ExternC();
void Todo()
{
printf("%d", i);
}
}
C_plusplus.cpp
98
-
7/23/2019 GettingStartedCpp - Full.pdf
99/245
Extern C in practice
#ifdef__cplusplusextern"C" {
#endif
// your code here
#ifdef__cplusplus}
#endif
__cplusplus: default C++ preprocessor definition
99
-
7/23/2019 GettingStartedCpp - Full.pdf
100/245
Pointer to function
A variable store address of a function
Advantage
Flexible
User for event handling mechanism
// C
void DoIt (float a, char b, charc){}void (*pt2Function)(float, char, char) = DoIt;
// using
pt2Function(0, 0, 0);
100
-
7/23/2019 GettingStartedCpp - Full.pdf
101/245
Inline function
Macro: preprocessor replaces all macro calls directly
with the macro code
101
#define NEXT(a) (a+1)
int main(){
printf("%d", NEXT(1));
}
int main(){
printf("%d", (a + 1));
}
-
7/23/2019 GettingStartedCpp - Full.pdf
102/245
Inline function (cont)
Like macro, but obeys C/C++ syntax
102
inlineint Next(int x)
{
return x + 1;
}
int main()
{
printf("%d", Next(1));
}
For OOP, Inline function is allowed to set access privilege
Improve performance (for short/simple inline functions)
NOTE: The compiler is not forced to inline anything at all
Why
performance isimproved?
-
7/23/2019 GettingStartedCpp - Full.pdf
103/245
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Variables and constant
Primary data type
Array Pointer - String
Data structure: enum union - struct
Function
Namespace
103
-
7/23/2019 GettingStartedCpp - Full.pdf
104/245
Namespace
A abstract container uses for grouping source code.
In C++, a namespace is defined with a namespace
block
namespacemaths {voidsin() {}voidcos() {}voidadd() {}
}
namespacematrix {voidmult() {}voidadd() {}
}
104
-
7/23/2019 GettingStartedCpp - Full.pdf
105/245
Using namespace
For using methods, variables, of a namespace:
::
namespacemaths {
voidsin() {}voidcos() {}voidadd() {}
}
namespacematrix {voidmult() {}voidadd() {}
}
voidmain(){
maths::sin();
matrix::add();
}105
-
7/23/2019 GettingStartedCpp - Full.pdf
106/245
Using namespace
Use using namespace for shorten way.
namespacemaths {voidsin() {}voidcos() {}
voidadd() {}}namespacematrix {
voidmult() {}voidadd() {}
}
using namespace maths;
using namespace matrix;voidmain(){
sin();
mult();
}
106
-
7/23/2019 GettingStartedCpp - Full.pdf
107/245
Namespace ambiguous call
More than two definition ofaddfunctions
maths::add()
matrix::add()
ambiguous call fatal error.
In this case, MUST BE specify
namespace.
namespace maths
{
void add();
}
namespace matrix{
void add();
}
usingnamespace maths;
usingnamespace 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
-
7/23/2019 GettingStartedCpp - Full.pdf
108/245
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Class & Object
Inheritance
Polymorphism
Operator overloading
Class static member108
-
7/23/2019 GettingStartedCpp - Full.pdf
109/245
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Class & Object
Inheritance
Polymorphism
Operator overloading
Class static member109
-
7/23/2019 GettingStartedCpp - Full.pdf
110/245
ClassAs same as structDefault access is private
110
class MyClass
{
public:
MyClass();
~MyClass();
protected:
int GetVal() {return m_Var;}
void Todo();
private:
int m_Var;
void SayHello();
};
void MyClass::Todo()
{
//some code here
}
Class name
Access methods
Constructor
Destructor
Function (methods)
Inline methods
Class variable (property)
Function implementation
-
7/23/2019 GettingStartedCpp - Full.pdf
111/245
Class (cont)
In traditional, code of class is divided into 2 parts
Declaration: in .h file
Implementation: in .cpp file
111
#ifndef__CCLASS_H__#define__CCLASS_H__class CClass{
public:CClass();
~CClass();private:
void Toso() ;
};
#endif
Any_name.h#include "Any_name.h"voidCClass::Todo(){
}
CClass::~CClass(){
}
Any_name.cpp
-
7/23/2019 GettingStartedCpp - Full.pdf
112/245
How to use class
112
MyClass objA; //or MyClass objA()
objA.SayHello();
Create a object directly
Access class methods,
properties by using dot
Create a object through pointer. Two ways to use methods,
properties
o (*objA). C style
o objA-> C++ style
Supported polymorphism
MyClass *ObjB = new MyClass;//or MyClass *ObjB = new MyClass();
(*objA).SayHello();
objA->SayHello();
Recommend!
MyClass *ObjB = new MyClass;
objA->SayHello();
-
7/23/2019 GettingStartedCpp - Full.pdf
113/245
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
http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) -
7/23/2019 GettingStartedCpp - Full.pdf
114/245
Constructor
Should be public
Called when an instance is created
A class could define a set of constructors (constructor
overloading)
114
class MyClass
{
public:
MyClass();
MyClass(MyClass* A);
MyClass(const MyClass& A);
MyClass(int val);
}
Default constructor
Copy constructor.
-
7/23/2019 GettingStartedCpp - Full.pdf
115/245
Copy constructor
Definition:
A constructor with the same name as the class
Used to make a deep copy of objects (be careful if class
content pointer properties)
115
If no user-defined constructor is defined, compiler definesone.
X (const X& copy_from_me)
X (X* copy_from_me)
X (X& copy_from_me)
X (const X©_from_me, int = 10, float = 1.0 )
Must be set default value
C ( )
-
7/23/2019 GettingStartedCpp - Full.pdf
116/245
Copy constructor (cont.)
Invoked when
When a object is created
from another object of
the same type When an object is
passed by value as
parameter to function
When a object is return
from a function
116
class ABC{
public:
ABC(){}
ABC(ABC *A){printf("here1\n");}
ABC(const ABC &A)
{
printf("here2\n");
}};
void Foo1(ABC A){}
ABC Foo2()
{
ABC a;
return a;
}int main()
{
ABC *A = new ABC();
ABC B(A);
Foo1(A);
Foo2();
}
C ( )
-
7/23/2019 GettingStartedCpp - Full.pdf
117/245
Copy constructor (cont)
A default copy constructor is created automatically,
but it is often not what you want.
117
Image(Image *img) {
width = img->width;
height = img->height;data = new int[width*height];
for (int i=0; idata[i];
}
Image(Image *img) {
width = img->width;
height = img->height;data = img->data;
}
Automatic generated copy constructor User-defined (expected) copy contructor
E li i
-
7/23/2019 GettingStartedCpp - Full.pdf
118/245
Explicit constructor
"nonconverting"
Explicit constructor syntax is required.118
class A {
public:
explicit A(int) {}};
void f(A) {}
void g()
{
A a1 = 37;
A a2 = A(47);
a1 = 67;
f(77);
}
Without explicit With explicit
D
-
7/23/2019 GettingStartedCpp - Full.pdf
119/245
Destructor
Automatically invoked whenan object is destroy:
Out of scope
Or manually free (usepointer)
Use for collect class memory
119
class MyClass{
char m_Var;
int m_pData;
public:
MyClass(char id) {
m_Var = id;
m_pData = new int[100];
};
~MyClass() {delete m_pData;
cout
-
7/23/2019 GettingStartedCpp - Full.pdf
120/245
this pointer
A special pointer point to class instance itself
Used inside class, for access class methods, properties
120
class MyClass
{
char m_Var;public:
MyClass(char id) {m_Var = id;};
~MyClass() {}
MyClass* Todo1(int val)
{
if (this->m_Var == val)
{
return this;}
return 0;
}
void Todo2()
{
this->Todo1('A');
}
};
M b i i i li i
-
7/23/2019 GettingStartedCpp - Full.pdf
121/245
Member initialization
121
class MyClass
{
private:
int m_iVar1;
float m_fVar2;
char * m_pVar3;public:
MyClass();
}
MyClass::MyClass():
m_iVar1(10),
m_fVar2(1.3f),m_pVar3(0)
{
}
Setup value of properties
O tli
-
7/23/2019 GettingStartedCpp - Full.pdf
122/245
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Class & Object
Inheritance
Polymorphism
Operator overloading
Class static member122
I h it
-
7/23/2019 GettingStartedCpp - Full.pdf
123/245
Inheritance
Code reuse:
Composition: create objects of existing class inside the
new class
Inheritance: create a new class as a type of an existing
class
123
Existing class
New class
class NewClass
{
public:
ExistingClass *m_member;
};
Base class
Derive classHierarchy model
class Derive: public Base
{
};
I h it t
-
7/23/2019 GettingStartedCpp - Full.pdf
124/245
Inheritance syntax
124
class Derive: public Base
{
public:
Derive():Base() {}
void Todo();
};
void Derive::Todo()
{
this->protectedFunc();
this->publicFunc();
this->privateFunc();
Base::Todo();
}
class Base
{
public:
Base() {}
void publicFunc() {}
void Todo() {}
protected:
void protectedFunc() {}
private:
void privateFunc() {}
};
FAIL: cannot access private member
Access bases method (same name)
Constructor init
I h it
-
7/23/2019 GettingStartedCpp - Full.pdf
125/245
Inheritance access
Base access Inherit access Derive access
Public
Public
Public
Protected Protected
Private PrivatePublic
Protected
Protected
ProtectedPrivate
Private
Public
Private privateProtected
Private
125
Inheritance access
-
7/23/2019 GettingStartedCpp - Full.pdf
126/245
Example
126
class CAnimal
{
public:
void Drink();
protected:
void Run();
private:void Eat();
};
class CRabbit: private CAnimal
{
public:
CRabbit(){
Run();
Eat();
Drink();
}
};
void main()
{
CRabbit rab;
rab.Drink();
rab.Eat();rab.Run();
}Why?
Constructor Destructor
-
7/23/2019 GettingStartedCpp - Full.pdf
127/245
Inheritance
127
Animal
Mammal
Lion
Lion *theLion = new Lion()
Lion()
Animal()
Mammal()
delete theLion;
~Lion()
~Mammal()
~Animal()
M lti l i h it
-
7/23/2019 GettingStartedCpp - Full.pdf
128/245
Multiple inheritance
A class could be inherit from multiple base class
128
Human
StreetMusician
Musician Worker
class Human{};
class Musician
{
public:
Musician(int instrument, int year){}};
class Worker
{
public:
Base2(int level){}
};
class StreetMusician: public Human,protected Musician,
private Worker
{
public:
StreetMusician(): Human(),
Musician(1, 1),
Worker(10) {}
};
Inheritance
-
7/23/2019 GettingStartedCpp - Full.pdf
129/245
Ambiguous access
CBase1::Hello()
CBase2::Hello()
129
class CBase1
{
public:
void Hello();
};
class CBase2
{
public:
void Hello();
};
class CDerive: CBase1, CBase2
{
public:
CDerive(): CBase1(), CBase2()
{
Hello();}
};
Ambiguous access of'Hello
How to
solve?
Outline
-
7/23/2019 GettingStartedCpp - Full.pdf
130/245
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Class & Object
Inheritance
Polymorphism
Operator overloading
Class static member130
Polymorphism
-
7/23/2019 GettingStartedCpp - Full.pdf
131/245
Polymorphism
Implemented in C++ with virtual functions
Virtual function
Pure virtual function
Pure virtual class (abstract class / base class)
Use for improved code organization
Extensible
131
Function call binding
-
7/23/2019 GettingStartedCpp - Full.pdf
132/245
Function call binding
Binding:
Connecting a function call to a function body
Early binding:
Binding is performed before the program is run by compiler,linker
Late binding:
Binding occurs at runtime, based on the type of the object
Aka Dynamic binding or Runtime binding
For C++, to cause late binding, use keyword virtual
132
Overriding vs Overloading
-
7/23/2019 GettingStartedCpp - Full.pdf
133/245
Overriding vs. Overloading
Overriding: override a
bases virtual or non-
virtual methods
Overloading: several
methods with the same
name which differ from
parameters
133
class Animal{
public:
virtualvoid Eat(){}
void Run(){}
};
class Cat: public Animal{
public:
//overiding
void Eat(){}
void Run(){}
//overloading
void Jump();
void Jump(int distance);
};
Virtual Overriding vs.
non-virtual Overriding
class Animal
{
public:
virtualvoid Eat()
-
7/23/2019 GettingStartedCpp - Full.pdf
134/245
Obj is a Animal pointer, but
really a Cat instant
Without virtual (early binding),Animal:Run was called instead
ofCat::Run
134
{
cout
-
7/23/2019 GettingStartedCpp - Full.pdf
135/245
destructor
When obj is freed, both
itself and base MUST BE
deleted
Its ok for obj1, but
problem for obj2
135
{
cout
-
7/23/2019 GettingStartedCpp - Full.pdf
136/245
( )
To solve this problem,
use virtual destructor
136
{
cout
-
7/23/2019 GettingStartedCpp - Full.pdf
137/245
Pure virtual classPure 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 classMUST implements all pure virtual
functions
137
class Base
{
public:
virtualvoid Todo() = 0;
};
class Derive: public Base
{
void Todo() {}
}
Outline
-
7/23/2019 GettingStartedCpp - Full.pdf
138/245
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Class & Object
Inheritance
Polymorphism
Operator overloading
Class static member138
Operator overloading
-
7/23/2019 GettingStartedCpp - Full.pdf
139/245
Operator overloading
Another way to make a function call
Define function of operator such as : +, -, *, /,
WARNING: Not recommend to use. Its easy to read,
but hard to debug !
139
Operator overloading
-
7/23/2019 GettingStartedCpp - Full.pdf
140/245
example
140
class Integer
{
public:
int i;
Integer(int ii) : i(ii) {}
const Integer operator+(const Integer& rv)
{
return Integer(i - rv.i);}
Integer& operator+=(const Integer& rv)
{
i *= rv.i;
return *this;
}
};
int main()
{
Integer ii(1), jj(2), kk(3);
kk += ii + jj;
cout
-
7/23/2019 GettingStartedCpp - Full.pdf
141/245
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Class & Object
Inheritance
Polymorphism
Operator overloading
Class static member141
Static function
-
7/23/2019 GettingStartedCpp - Full.pdf
142/245
Static function
Allow user invokes
without creating an
instance
Declaration with statickeyword
No need to create
object, but must be
declared class name
142
class MyClass
{
public:
staticvoid Todo();
};
void MyClass::Todo()
{
//implemetation
}
int main()
{
MyClass::Todo();
}
Static variable
-
7/23/2019 GettingStartedCpp - Full.pdf
143/245
Static variable
Same as static function
Value of static variable
MUST BE set outside
class declaration.
143
class MyClass {
public:
staticint s_Var;
};
int MyClass::s_Var = 99;
int main()
{
printf("%d",
MyClass::s_Var);}
Lazy initialization
-
7/23/2019 GettingStartedCpp - Full.pdf
144/245
y
0The tactic of delaying the
creation of an object,
calculation of a value, or
some other expensiveprocess until the first
time it is need.
144
class ExpensiveRes
{public:
ExpensiveRes() {}
void todo1();
static ExpensiveRes* GetInstance();
private:
static ExpensiveRes* s_Instance;
};
ExpensiveRes* ExpensiveRes::s_Instance = 0;ExpensiveRes* ExpensiveRes::GetInstance()
{
if (!s_Instance)
{
s_Instance = new ExpensiveRes();
}
return s_Instance;}
int main()
{
ExpensiveRes::GetInstance()->todo1();
ExpensiveRes::GetInstance()->todo1();
}
Outline
-
7/23/2019 GettingStartedCpp - Full.pdf
145/245
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Recall pointer
Memory leak
145
Question?
-
7/23/2019 GettingStartedCpp - Full.pdf
146/245
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
-
7/23/2019 GettingStartedCpp - Full.pdf
147/245
What does memory leak
mean ?First, How is memory structure ?
147
-
7/23/2019 GettingStartedCpp - Full.pdf
148/245
How is memory structure ?STACK vs HEAP
148
Run-time storage
-
7/23/2019 GettingStartedCpp - Full.pdf
149/245
Run time storage
Code segment:
where the compiled program sits inmemory
Global area:
store global variables
Stack segment:
where parameters and local variables areallocated
Heap segment:
where dynamically allocated variables areallocated
149
Text segment
(Code segment)
Stack segment
Heap Segment
Global area
Stack
-
7/23/2019 GettingStartedCpp - Full.pdf
150/245
Stack
Where parameters and local
variables are allocated
Limited sizeStack
overflowMemory use in stack is
temporary and auto release
Fast processing/low size
150
Parameters
Return Addresswhere to begin execution
when function exits
Dynamic linkpointer to caller's stack
frame
Static linkpointer to lexical parent
(for nested functions)
Return value
Local variables
Concept Stack frame
Text segment
(Code segment)
Stack frame
Heap Segment
Global area
Stack frame
Heap
-
7/23/2019 GettingStartedCpp - Full.pdf
151/245
Heap
Large pool of memory
Dynamic allocation
Stays allocated untilspecifically deallocated
leak!Must be accessed through a
pointer
Large arrays, structures, orclasses should be storedHeapwhy?
Large & dynamic
151
Parameters
Return Addresswhere to begin execution
when function exits
Dynamic linkpointer to caller's stack
frame
Static linkpointer to lexical parent
(for nested functions)
Return value
Local variables
Concept Stack frame
Text segment
(Code segment)
Stack frame
Heap Segment
Global area
Stack frame
Heap vs Stack
-
7/23/2019 GettingStartedCpp - Full.pdf
152/245
Heap vs Stack
int_array[10]; stored in stack
152
Stack
_array
int*_array = new int[n]
Pointer _array is stored in Stack Data of array is stored in Heap
_array0x00FF
Stack10
Heap
0x00FF
0x0005
Value of:
_array : address where int point into in heap (0x00FF) (*_array): value at it's address on heap (10) (&_array): address of the memory which used for stored pointer
_array in stack (0x0005)
FAQ
-
7/23/2019 GettingStartedCpp - Full.pdf
153/245
FAQ
Why we use
Classname *Obj = new Classname();
instead of Classname Obj;
153
-
7/23/2019 GettingStartedCpp - Full.pdf
154/245
Memory leak overview
154
What does memory leaking
-
7/23/2019 GettingStartedCpp - Full.pdf
155/245
mean?Definition:
Particular type of unused memory, unable to release
Common:
Refer to any unwanted increase in memory usage* usually for heap memory
155
void Leak()
{
int *A = newint[1000];
// some code here// ...
// without delete A
//
return;
}
4000 bytes
Return without free A Leak
What does its consequences ?
-
7/23/2019 GettingStartedCpp - Full.pdf
156/245
What does its consequences ?
Application gets slow fps
Application is crashed
Device has been freeze, restarted
156
-
7/23/2019 GettingStartedCpp - Full.pdf
157/245
Why does memory leak
happen?First, Let's see some examples
157
Example 0
-
7/23/2019 GettingStartedCpp - Full.pdf
158/245
Example 0 Forget to release resources
No GC mechanic supported
Button is
pressed
Save current floor
On target
floor ?
Wait until lift is idle
Go to required
floor
Release memory used to
save current floor
True
Finished Memory
Leaking
here
158
C/C++ Example 1
-
7/23/2019 GettingStartedCpp - Full.pdf
159/245
void Fa()
{
}
void Fb()
{}
void Leak(){
int *a = newint[10];
Fa();
Fb();
return;
}
void main()
{
Leak();
}
C/C Example 1
Leak memory
caused by
lacking of releasedynamic memory
delete a[];
return;
Solution
Leak !
159
C/C++ Example 2
-
7/23/2019 GettingStartedCpp - Full.pdf
160/245
C/C Example 2
voidleak()
{
int **list = newint*[10];
for (int i = 0; i < 10; i++){
list[i] = newint;
}
delete list;
return;
}
Allocation a series,delete only one unit
Leak !for (int i = 0; i < 10; i++){
delete list[i];
}
delete list;
Solution
160
C/C++ Example 3
-
7/23/2019 GettingStartedCpp - Full.pdf
161/245
C/C Example 3
Leak memory when
using pointer-return-
type
delete []str;
Avoid to call directly GenString()
Solution
161
char* GenString()
{
char *a = newchar[10];
a[9] = '\0';
return a;
}
void Leak()
{
char *str = GenString();
printf("%s\n", str);
printf("%s\n", GenString());}
C/C++ Example 4
-
7/23/2019 GettingStartedCpp - Full.pdf
162/245
#include
void Foo(){
int* a = newint[100];
a = newint[1000];
}
void Foo1()
{int* a = newint[100];
int* b = newint[1000];
a = b;
}
C/C Example 4Leak memory because ofmisunderstanding = operator in
C++
Stack
Heap
A
LEAK!
162
Leak!
C/C++ Example 5
-
7/23/2019 GettingStartedCpp - Full.pdf
163/245
/ p
void main()
{
Classname *A = new A();
...
...
//free A
A = NULL;
}
163
Misunderstand free memory methodin C/C++
Stack
Heap
A
NULL
LEAK!
Keep in mind we are using C/C++
Use MACRO for safe deallocating
#define SAFE_DEL(a) {if(a){delele a;a = 0;}}
Solution
C/C++ Example 6 - STLclass Element
{
int ID;Created 0 addr 0xa719c0
d 1 dd 0 81 18
Command prompt
-
7/23/2019 GettingStartedCpp - Full.pdf
164/245
164
;
public:
Element(int id)
{printf("Created %d at 0x%x\n", id, this);
ID = id;
}
~Element()
{
printf("Destroy %d at 0x%x\n", ID, this);
}};
int main()
{
list m_List;Element *e0 = new Element(0);Element *e1 = new Element(1);//add to list
m_List.push_back(e0); m_List.push_back(e1);//clear list
printf("-----Before clear-----\n");
m_List.clear();
printf("-----After clear-----\n");
return 0;
}
Created 1 addr 0xa81a18
-----Before clear-----
-----After clear-----
Memory
leak here
list
Item 0
Item 1
e0
e1
C/C++ Example 6 STL
( t )
-
7/23/2019 GettingStartedCpp - Full.pdf
165/245
(cont.)
165
int main()
{
list m_List;
Element *e0 = new Element(0);
Element *e1 = new Element(1);
//add to list
m_List.push_back(e0);m_List.push_back(e1);
//clear list
printf("-----Before clear-----\n");list ::iterator i;for (i = m_List.begin(); i != m_List.end(); i++){
delete *i;}m_List.clear();
printf("-----After clear-----\n");
return 0;
}
Free data of each
element pointer
Created 0 addr 0xb61a28
Created 1 addr 0xb71a70
-----Before clear-----
Destroy 0 addr 0xb61a28
Destroy 1 addr 0xb71a70-----After clear-----
Command prompt
Example 7
-
7/23/2019 GettingStartedCpp - Full.pdf
166/245
p
166
class CB {
public:
CB(){
m_iVal = 0;
}
~CB(){}
int m_iVal;
};
class CA {
public:
CA(){
m_pB = 0;
}
~CA(){
delete m_pB;
m_pB = 0;
}
CB *m_pB;
};
int main()
{
CB *B = new CB;
CA *A = new CA();
A->m_pB = B;
delete(A);
printf("%d", B->m_iVal);
}
B
Am_pB
Access violationreading location
.
Try toremove
delete m_pB
Example 7 (cont.)
-
7/23/2019 GettingStartedCpp - Full.pdf
167/245
p ( )
167
class CB {
public:
CB(){
m_iVal = 0;
}
~CB(){}
int m_iVal;
};
class CA {
public:
CA(){
m_pB = 0;
}
~CA(){
delete m_pB;
m_pB = 0;
}
CB *m_pB;
};
int main()
{
CA *A = new CA();
A->m_pB = new CB()
delete(A);
}
Am_pB
Leak
Delete or not?
Use manual delocate m_pB
Solution
C/C++ Example 8
-
7/23/2019 GettingStartedCpp - Full.pdf
168/245
class cA()
{
public :cA() {m_pdata = newint[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 finalizationmethod
Without virtual, in this case,m_pdata is not deleted leak
Be careful with virtual for
finalization method
Solution
168
C/C++ Example 9
-
7/23/2019 GettingStartedCpp - Full.pdf
169/245
/ p
Using new vs free. Nodestructor will be invokedafter free
169
class MyClass{
public
MyClass()
{
m_pdata2 = newint[100];
}~ MyClass()
{
delete []m_pdata2;
}
int *m_pdata2;
}
void main()
{
MyClass* p = new MyClass();
free(p);
}Leak here
What are reasons of memory
l k?
-
7/23/2019 GettingStartedCpp - Full.pdf
170/245
leak?Forget/ misunderstand C/C++ mechanism
Out-of-Control (logic)
170
Current Solutions
-
7/23/2019 GettingStartedCpp - Full.pdf
171/245
For Forget/ misunderstand C/C++ mechanism
Semi-automatic memory management
oReference Counting
Automatic memory managementoTracing Garbage Collection (GC): Java , C #
No GC mechanic for C/C++
171
Reference Counter: Good or bad ?
-
7/23/2019 GettingStartedCpp - Full.pdf
172/245
Reference counter:Simple method formemory conflictresolution
Algorithms:
Increase counter whenuse as reference
Decrease when release
Delete memory ofcounter is zero
172
class IShareMem{
public:
IShareMem():m_iRefCounter(1){}
virtual ~IShareMem(){}
static
IShareMem* SetReference(IShareMem* src)
{
src->m_iRefCounter++;return src;
}
void Release()
{
m_iRefCounter--;
if (m_iRefCounter
-
7/23/2019 GettingStartedCpp - Full.pdf
173/245
Good:
o Avoid conflict in memory usage. (See example no.7)
Bad:o Cause memory leak ifuser forget to release
o Hard to detect memory leak
o CAN NOT DETECT by tool
173
Current Solutions -
Disadvantage
-
7/23/2019 GettingStartedCpp - Full.pdf
174/245
DisadvantageGarbage collectors generally can do nothing about
logical memory leaks
174
0
1
2
n
..
.
Alloc
Alloc
Alloc
Alloc
Which is really needed?A
B
D
E
Z
Do I alloc some-
where without
release?
Somethings else
is pointed
to an object
C/C++
How to avoid detect?
-
7/23/2019 GettingStartedCpp - Full.pdf
175/245
How to avoid, detect?Rule:
o Remember to release dynamic data (pointer) HARD
o Keep our resource in well controlled TOO HARD
Detect
o By phenomenon on device ? not exactly
o By review source ? TOO HARD
o By tool
VC++ memory leak debugging
External toolo Cannot detect some cases.
175
C/C++
How to solve?
-
7/23/2019 GettingStartedCpp - Full.pdf
176/245
How to solve?Easy to detect, but hard to solve
Depend on kind of memory leak
Experience
Organize source and keep it in control Such as a document about resource ?!?
176
-
7/23/2019 GettingStartedCpp - Full.pdf
177/245
Detect Memory Leak
177
Memory leak quick detection
-
7/23/2019 GettingStartedCpp - Full.pdf
178/245
0Windows: use task manager / process tab
0Android:adb shell top -m
See VSS, RSS
178
Use Visual studio supported
function
-
7/23/2019 GettingStartedCpp - Full.pdf
179/245
functionUse __CrtDumpMemoryLeaks
Advantageo Easy to use
o Fully report about leak when application completed
o Free
Disadvantageo Cannot detect run-time
o Fail if application Crashed
Presentation:o Manually coding by user
o Use some lib such as VLD
179
Debug in Visual studio
-
7/23/2019 GettingStartedCpp - Full.pdf
180/245
180
VLD Tool
-
7/23/2019 GettingStartedCpp - Full.pdf
181/245
http://www.codeproject.com/KB/applications/visual
leakdetector.aspx
http://vld.codeplex.com/
Include vld.h in source
Add vld.lib
181
#include"vld.h"
#pragmacomment(lib, "vld.lib")
VLD Tool
http://www.codeproject.com/KB/applications/visualleakdetector.aspxhttp://www.codeproject.com/KB/applications/visualleakdetector.aspxhttp://vld.codeplex.com/http://vld.codeplex.com/http://vld.codeplex.com/http://www.codeproject.com/KB/applications/visualleakdetector.aspxhttp://www.codeproject.com/KB/applications/visualleakdetector.aspxhttp://www.codeproject.com/KB/applications/visualleakdetector.aspx -
7/23/2019 GettingStartedCpp - Full.pdf
182/245
0After finish application normally, memory leakinformation will be display in output
182
WARNING: Visual Leak Detector detected memory leaks!
---------- Block 3 at 0x006F4F98: 12 bytes ----------
Call Stack:
c:\users\ricky.ngk\desktop\testleak\testleak\main.cpp (81): TestLeak.exe!Init + 0x7 bytes
c:\users\ricky.ngk\desktop\testleak\testleak\main.cpp (108): TestLeak.exe!mainf:\dd\vctools\crt_bld\self_x86\crt\src\crtexe.c (586): TestLeak.exe!__tmainCRTStartup + 0x19 bytes
f:\dd\vctools\crt_bld\self_x86\crt\src\crtexe.c (403): TestLeak.exe!mainCRTStartup
0x76BBED6C (File and line number not available): kernel32.dll!BaseThreadInitThunk + 0x12 bytes
0x772237F5 (File and line number not available): ntdll.dll!RtlInitializeExceptionChain + 0xEF bytes
0x772237C8 (File and line number not available): ntdll.dll!RtlInitializeExceptionChain + 0xC2 bytes
Data:
74 A7 DF 00 01 00 00 00 20 60 6F 00 t....... .`o.....
0Double click the stack to navigate to source
Debug memory leak run-time
-
7/23/2019 GettingStartedCpp - Full.pdf
183/245
Use some tool, such as:o Glow code: http://www.glowcode.com/
o Memory validator: http://www.softwareverify.com/cpp-memory.php
Advantage
o Runtime checkingo Nice Interface
Disadvantageo Not free
o Not easy to use. Need tutorial
Note: Those tool cannot working well with VLD
183
Outline
http://www.glowcode.com/http://www.softwareverify.com/cpp-memory.phphttp://www.softwareverify.com/cpp-memory.phphttp://www.softwareverify.com/cpp-memory.phphttp://www.softwareverify.com/cpp-memory.phphttp://www.glowcode.com/http://www.glowcode.com/ -
7/23/2019 GettingStartedCpp - Full.pdf
184/245
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Forward declaration
Standard IO Console IO & FILE
Template
Type casting
Exception handling
Endian
STL introduction
GNU GCC/G++ 184
Outline
-
7/23/2019 GettingStartedCpp - Full.pdf
185/245
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Forward declaration
Standard IO Console IO & FILE
Template
Type casting
Exception handling
Endian
Bit processing
STL introduction
GNU GCC/G++ 185
Forward declaration
-
7/23/2019 GettingStartedCpp - Full.pdf
186/245
Declaration of a identifier which not completed
definition
For C/C++, aka function prototype (for function)
186
int first(int x) {
if (x == 0)
return 1;
return second(x-1);
}
int second(int x) {
if (x == 0)
return 0;
return first(x-1);
}
int second(int x);int first(int x) {
if (x == 0)
return 1;
return second(x-1);
}
int second(int x) {
if (x == 0)
return 0;
return first(x-1);
}
Forward declaration
-
7/23/2019 GettingStartedCpp - Full.pdf
187/245
187
ClassA.h ClassB.h#ifndef _CLASSA_H_#define _CLASSA_H_
class ClassA{
public:
ClassA();
ClassB* m_pB;
};
#endif
#ifndef _CLASSB_H_
#define _CLASSB_H_
class ClassB{
public:
ClassB();
ClassA* m_pA;
};
#endif
ClassA.cpp ClassB.cpp#include "ClassA.h"
ClassA::ClassA(){}
#include "ClassB.h"
ClassB::ClassB(){}
Class forward declaration
#include "ClassB.h" #include "ClassA.h"
class ClassB; class ClassA;
Must be pointer
Outline
-
7/23/2019 GettingStartedCpp - Full.pdf
188/245
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Forward declaration
Standard IO Console IO & FILE
Template
Type casting
Exception handling
Endian
Bit processing
STL introduction
GNU GCC/G++ 188
Standard IO
-
7/23/2019 GettingStartedCpp - Full.pdf
189/245
stdio.h
int printf ( const char * format, ... );
Format: %[flags][width][.precision][length]specifier
Write data to stdout and store
189
printf ("Characters: %c %c \n", 'a', 65);
printf ("Decimals: %d %ld\n", 1977, 650000L);
printf ("Preceding with blanks: %10d \n", 1977);
printf ("Preceding with zeros: %010d \n", 1977);
printf ("Some different radixes: %d %x %o %#x %#o \n", 100, 100, 100, 100, 100);
printf ("floats: %4.2f %+.0e %E \n", 3.1416, 3.1416, 3.1416);printf ("Width trick: %*d \n", 5, 10);
printf ("%s \n", "A string");
Standard IO
-
7/23/2019 GettingStartedCpp - Full.pdf
190/245
stdio.h
int scanf( const char * format, ... );
Format: %[flags][width][.precision][length]specifier
Reads data from stdin and store
190
int n;
scanf ("%d",&n);
Standard IO
-
7/23/2019 GettingStartedCpp - Full.pdf
191/245
std::cout
an object of class ostream that represents the standard
output stream
191
cout
-
7/23/2019 GettingStartedCpp - Full.pdf
192/245
0
std::cin
an object of class istream that represents the standardinput stream
192
int input = 0;
cout > input;
cout
-
7/23/2019 GettingStartedCpp - Full.pdf
193/245
193
FILE * fopen ( const char * filename, const char * mode ); Open file
int fclose ( FILE * stream ); Close a file
size_t fwrite ( const void * ptr, size_t size, size_t count,FILE * stream );
Write block of data to stream
size_t fread( void * ptr, size_t size, size_t count, FILE *stream );
Read a block data from stream
int fscanf ( FILE * stream, const char * format, ... ); Read formatted data from stream
int fprintf ( FILE * stream, const char * format, ... ); Write formatted output to stream
int fseek ( FILE * stream, long int offset, int origin ); Reposition stream position indicatorOrigin:
SEEK_SET : beginning of gfile
SEEK_END: end of file
SEEK_CUR: current position
long intftell ( FILE * stream ); Get current position in stream
void rewind( FILE * stream ); Set position indicator to the beginning
File
http://www.cplusplus.com/reference/clibrary/cstdio/fopen/http://www.cplusplus.com/reference/clibrary/cstdio/fopen/ -
7/23/2019 GettingStartedCpp - Full.pdf
194/245
194
#include
int main ()
{
FILE * pFile;
pFile = fopen ("myfile.txt","w");
if (pFile!=NULL){
fprintf (pFile, "example");
fclose (pFile);
}
return 0;
}
Outline
-
7/23/2019 GettingStartedCpp - Full.pdf
195/245
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Forward declaration
Standard IO Console IO & FILE
Template
Type casting
Exception handling
Endian
STL introduction
GNU GCC/G++ 195
Function template
-
7/23/2019 GettingStartedCpp - Full.pdf
196/245
special functions that can operate withgeneric types
Can be adapted to more than one type or class
without repeating code
A set of needed functions will be created whencompile slow down compiling process
196
template function_declaration;
template function_declaration;
Function template
Example 1
-
7/23/2019 GettingStartedCpp - Full.pdf
197/245
Example 1
197
template 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(i,j);
n=GetMax(l,m);
cout
-
7/23/2019 GettingStartedCpp - Full.pdf
198/245
Example 2
198
template U GetMax (U a, V b)
{
return (a>b?a:b);
}
int main()
{
cout
-
7/23/2019 GettingStartedCpp - Full.pdf
199/245
A class can have members that use template
parameters as types
199
template
class mypair
{T values [2];
public:
mypair (T first, T second)
{
values[0]=first; values[1]=second;
}
};
int main(){
return 1;
mypair Pair1(100, 200);
mypair Pair2('A', 'B');
}
Class template
-
7/23/2019 GettingStartedCpp - Full.pdf
200/245
template class mypair
{
T a, b;
public:
mypair (T first, T second) {a=first; b=second;}T getmax ();
};
template T mypair::getmax ()
{
T retval;
retval = a>b? a : b;
return retval;
}
int main ()
{
mypair myobject (100, 75);
cout
-
7/23/2019 GettingStartedCpp - Full.pdf
201/245
Template specializationDefine a different implementation for a template
when a specific type is passed as template parameter
201
// class template:
template
class mycontainer{
T element;
public:
mycontainer (T arg)
{
element=arg;
}
T increase () {return ++element;}};
// class template specialization:
template
class mycontainer {
char element;
public:
mycontainer (char arg)
{
element=arg;
}
char uppercase (){
if ((element>='a')&&(element
-
7/23/2019 GettingStartedCpp - Full.pdf
202/245
New code will be generated while compiling, DO NOT
split a template class into two parts: .h, and .cpp
Easy to use, but not easy to debug/read
202
Mixin
-
7/23/2019 GettingStartedCpp - Full.pdf
203/245
We can implement inheritance delaying the definition
of the base.
203
template
class Mixin : public Base {};
class Base {};
Mixin issue
-
7/23/2019 GettingStartedCpp - Full.pdf
204/245
If the client never calls Todo there is no errormessage!
204
template
class Mixin : public Base
{
public:
void Todo() {Base::Do();}};
class Base
{};
C++ meta programming
-
7/23/2019 GettingStartedCpp - Full.pdf
205/245
Is writing programs that represent and manipulate
other programs (e.g. compilers, program generators,
interpreters) or themselves (reflection).
In C++, meta programming base on: Template
205
Example: Factorial
-
7/23/2019 GettingStartedCpp - Full.pdf
206/245
N! = 1 x 2 x 3 x x N
206
template struct Factorial
{
enum {RET=Factorial::RET*n};
};
// Note: template specializationtemplate struct Factorial
{
enum{RET=1};
};
int main(){
printf("%d", Factorial::RET);
return 1;
}
Outline
-
7/23/2019 GettingStartedCpp - Full.pdf
207/245
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Forward declaration
Standard IO Console IO & FILE
Template
Type casting
Exception handling
Endian
STL introduction
GNU GCC/G++ 207
Type casting
-
7/23/2019 GettingStartedCpp - Full.pdf
208/245
0Convert from specific type to another type
char a = 10;
int b = (int) a;
bool c = a;