GettingStartedCpp PDF
GettingStartedCpp PDF
Preparation
Getting Start
OOP Memory management Rest of C/C++ features Appendix
2
Outline
Preparation
Getting Start
OOP Memory management Rest of C/C++ features Appendix
Hello world
C/C++ files Entry point C/C++ libraries Source compile process
3
Outline
Preparation
Variables and constant Primary data type Array Pointer String Data structure: enum union - struct Function Namespace
4
Getting Start
OOP Memory management Rest of C/C++ features Appendix
Outline
Preparation
Getting Start
OOP Memory management Rest of C/C++ features Appendix
Outline
Preparation
Getting Start
OOP Memory management Rest of C/C++ features Appendix
Outline
Preparation
Forward declaration Standard IO Console IO & FILE Template
Getting Start
OOP Memory management Rest of C/C++ features Appendix
GNU GCC/G++
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
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
10
Hello world
main.cpp # include <stdio.h> void main() { printf("Hello world"); } Use standard IO lib Entry point Print to console screen
11
Outline
Preparation Getting Start OOP Memory management Rest of C/C++ features
Hello world!
C/C++ files Entry point C/C++ libraries Source compile process
12
# include "header.h" void Todo1() { Todo2(); } void Todo2(){} void main() { Todo1(); }
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
Entry point
Form1.cpp void main() { // your code here } Form2.cpp
int main(int n, char ** args) { // your code here }
15
Outline
Preparation Getting Start OOP Memory management Rest of C/C++ features
Hello world!
C/C++ files Entry point C/C++ libraries Source compile process
16
17
C header
<assert.h>
C++ header
<cassert>
<Ctype.h>
<Errno.h> <float.h> <limits.h> <math.h> <setjmp.h> <signal.h> <stdlib.h>
<cctype>
<cerrno> <cfloat> <climits> <cmath> <csetjmp> <csignal> <cstdlib>
<stddef.h>
<stdarg.h> <stdio.h> <string.h> <time.h> <wchar.h> <wctype>
<cstddef>
<cstdarg> <cstdio> <cstring> <ctime> <cwchar> <cwctype>
Standard IO Manipulating several kinds of string Converting between time & date formats
18
Error caused when forget to add .lib file error LNK2019: unresolved external symbol
19
20
21
22
Outline
Preparation Getting Start OOP Memory management Rest of C/C++ features
C/C++ files
Entry point C/C++ libraries Hello world! Source compile process
23
Process
Source .h/.c/.cpp preprocess Preprocessed source Compile
Tools: Visual Studio: cl.exe (Press F7 / F5) GNU GCC: gcc/ g++
.o / .obj (object file)
Executable/ lib
Linker
24
Outline
Preparation Getting Start OOP
Data structure: enum union - struct Variables and constant Primary data type Array Pointer - String
Function Namespace
25
Outline
Preparation Getting Start OOP
Data structure: enum union - struct Variables and constant Primary data type Array Pointer - String
Function Namespace
26
Variable classification
Scope: Local variable Global variable Static variable Storage class specifier auto static register extern
27
Auto variable
As default, a variable is a auto variable
int myVar
current block
29
Static variable
#include <cstdio> static int s_iGlobalStatic; void Foo() { static int s_iLocalStatic; printf("Foo: called %d\n", s_iLocalStatic++); } int main() { int localVar = 1; printf("Main: %d\n", s_iGlobalStatic); Foo(); Foo(); Foo(); return 1; }
Register variable
int main() { int sum = 0; for (register int i = 0; i < 100; i++) { sum += i; } printf("Sum = %d\n", sum);
return 1; }
31
Extern variable
Extern.cpp int m_iExternVar = 100; main.cpp #include <cstdio> extern int m_iExternVar; int main() { printf("Value = %d\n", m_iExternVar); return 1; } Specify that the variable is
Constant
Variable's value is constant To prevent the programmer from modifying
int const k_Hello = 0;
int main() { k_Hello = 10; } Error error C3892: 'k_Hello' : you cannot assign to a variable that is const
33
Outline
Preparation Getting Start OOP
Data structure: enum union - struct Variables and constant Primary data type Array Pointer - String
Function Namespace
34
35
36
sizeof operator
0 Return size (in byte) of a type, data structure, variable
37
Outline
Preparation Getting Start OOP
Data structure: enum union - struct Variables and constant Primary data type Array Pointer - String
Function Namespace
38
Array
Used to store consecutive values of the same data types int b[4] = {1, 2, 3, 4};
n-dimensions array
int b[<s1>][<s2>][<sn>]
Index of array is counted from 0 to (si-1) C/C++ do not handle out-of-range exception
si MUST BE constant
int b[4] = {1, 2, 3, 4}; for (int i = 0; i < 4; i++) { printf("%d\n", b[i]); } printf("%d\n", b[10]);
b[10] = ?
39
Array Assignment
int a[4] = {1, 2, 3, 4};
int a[4] = {1}; int a[] = {1, 2, 3, 4}; int a[4]; a[0] = 1; a[1] = 2; a[2] = 3; a[3] = 4; int a[4]; memset(a, 0, 4*sizeof(int)); a[0], a[1], a[2], a[3] = ?
40
int a[3][2] = {1, 2, 3, 4, 5, 6}; int a[][2] = {1, 2, 3, 4, 5, 6}; int a[3][2]; memset(a, 0, 6*sizeof(int)); int a[3][2] = {
Pointer
Computer's memory is made up of bytes. Each byte has a number, an address, associated with it.
0x01 0x02
0x01 0x02
o i = 1 o &i = 0x01
Pointer (cont.)
For storing address of a variable, use a special type:
pointer
int *pi;
Pointer of a integer variable
char *pc;
Pointer of a char variable
float *pf;
Pointer of a float variable
0x10
0x00
0x00
0x00
0xF1 0xF2
&i
43
Pointer (cont.)
Pointer is also a variable its stored in memory
int i = 10; int *p = &i;
0x2f00002c
i = 10
0x2f00aabb p = 0x2f00002c
Pointer (cont.)
Type of pointer notify that how to get the value
pointed by pointer
0x01 0xcc 0x20 0x3f
0xF1 0xF2
Little Endian
int i = 0x3f20cc01; char *p1 = (char *)&i; short *p2 = (short *)&i; int *p3 = &i;
P1
P2
P3
45
bits)
--
p--;
0x01
0xcc
0x20
0x3f
0x00 0x05
0x10 0x06
0xaa 0x07
0x01
0xcc
0x20
0x3f
0x00
0x10
0xaa
0x01
0x02
0x03 0x04
0x01 0x02
0x06 0x07
p1
p1+1
p1+5
p2
p2+1
p2+3
47
char *p1;
short *p2;
a
a = ? &a = ? *a = ? p = ? &p = ? *p = ? p + 1 = ? (*p) + 1 = ? *(p + 1) = ? &p + 1; &a + 1 a++; a = ? p++; p = ?
48
Pointer to pointer
Recall that, a pointer variable is a variable. To store address of a pointer variable, we use pointer-
to-pointer variable.
int iVar = 10; int *p1 = &iVar; int **p2 = &p1;
0x100
iVar = 10
0x200
p1 = 0x100 p2 = 0x200
49
0x300
Dynamic allocation
User pointer Allocation a block of memory in heap high capacity Clean up easily
delete p;
Free memory block pointed by p
nx4 bytes
50
51
Delete all cA
52
int **p; p = new int*[2]; *(p+0) = new int; *(p+1) = new int;
0x300
0x500
0x200 0x300
0x900
p = 0x500
*(*(p + i) +j ) p[i][j]
53
stack
P = 0x2f330000
int main() { int *p = new int [3]; p[0] = 1; *(p + 1) = 12; p[2] = 5 }
heap 1 12 5
0x2f330000
0x2f330004
0x2f330008
54
Array is a pointer
10 20 30
p+1
&a + 1
1 a
2 3
a+1
Command prompt a = a+1 = &a = &a+1= 0x26FE6C 0x26FE6D 0x26FE6C 0x26FE6F p p+1 &p &p+1 = = = = 0x0E1AF0 0x0E1AF1 0x26FE70 0x26FE74
&p + 1
56
FAIL
OK
FAIL
OK
57
pointer-to-pointer
int **p = new int*[2]; p[0] = new int[3]; p[1] = new int[3];
Block 0
Block 1
p
[0][0] [1][0] [0][1]
[1][1]
p[0]
p[1]
p[0][0]
p[0][1]
p[0][2]
[0][2] [1][2]
p[1][0]
p[1][1]
p[1][2]
arr[2][2] = 5
p[2][2] = 10
58
*(*(p + i) +j ) p[i][j]
C/C++ String
59
String
No standard string in C/C++ Use char*, or char[] instead String in C/C++ is array of byte, end with \0
char *st = "String"; st S t r i n g \0
60
String allocation
Static allocation
char *st = "String"; char st2[] = "String";
Dynamic allocation
char *st3 = new char[6]; st3[0] = 's'; st3[1] = 't'; st3[2] = 'i'; st3[3] = 'n'; st3[4] = 'g'; st3[5] = '\0';
61
int main() { printf("Say: %s", GetString1()); printf("Say: %s", GetString2()); printf("Say: %s", GetString3()); }
62
63
string
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
Pointer to constant: Value at address which pointed to is constant Address of memory stored could be changed
char char_A = 'A'; const char * myPtr = &char_A; *myPtr = 'J'; // error - can't change value of *myPtr
65
Outline
Preparation Getting Start OOP
Data structure: enum union - struct Variables and constant Primary data type Array Pointer - String
Function Namespace
66
Enum
Use for set up collections of named integer constants In traditional C way:
#define #define #define #define SPRING SUMMER FALL WINTER 0 1 2 3
Alternate approach
enum {SPRING, SUMMER, FALL, WINTER}; 0 1 2 3
67
Enum (cont.)
Declaration
enum MyEnum {SPRING, SUMMER, FALL, WINTER}; enum MyEmum x; MyEnum y; // C style // C++ style
68
Union
Allow same portion of memory to be accessed as
Memory block
0x04
0x03
0x02
0x01
iValue cValue
0x04 0x04
0x01020304
int main() { MyUnion mine = {0x01020304}; printf("iValue: 0x%x\n", mine.iValue); printf("iValue: 0x%x\n", mine.cValue); printf("iValue: 0x%x 0x%x 0x%x 0x%x\n", mine.aValue[0], mine.aValue[1], mine.aValue[2], mine.aValue[3]); }
aValue
0x03
0x02
0x01
sizeof(mine) = ?
69
Struct
Define a structure type and/or a variable of a
structure type.
struct T_MyStruct { int val1; char val2; char val3[5]; }; struct T_MyStruct myStruct; T_MyStruct
val1
val2 val3
70
Struct
Using struct:
typedef struct T_MyStruct { int val1; char val2; char val3[5]; }MyStruct; MyStruct myStruct; int main() { myStruct.val1 = 10; myStruct.val2 = 100; myStruct.val3[0] = 1000; }
71
memory.
Consist two issue: Data alignment:
o Put data at memory offset equal to multiple word size
Structure padding: o Insert some meaningless bytes between the of last data structure and start of next
72
of T_MyStruct is 8 byte
val1 0 1
val2
3
val3
val4 7
4 bytes alignment
val2
2 3 4
val3
val4 8 9
pad2 10 11
4 bytes block
4 bytes block
4 bytes block
73
sizeof(T_MyStruct) == 12 bytes
74
GCC alignment
struct test_t { int a; char b; int c; }__attribute__((aligned(8))); struct test_t { int a; char b; int c; }__attribute__((__packed__)); http://www.delorie.com/gnu/docs/gcc/gcc_62.html
8 byte alignment
75
Struct - function
typedef struct T_MyStruct { int val1; char val2; char val3[12]; void SayHello(); }MyStruct; void MyStruct::SayHello() { printf("Hello world"); } int main() { MyStruct myStruct; myStruct.SayHello(); }
in C Beside variable, struct also has had function Struct alignment is not effected to structfunction Function is not counted when calculate struct size
76
~T_MyStruct();
}MyStruct;
destructor
C++ only, not available in C Two special function of struct Constructor: automatically call when a instant of struct is created Destructor: automatically call when a instant of struct is destroy
77
variable Static variable is not counted is struct alignment and struct size
78
79
Outline
Preparation Getting Start OOP
Data structure: enum union - struct Variables and constant Primary data type Array Pointer - String
Function Namespace
80
C/C++ function
<return-type> function_name([<type> <param>], [])
No return function
void foo() {}
81
Default parameters
#include <cstdio> void foo(int a, int b = 1 , int c = 2 ); void foo(int a, int b, int c) printf("%d %d %d\n", a, b, c); } void main() { foo(0); foo(0, 10); foo(0, 10, 100); }
ERROR
error C2548: 'foo' : missing default parameter for parameter 3
RULES
When a parameter is set default value, the rest of next parameters MUST BE set default value too
83
84
Parameter classification
Value parameter
Reference parameter
Constant parameter
Const Reference parameter Pointer parameter
85
Parameter classification
Value parameter
Pass-by-value
A copy of parameter is made
void foo(int n) { n++; } void main() { int x = 2; foo(x); printf("%d\n", x); }
Reference parameter
Constant parameter
Const Reference parameter Pointer parameter
x=2
2
2 foo
x n
2 3
2
86
Parameter classification
Value parameter
Reference parameter
Constant parameter
Const Reference parameter Pointer parameter
x=3
2 foo
x n
3
87
Parameter classification
Value parameter
strict as const.
Reference parameter
Constant parameter
Const Reference parameter Pointer parameter
void foo(int cont n) { n++; Fail, can not } modified void main() { const value int x = 2; foo(x); printf("%d\n", x); }
x n
2 2 foo
x n
2 3
88
Parameter classification
Value parameter
Pass-by-ref
Actually parameter itself is passed but avoid modify Void the overhead of creating a copy
Reference parameter
Constant parameter
Const Reference parameter Pointer parameter
89
Parameter classification
Value parameter
Reference parameter
Constant parameter
Const Reference parameter Pointer parameter
90
Pointer Parameter
#include <cstdio> void foo(int *A, int *B) { int *tmp = A; A = B; B = tmp; } void main() { int A[] = {1, 2, 3}; int B[] = {10, 11}; printf("0x%x 0x%x\n", A, B); foo(A, B); printf("0x%x 0x%x\n", A, B); } Copy value (addr. of data)
foo
A B A B
A B A B
Command prompt
0x29faa8 0x29faa0 0x29faa8 0x29faa0
91
Pointer Parameter
A[2] = 3
#include <cstdio> void foo(int *A) { A[2] = 10; } void main() { int A[] = {1, 2, 3}; printf(%d\n", A[2]); foo(A); printf(%d\n", A[2]); }
A
A[2] = 10
1 2 3
10
A[2] = 10
92
Function overloading
C++ only Allow multiple functions with the same name, so long
94
Function Prototype
In C/C++, functions MUST BE declare before using. To solve this problems
Keep all functions in correct order Use prototype inside .cpp file Use prototype inside header (.h) file -> recommend
Main.cpp
void Todo1() { Todo2(); Error } error C3861: void Todo2() 'Todo2': identifier {} not found int main() {}
header.h
void Todo1(); void Todo2();
Main.cpp
#include "header.h" void Todo1() { Todo2(); } void Todo2(){} int main(){}
95
Extern function
Sometimes, we need to use a function in another
module (.cpp file) Header file is too complicated to use (caused error when used)
Extern.cpp
#include <cstdio> void TodoExtern() { printf("TodoExtern\n"); }
Main.cpp
#include <cstdio> extern void TodoExtern(); int main() { TodoExtern(); return 1; }
96
Extern C
Name mangling: Aka name decoration The way of encoding additional information in a name of function, struct, class In C++: For adapting overload, class/struct functions, name of function will be encoding
int int f (void) { return 1; } f (int) { return 0; }
int int
97
Extern C
For mixing C and C++ source (Object C also) use extern "C" Extern C talk to compiler that use C style for its scope
No name mangling No overloading
Ansi_c.c
#include <stdio.h> void ExternC() { printf("ExternC\n"); }
C_plusplus.cpp
extern "C" { void ExternC(); void Todo() { printf("%d", i); } }
98
Extern C in practice
#ifdef __cplusplus extern "C" { #endif
// your code here
99
Pointer to function
A variable store address of a function Advantage Flexible User for event handling mechanism
// C void DoIt (float a, char b, char c){} void (*pt2Function)(float, char, char) = DoIt; // using pt2Function(0, 0, 0);
100
Inline function
Macro: preprocessor replaces all macro calls directly
101
For OOP, Inline function is allowed to set access privilege Improve performance (for short/simple inline functions)
Outline
Preparation Getting Start OOP
Data structure: enum union - struct Variables and constant Primary data type Array Pointer - String
Function Namespace
103
Namespace
A abstract container uses for grouping source code. In C++, a namespace is defined with a namespace
block
namespace maths { void sin() {} void cos() {} void add() {} } namespace matrix { void mult() {} void add() {} }
104
Using namespace
For using methods, variables, of a namespace:
<namespace>::<methods/variables>
namespace maths { void sin() {} void cos() {} void add() {} } namespace matrix { void mult() {} void add() {} } void main() { maths::sin(); matrix::add(); }
105
Using namespace
Use using namespace for shorten way.
namespace maths { void sin() {} void cos() {} void add() {} } namespace matrix { void mult() {} void add() {} } using namespace maths; using namespace matrix; void main() { sin(); mult(); }
106
add functions
maths::add() matrix::add()
namespace.
error C2668: 'matrix::add' : ambiguous call to overloaded function .\main.cpp(8): could be 'void matrix::add(void)' .\main.cpp(3): or 'void maths::add(void)' 107
Outline
Preparation Getting Start OOP Memory management Rest of C/C++ features
Outline
Preparation Getting Start OOP Memory management Rest of C/C++ features
Class
As same as struct Default access is private
class MyClass { public: MyClass(); ~MyClass(); protected: int GetVal() {return m_Var;} void Todo(); private: int m_Var; void SayHello(); }; void MyClass::Todo() { //some code here } Class name Access methods Constructor
Destructor
Function (methods) Inline methods Class variable (property) Function implementation 110
Class (cont)
In traditional, code of class is divided into 2 parts Declaration: in .h file Implementation: in .cpp file
Any_name.h
#ifndef __CCLASS_H__ #define __CCLASS_H__ class CClass { public: CClass(); ~CClass(); private: void Toso() ; }; #endif
Any_name.cpp
#include "Any_name.h" void CClass::Todo() { } CClass::~CClass() { }
111
Recommend!
MyClass *ObjB = new MyClass; objA->SayHello();
112
Access methods
Aka Encapsulation Public: allow access inside & outside class Protected: allow access inside class & in derived class Private : allow access inside class only
113
Constructor
Should be public Called when an instance is created A class could define a set of constructors (constructor
overloading)
class MyClass { public: MyClass(); MyClass(MyClass* A); MyClass(const MyClass& A); MyClass(int val); }
114
Copy constructor
Definition: A constructor with the same name as the class Used to make a deep copy of objects (be careful if class content pointer properties)
X X X X (const X& copy_from_me) (X* copy_from_me) (X& copy_from_me) (const X©_from_me, int = 10, float = 1.0 ) Must be set default value
one.
115
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
117
Explicit constructor
class A { public: explicit A(int) {} }; void f(A) {} void g() { A a1 = 37; A a2 = A(47); a1 = 67; f(77);
Without explicit
With explicit
118
Destructor
class MyClass { char m_Var; int m_pData; public: MyClass(char id) { m_Var = id; m_pData = new int[100]; }; ~MyClass() { delete m_pData; cout<<"Destroyed "<<m_Var<<endl; } }; int main() { cout << "---Alloc A---"<<endl; MyClass *A = new MyClass('A'); cout << "---Free A---"<<endl; delete A; cout << "---Create B---"<<endl; MyClass B('B'); cout << "---End---"<<endl; return 1; }
an object is destroy:
pointer)
this pointer
A special pointer point to class instance itself Used inside class, for access class methods, properties
class MyClass { char m_Var; public: MyClass(char id) {m_Var = id;}; ~MyClass() {} MyClass* Todo1(int val) { if (this->m_Var == val) { return this; } return 0; } void Todo2() { this->Todo1('A'); } };
120
Member initialization
class MyClass { private: int m_iVar1; float m_fVar2; char * m_pVar3; public: MyClass(); } MyClass::MyClass(): m_iVar1(10), m_fVar2(1.3f), m_pVar3(0) { }
121
Outline
Preparation Getting Start OOP Memory management Rest of C/C++ features
Inheritance
Code reuse: Composition: create objects of existing class inside the new class class NewClass
Existing class New class
{ public: ExistingClass *m_member; };
class
Base class Hierarchy model Derive class
123
Inheritance syntax
class Base { public: Base() {} void publicFunc() {} void Todo() {} protected: void protectedFunc() {} private: void privateFunc() {} };
class Derive: public Base { public: Derive():Base() {} void Todo(); }; Constructor init
FAIL: cannot access private member Access bases method (same name)
}
Base::Todo();
124
Inheritance access
Base access Public Protected Private Public Inherit access Derive access Public Protected Private
Public Protected
Private Public Protected Private Protected
Protected
Private
Private
private
125
Why?
126
Animal()
Animal
~Animal()
Mammal()
Mammal
~Mammal()
Lion()
Lion
~Lion()
delete theLion;
127
Multiple inheritance
A class could be inherit from multiple base class
class Human{}; class Musician { public: Musician(int instrument, int year){} }; class Worker { public: Base2(int level){} }; class StreetMusician: public Human, protected Musician, private Worker { public: StreetMusician(): Human(), Musician(1, 1), Worker(10) {} };
Human
Musician
Worker
StreetMusician
128
CBase1::Hello() CBase2::Hello()
129
Outline
Preparation Getting Start OOP Memory management Rest of C/C++ features
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
132
Overriding: override a
several methods with the same name which differ from parameters
class Animal { public: virtual void Eat() { cout<<Animal:Eat"<<endl; } void Run() { cout<<Animal:Run"<<endl; } }; class Cat: public Animal { public: void Eat() { cout<<Cat:Eat"<<endl; } void Run() { cout<<Cat:Run"<<endl; } }; int main() { Animal *obj = new Cat(); obj->Eat(); obj->Run(); }
134
Virtual destructor
When obj is freed, both
135
virtual
~Base()
cout<<"Destroy Base"<<endl;
Command prompt --Free obj1-Destroy Derive Destroy Base --Free obj2 Destroy Derive Destroy Base
136
Pure virtual function: Virtual function with no body Pure virtual class: Class content pure virtual function CAN NOT create an instance of
pure virtual class directly Derive class of pure virtual class MUST implements all pure virtual functions
137
Outline
Preparation Getting Start OOP Memory management Rest of C/C++ features
Operator overloading
Another way to make a function call Define function of operator such as : +, -, *, /, WARNING: Not recommend to use. Its easy to read,
139
class Integer { public: int i; Integer(int ii) : i(ii) {} const Integer operator+(const Integer& rv) { return Integer(i - rv.i); } Integer& operator+=(const Integer& rv) { i *= rv.i; This implementation make user confused return *this; } }; int main() { Integer ii(1), jj(2), kk(3); kk += ii + jj; cout << "Value = " << kk.i << endl; }
140
Outline
Preparation Getting Start OOP Memory management Rest of C/C++ features
Static function
class MyClass { public: static void Todo(); }; void MyClass::Todo() { //implemetation }
int main() { MyClass::Todo(); }
without creating an instance Declaration with static keyword No need to create object, but must be declared class name
142
Static variable
class MyClass { public: static int s_Var; };
int MyClass::s_Var = 99; int main() { printf("%d", MyClass::s_Var); }
143
Lazy initialization
class ExpensiveRes { public: ExpensiveRes() {} void todo1(); static ExpensiveRes* GetInstance(); private: static ExpensiveRes* s_Instance; }; ExpensiveRes* ExpensiveRes::s_Instance = 0; ExpensiveRes* ExpensiveRes::GetInstance() { if (!s_Instance) { s_Instance = new ExpensiveRes(); } return s_Instance; } int main() { ExpensiveRes::GetInstance()->todo1(); ExpensiveRes::GetInstance()->todo1(); }
creation of an object, calculation of a value, or some other expensive process until the first time it is need.
144
Outline
Preparation Getting Start OOP Memory management Rest of C/C++ features
145
Question?
What does memory leak mean ? How is memory structure ?
146
147
148
Run-time storage
Text segment (Code segment) Global area
Stack segment
Heap Segment
Code segment: where the compiled program sits in memory Global area: store global variables Stack segment: where parameters and local variables are allocated Heap segment: where dynamically allocated variables are allocated
149
Stack
Parameters
where to begin execution when function exits
variables are allocated Limited size Stack overflow Memory use in stack is temporary and auto release Fast processing/low size
150
Heap
Parameters
where to begin execution when function exits
specifically deallocated leak ! Must be accessed through a pointer Large arrays, structures, or classes should be stored Heap why? Large & dynamic
151
Heap vs Stack
int _array[10]; stored in stack int *_array = new int[n]
Pointer _array is stored in Stack Data of array is stored in Heap
Stack _array
Stack
0x00FF
0x0005
Heap
10
_array
0x00FF
Value of: _array : address where int point into in heap (0x00FF) (*_array): value at it's address on heap (10) (&_array): address of the memory which used for stored pointer _array in stack (0x0005)
152
FAQ
Why we use Classname *Obj = new Classname(); instead of Classname Obj;
153
154
void Leak() { int *A = new int[1000]; // some code here // ... // without delete A // return; }
4000 bytes
155
156
157
Example 0
No GC mechanic supported
Button is pressed
Finished
On target floor ?
Memory
True
Wait until lift is idle Go to required floor Release memory used to save current floor
158
C/C++ Example 1
Leak !
C/C++ Example 2
void leak() { int **list = new int*[10]; for (int i = 0; i < 10; i++) { list[i] = new int; }
Leak !
delete list;
return; }
Solution for (int i = 0; i < 10; i++) { delete list[i]; } delete list; 160
C/C++ Example 3
char* GenString() { char *a = new char[10]; a[9] = '\0'; return a; } void Leak() { char *str = GenString(); printf("%s\n", str); printf("%s\n", GenString()); }
C/C++ Example 4
Leak memory when using pointer as a parameter
Stack Heap Leak! A LEAK!
Solution Well control with reference variables Check if a pointer is allocated memory yet!
162
C/C++ Example 5
void main() { Classname *A = new A(); ... ... //free A A = NULL; }
NULL
Heap
LEAK!
Solution Keep in mind we are using C/C++ Use MACRO for safe deallocating
Example 6
class CB { public: CB(){ m_iVal = 0; } ~CB(){} int m_iVal; }; class CA { public: CA(){ m_pB = 0; } ~CA(){ delete m_pB; m_pB = 0; } CB *m_pB; };
m_pB
int main() { CB *B = new CB; CA *A = new CA(); A->m_pB = B; delete(A); printf("%d", B->m_iVal); }
164
Example 6 (cont.)
Leak class CB { public: CB(){ m_iVal = 0; } ~CB(){} int m_iVal; }; class CA { public: CA(){ Delete or not? m_pB = 0; } ~CA(){ delete m_pB; m_pB = 0; } CB *m_pB; };
m_pB
165
C/C++ Example 7
class cA() { public : cA() {m_pdata = new int[100];} virtual ~cA() {delete[] m_pdata;} int *m_pdata; }; class cB: public cA() { public cB():cA() {m_pdata2 = new int[100];} ~cB() {delete []m_pdata2;} int *m_pdata2; }
167
Current Solutions
For Forget/ misunderstand C/C++ mechanism Semi-automatic memory management
o Reference Counting
168
Alloc
.. .n
169
170
171
172
173
VLD Tool
0 http://www.codeproject.com/KB/applications/visualleakdetector.aspx
174
Outline
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++
175
Outline
Preparation Getting Start OOP Memory management Rest of C/C++ features
Forward declaration
Type casting
Exception handling Endian Bit processing STL introduction GNU GCC/G++
176
Forward declaration
Declaration of a identifier which not completed
177
Forward declaration
ClassA.h
#ifndef _CLASSA_H_ #define _CLASSA_H_
ClassB.h
#ifndef _CLASSB_H_ #define _CLASSB_H_
Must be pointer
#endif
#endif
ClassA.cpp
#include "ClassA.h" ClassA::ClassA(){}
ClassB.cpp
#include "ClassB.h" ClassB::ClassB(){}
178
Outline
Preparation Getting Start OOP Memory management Rest of C/C++ features
Forward declaration
Type casting
Exception handling Endian Bit processing STL introduction GNU GCC/G++
179
Standard IO
stdio.h
180
Standard IO
stdio.h
181
Standard IO
<iostream>
std::cout
an object of class ostream that represents the standard
output stream
cout cout cout cout cout cout cout cout << << << << << << << << "Hello there.\n"; "Here is 5: " << 5 << "\n"; "The manipulator endl writes a new line to the screen." << endl; "Here is a very big number:\t" << 70000 << endl; "Here is the sum of 8 and 5:\t" << 8+5 << endl; "Here's a fraction:\t\t" << (float) 5/8 << endl; "And a very very big number:\t" << (double) 7000 * 7000 << endl; "I am a C++ programmer!\n";
182
Standard IO
0 <iostream>
std::cin
an object of class istream that represents the standard
input stream
int input = 0; cout << "Enter a number here: "; cin >> input; cout << "You entered the number " << input << ".\n";
183
File <stdio.h>
FILE * fopen ( const char * filename, const char * mode ); int fclose ( FILE * stream ); size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream ); size_t fread ( void * ptr, size_t size, size_t count, FILE * stream ); int fscanf ( FILE * stream, const char * format, ... ); int fprintf ( FILE * stream, const char * format, ... ); int fseek ( FILE * stream, long int offset, int origin ); Open file Close a file Write block of data to stream Read a block data from stream Read formatted data from stream Write formatted output to stream Reposition stream position indicator Origin: SEEK_SET : beginning of gfile SEEK_END: end of file SEEK_CUR: current position Get current position in stream Set position indicator to the beginning
184
File <stdio.h>
#include <stdio.h> int main () { FILE * pFile; pFile = fopen ("myfile.txt","w"); if (pFile!=NULL) { fprintf (pFile, "example"); fclose (pFile); } return 0; }
185
Outline
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++
186
Function template
special functions that can operate with generic types Can be adapted to more than one type or class
without repeating code A set of needed functions will be created when compile slow down compiling process
template <class identifier> function_declaration; template <typename identifier> function_declaration;
187
188
Class template
A class can have members that use template
parameters as types
template <class T> class mypair { T values [2]; public: mypair (T first, T second) { values[0]=first; values[1]=second; } }; int main() { return 1; mypair<int> Pair1(100, 200); mypair<char> Pair2('A', 'B'); }
190
Class template
Function member outside the declaration of the class template, we
must always precede that definition with the template <...> prefix
template <class T> class mypair { T a, b; public: mypair (T first, T second) {a=first; b=second;} T getmax (); }; template <class T> T { T retval; retval = a>b? a : b; return retval; } mypair<T>::getmax ()
Template prefix
Class prefix Return type
int main () { mypair <int> myobject (100, 75); cout << myobject.getmax(); return 0; }
191
Class template
New code will be generated while compiling, DO NOT
193
Mixin
We can implement inheritance delaying the definition
of the base.
template <class Base> class Mixin : public Base class Base {};
{};
194
Mixin issue
template <class Base> class Mixin : public Base { public: void Todo() {Base::Do();} };
message!
195
196
Example: Factorial
N! = 1 x 2 x 3 x x N
template<int n> struct Factorial { enum {RET=Factorial<n-1>::RET*n}; }; // Note: template specialization template<> struct Factorial<0> { enum{RET=1}; }; int main() { printf("%d", Factorial<10>::RET); return 1; }
197
Outline
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++
198
Type casting
0 Convert from specific type to another type
Explicit casting c-like casting notation
199
Numeric overflow
void main() { int a = 200; char c = a; } c = -56 ?
200
i is equal to or ?
201
202
also supported:
dynamic_cast<>
static_cast<> const_cast<> reinterpret_cast<>
203
const_cast<>
Used to add to or remove the const-ness or volatile-
204
reinterpret_cast<>
Allows any integral type to be converted into any
Unrelated_class*,
which
are
205
reinterpret_cast<> Example
// Returns a hash code based on an address unsigned short Hash( void *p ) { unsigned int val = reinterpret_cast<unsigned int>( p ); return ( unsigned short )( val ^ (val >> 16)); } int main() { int a[20]; for ( int i = 0; i < 20; i++ ) cout << Hash( a + i ) << endl; }
206
static_cast<>
0 Allows casting
0 0 0 0 0 0 0
a pointer of a derived class to its base class and vice versa int to enum Reference of type &p to &q Object type P to Object type Q Pointer to a member to pointer to a member with the same hierarchy. Any expression to void Primary data type
207
static_cast<>
#include <iostream.h> #include <stdlib.h> enum color {blue, yellow, red, green, magenta}; int main() { int p1 = 3; cout<<"integer type, p1 = "<<p1<<endl; cout<<"color c1 = static_cast<color> (p1)"<<endl; color c1 = static_cast<color> (p1); cout<<"enum type, c1 = "<<c1<<endl; return 0; }
Command prompt integer type, p1 = 3 color c1 = static_cast<color> (p1) enum type, c1 = 3 Press any key to continue . . .
208
dynamic_cast<>
209
dynamic_cast<>
Used with pointers and references to objects for class
hierarchy navigation Requires the Run-Time Type Information (RTTI) If the pointer being cast is not a pointer to a valid complete object of the requested type, the value returned is a NULL pointer Used for polymorphism class
210
dynamic_cast<>
Class Base upcast
dynamic_cast<> upcast
Always successful
Why?
Base Derive1
Derive2
Derive class always contents valid complete base class
212
dynamic_cast<>
upcast multiple conversion with multiple inheritace
Base
CAN NOT cast directly from Derived3 to base.
Do step by step: Derived3 Derived2 Base
Derived 1
Derived 2
Derived 3
213
dynamic_cast<> downcast
Base
Funct2()
class only
class Base1 { public: virtual void funct1(){}; };
Derive
Funct3()
Derive
Funct3() Base* Test1 = new Derived; Base* Test2 = new Base; Derived* Test3 = dynamic_cast<Derived*>(Test1); fail Derived* Test4 = dynamic_cast<Derived*>(Test2);
215
successful
dynamic_cast<> crosscast
Crosscast Base2 Derived1
Base Derived 1 Derived 2 Fail
Base2 *p1 = new Base2; Derived1 *p2 = dynamic_cast<Derived1*>(p1);
Base2
Derived 3
OK
Base2 *p1 = new Derived3; Derived1 *p2 = dynamic_cast<Derived1*>(p1);
216
Outline
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++
217
Exception Handling
Improved error recovery is one of the most powerful
Throw exception
throw type; //type: user defined type or principle type
218
Exception example
class DivByZeroEx {}; void div(int num1, int num2) { if (num2 == 0) throw (DivByZeroEx ()); } void main() { try { div(1, 0); } catch (DivByZeroEx ex) { printf(" DivByZero Exception "); } catch (...) { printf("Unkown exception"); } }
219
Outline
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++
220
Endian
big-endian and little-endian refer to which bytes are
221
Endian - Example
int main() { char num[4] = {0x00, 0x11, 0x22, 0x33}; int *val = (int*)num; printf("val = 0x%x", *val); }
Command prompt val = 0x33221100 Windows 32 bits
Important notes: Avoid to save/load a short/int/long array. Use char (byte) array instead.
222
Outline
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++
223
STL
Standard template library Powerful library for container and algorithms Some basic types:
STL
Container Vector, deque, set, list, map, hash
Iterator: an object used for selecting the elements within a container and present them to the user
225
STL example
#include <cstdio> #include <list> using namespace std; int main() { list<int> m_List; m_List.push_back(10); m_List.push_back(20); //travel list list<int>::iterator i = m_List.begin(); for (i = m_List.begin(); i != m_List.end(); i++) { printf("%d\n", *i); } return 0; }
226
Command prompt Created 0 addr 0x22cce8 Created 1 addr 0x22cce4 -----Before clear----Destroy 0 addr 0xc91a38 Destroy 1 addr 0xc91a48 -----After clear----Destroy 1 addr 0x22cce4 Destroy 0 addr 0x22cce8
???
Command prompt Created 0 addr 0xa719c0 Created 1 addr 0xa81a18 -----Before clear---------After clear----Memory leak here
228
Outline
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++
230
GNU GCC
GNU compiler collection include front ends for C, C++,
Object-C,
Example
make.bat
@echo off cls SET CYGWIN=c:\cygwin\ SET CYGWIN_BIN=%CYGWIN%\bin SET PATH=%PATH%;%CYGWIN%;%CYGWIN_BIN%
makefile
all: main.o MyClass1.o g++ main.o MyClass1.o -o main.exe main.o: main.cpp g++ -c main.cpp MyClass1.o: MyClass1.cpp g++ -c MyClass1.cpp
del *.o >nul if exist main.exe (del main.exe)>nul %CYGWIN_BIN%\make if exist main.exe (call main.exe)
MyClass1.h
#ifndef __MYCLASS_H__ #define __MYCLASS_H__ class MyClass { public: MyClass(); }; #endif
main.cpp
#include "MyClass1.h" int main() { MyClass *c = new MyClass(); return 1; }
MyClass1.cpp
#include <cstdio> #include "MyClass1.h" MyClass::MyClass() { printf("Hello\n"); }
232
Introduction
Design patterns can speed up the development by
providing test, proven development paradigm Allow developers to communicate using well-know, well understood names for software interactions.
See http://sourcemaking.com/designed_patterns for
more detail
234
235
Reference
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
From Java to C Mihai Popa Gameloft Thinking in C++, 2nd Edition - Bruce Eckel, President, MindView, Inc. http://en.wikipedia.org http://www.learncpp.com http://msdn.microsoft.com http://www.cplusplus.com http://en.allexperts.com http://www.desy.de/gna/html/cc/Tutorial/tutorial.html http://aszt.inf.elte.hu/~gsd/halado_cpp/ http://www.codeguru.com/forum/showthread.php http://www.uow.edu.au/~nabg/ABC/ABC.html http://pages.cs.wisc.edu/~hasti/cs368/CppTutorial/ http://www.devmaster.net http://enel.ucalgary.ca/People/Normal/enel1315_winter1997/ http://www.cantrip.org http://sourcemaking.com/designed_patterns
236