Skip to main content
Outline
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
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
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Appendix
Class & Object
Inheritance
Polymorphism
Operator overloading
Class’ static member
5
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Appendix
Recall pointer
Memory leak
6
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
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
Hello world using VS
10
Hello world
# include <stdio.h>
void main()
{
printf("Hello world");
}
main.cpp
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
C/C++ source files
Header file (.h)
 aka include file
 Hold declarations for other files
use (prototype)
 Not required
#include "stdio.h"
void Todo1();
void Todo2();
# include "header.h"
void Todo1()
{
Todo2();
}
void Todo2(){}
void main()
{
Todo1();
}
Source file (.c / .cpp)
 Content implementation
 Required
13
Outline
Preparation
Getting Start
OOP
Memory management
Rest of C/C++ features
Hello world!
C/C++ files
Entry point
C/C++ libraries
Source compile process
14
Entry point
Required unique entry point
The most common is: main
void 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
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
C/C++ standard library
C/C++ support a set of internal
basic library, such as
• Basic IO
• Math
• Memory handle
• …
For using, include the header
file
#include <…>
#include "…"
#include "stdio.h"
void main()
{
printf("hello");
}
17
C header C++ header
<assert.h> <cassert> Content assert macro, for debugging
<Ctype.h> <cctype> For character classification/convert functions
<Errno.h> <cerrno> For testing error number
<float.h> <cfloat> Floating point macros
<limits.h> <climits> Define range of value of common type
<math.h> <cmath> Mathematical functions
<setjmp.h> <csetjmp> Provide “non-local jumps” for flow control
<signal.h> <csignal> Controlling various exceptional conditions
<stdlib.h> <cstdlib> Standard lib
<stddef.h> <cstddef>
<stdarg.h> <cstdarg>
<stdio.h> <cstdio> Standard IO
<string.h> <cstring> Manipulating several kinds of string
<time.h> <ctime> Converting between time & date formats
<wchar.h> <cwchar>
<wctype> <cwctype> 18
C/C++ user-defined lib
Not C/C++ standard lib
Come from:
• Third-party
• User own
In common, include 2 parts
• .h files & .lib files: for developer
• .dll file (dynamic library): for end-user
error LNK2019: unresolved external symbol
Error caused when forget to add .lib file
19
C/C++ user-defined lib (cont.)
For using
• Include .h files
• Inform .lib files to compiler
• Copy all .dll file to (if any) :
o same folder with execute file, or
o to system32 (windows) – not recommend
20
Declare path to .lib
Import user-defined library
Visual studio
21
Import user-defined library
Visual studio
Declare .lib file
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
(c/cpp)
Compile
.o / .obj
(object file)Linker
Executable/
lib
Tools:
• Visual Studio: cl.exe (Press F7 / F5)
• GNU GCC: gcc/ g++
24
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
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
Variable classification
Scope:
• Local variable
• Global variable
• Static variable
Storage class specifier
• auto
• static
• register
• extern
27
Global & local
int mGlobalVar;
void Foo()
{
int localVar;
printf("Foo : %d %dn",
localVar, mGlobalVar);
}
int main()
{
int localVar = 1;
printf("Main: %d %dn",
localVar, mGlobalVar);
mGlobalVar = 1;
Foo();
return 1;
}
Global variable
• Available in all of program
• Set default value to zero
Local variable
• NO default value
• Available inside block
Main: 1 0
Foo : 2280752 1
Command prompt
28
Auto variable
As default, a variable is a auto variable
int myVar  auto int myVar
Go out of scope once the program exits from the
current block
29
Static variable
Allocated when the program
starts and is deallocated when
the program ends.
Default value is zero (0)
#include <cstdio>
static int s_iGlobalStatic;
void Foo()
{
static int s_iLocalStatic;
printf("Foo: called %dn",
s_iLocalStatic++);
}
int main()
{
int localVar = 1;
printf("Main: %dn",
s_iGlobalStatic);
Foo();
Foo();
Foo();
return 1;
}
Main: 0
Foo: called 0
Foo: called 1
Foo: called 2
Command prompt
30
Register variable
Stored in a machine register if
possible
Usually used in “for iterator”
for improve performance
int main()
{
int sum = 0;
for (register int i = 0;
i < 100;
i++)
{
sum += i;
}
printf("Sum = %dn", sum);
return 1;
}
31
Extern variable
Specify that the variable is
declared in a different file.
Compiler will not allocate
memory for the variable
Avoid duplicate declaration
Share (global) variable for
multiple .cpp files
#include <cstdio>
extern int m_iExternVar;
int main()
{
printf("Value = %dn",
m_iExternVar);
return 1;
}
main.cpp
int m_iExternVar = 100;
Extern.cpp
Value = 100
Command prompt
32
Constant
Variable's value is constant
To prevent the programmer from modifying
int const k_Hello = 0;
int main()
{
k_Hello = 10;
}
error C3892: 'k_Hello' : you cannot assign to
a variable that is const
Error
33
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
Primitive data type
(32bits processor)
Type Size Range
void n/a
char 1 byte unsigned char: -128 … 127
signed char: 0…255
short 2 bytes unsigned short: 0 … (216 -1)
signed short: -215 … (215 – 1)
int 4 bytes
-231 … (231 – 1)
unsigned int: 0 … (232 -1)
signed int: -231 … (231 – 1)
long 4 bytes
-231 … (231 – 1)
unsigned long: 0 … (232 -1)
signed long: -231 … (231 – 1)
long long 8 bytes
-263 … (263 – 1)
unsigned long long: 0 … (264 -1)
signed long long: -263 … (263 – 1)
bool 1 byte True /false (non-zero / zero)
float 4 bytes
double 8 bytes 35
New type definition
Use typedef
36
typedef int Mytype;
typedef int MyArr[5];
Mytype var1;
MyArr arr;
sizeof operator
0 Return size (in byte) of a type, data structure, variable
int sizeInt = sizeof(int);
int sizeLong = sizeof(long);
char a;
int sizeA = sizeof(a);
Return 4
Return 4
Return 1
37
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
Array
Used to store consecutive values of the same data types
int b[4] = {1, 2, 3, 4};
n-dimensions array
int b[<s1>][<s2>]…[<sn>] si MUST BE constant
 Index of array is counted from 0 to (si-1)
 C/C++ do not handle out-of-range exception
int b[4] = {1, 2, 3, 4};
for (int i = 0; i < 4; i++)
{
printf("%dn", b[i]);
}
printf("%dn", b[10]);
b[10] = ?
39
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));
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}
};
Pointer
 Computer's memory is made up of bytes.
 Each byte has a number, an address, associated with it.
0x01 0x02 0x03 0x01 0x05 0x06 0x07 0x08
When storing a variable, such as int i = 1
0x00 0x00 0x00 0x01
0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08
i
o i = 1
o &i = 0x01 & operator: get address of a variable
42
Pointer (cont.)
For storing address of a variable, use a special type:
pointer
int *pi; char *pc; float *pf;
Pointer of a
integer variable
Pointer 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
Pointer (cont.)
Pointer is also a variable  it’s 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
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
i Little Endian
P3
45
0x01
0xCC01
0x3f20cc01
Pointer (cont.)
sizeof operator
Size of pointer is not belong to type of pointer
Size of pointer depend on processor (16 bits, 32 bits, 64
bits)
• For windows 32 bits: size of pointer is 4 bytes
int main()
{
char c = 0;
char *p = &c;
printf("size = %d", sizeof(p));
}
46
Pointer
pointer operator
 Note: 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
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 + 1
a++; a = ?
p++; p = ?
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) == ?
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 = new int[n];
p
Free memory block pointed by p
50
delete p;
How about
“p” after
deleting?
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;
}
Pointer
Dynamic allocation (cont.)
Use delete for new,
Use delete[] for new[]
52
struct A
{
public:
static int count;
int val;
A()
{
printf("Created %dn",
val = count++);}
~A()
{
printf("Deleted %dn",
val);}
};
int A::count = 0;
int main()
{
A *cA = new A[10];
delete cA;
return 1;
}
Delete cA[0] only
int main()
{
A *cA = new A[10];
delete []cA;
return 1;
}
Delete all cA
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 = new int*[3];
p[0] = new int[4];
p[1] = new int[4];
p[2] = new int[4];
*(*(p + i) +j )  p[i][j]
Pointer vs. 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
new int [3];
= 0x2f330000
1
12
5
=
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 %dn", a, &a, *a);
int *p = new int[3];
p[0] = 1; p[1] = 2; p[2] = 3;
printf ("0x%x 0x%x %dn", p, &p, *p);
int *p2 = (int*)a;
printf("value of p2 = 0x%xn", *p2);
}
0x14fd64 0x14fd64 1
0x591398 0x14fd60 1
Value of p2 = 0x04030201
Command prompt
55
Pointer vs. Array
char a[3] = {1, 2, 3};
char *p = new char[3];
p[0] = 10; p[1] = 20; p[2] = 30;
printf ("a = 0x%x p = 0x%xn", a, p);
printf ("a+1 = 0x%x p+1 = 0x%xn", a+1, p+1);
printf ("&a = 0x%x &p = 0x%xn", &a, &p);
printf ("&a+1= 0x%x &p+1 = 0x%xn", &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
20
30
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
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
0 Can not delete an array
int 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 “delete”
57
Pointer vs. Array
2D array
int arr[2][3]
pointer-to-pointer
int **p = new int*[2];
p[0] = new int[3];
p[1] = new int[3];
[0][0] [0][1] [0][2]
[1][0] [1][1] [1][2]
p[1]
p[0]p p[0][0] p[0][1] p[0][2]
p[1][0] p[1][1] p[1][2]
0 2D array & 2D pointer could use in the same way
arr[2][2] = 5 p[2][2] = 10
58
[0][0] [0][1] [0][2] [1][0] [1][1] [1][2]
Block 0 Block 1
*(*(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";
S t r i n g 0st
60
String allocation
Static allocation
char *st = "String";
char st2[] = "String";
Dynamic allocation
char *st3 = new char[6];
st3[0] = 's';
st3[1] = 't';
st3[2] = 'i';
st3[3] = 'n';
st3[4] = 'g';
st3[5] = '0';
61
String allocation (cont.)
62
char* GetString1()
{
char *st = "String";
return st;
}
char* GetString2()
{
char st[] = "String";
return st;
}
char* GetString3()
{
char *st = new char[6];
strcpy(st, "String");
return st;
}
int main()
{
printf("Say: %sn", GetString1());
printf("Say: %sn", GetString2());
printf("Say: %sn", GetString3());
}
What are
different?
Memory utility functions
MUST #include <string.h>
void * memcpy ( void * destination, const void * source, size_t num )
Copies the values of num bytes from the location pointed
by source directly to the memory block pointed by destination
int memcmp ( const void * ptr1, const void * ptr2, size_t num )
Compare the C string pointed by source into the array pointed
by destination, including the terminating null character
63
Memory utility functions
size_t strlen ( const char * str )
• Returns the length of str
• The length of a C string is determined by the terminating null-character
• This should not be confused with the size of the array that holds the
string
 char * strcpy ( char * destination, const char * source )
• Copies the C string pointed by source into the array pointed
by destination, including the terminating null character
 int strcmp ( const char * str1, const char * str2 )
• Compares the C string str1 to the C string str2.
http://www.cplusplus.com/reference/clibrary/cstring/ 64
Constant pointer vs.
pointer to constant
Constant 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';
const char * 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
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
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 3 67
Enum (cont.)
Declaration
Values of enum constants
enum MyEnum {SPRING, SUMMER, FALL, WINTER};
enum MyEmum x; // C style
MyEnum y; // C++ style
int main()
{
y = MyEnum::SPRING;
y = FALL;
y = 1; // ILLEGAL
}
enum MyEnum {SPRING = 0, SUMMER = 10, FALL = 11, WINTER = 100};
int main()
{
y = MyEnum::SPRING;
printf("%d", y);
} 68
Union
Allow same portion of memory to be accessed as
different data type
union MyUnion
{
int iValue;
char cValue;
char aValue[4];
};
int main()
{
MyUnion mine = {0x01020304};
printf("iValue: 0x%xn", mine.iValue);
printf("iValue: 0x%xn", mine.cValue);
printf("iValue: 0x%x 0x%x 0x%x 0x%xn",
mine.aValue[0],
mine.aValue[1],
mine.aValue[2],
mine.aValue[3]);
}
0x04 0x03 0x02 0x01
iValue 0x01020304
0x04
0x04 0x03 0x02 0x01
cValue
aValue
Memory block
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;
val1
val2
val3
T_MyStruct
70
Struct
Using struct:
typedef struct T_MyStruct
{
int val1;
char val2;
char val3[5];
}MyStruct;
MyStruct myStruct;
int main()
{
myStruct.val1 = 10;
myStruct.val2 = 100;
myStruct.val3[0] = 1000;
}
71
Data Structure alignment
Is the way data is arranged and accessed in computer
memory.
Consist two issue:
• Data alignment:
o Put data at memory offset equal to multiple word size
• Structure padding:
o Insert some meaningless bytes between the of last data
structure and start of next
72
Data Structure alignment
0 Before 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
1
val2 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 bytes 73
VS Struct member alignment
74
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
Struct - function
C++ only, not available
in C
Beside variable, struct
also has had function
Struct alignment is not
effected to struct-
function
Function is not counted
when calculate struct
size
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();
}
76
Struct
constructor / 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
typedef struct T_MyStruct
{
int val1;
T_MyStruct();
~T_MyStruct();
}MyStruct;
T_MyStruct::T_MyStruct()
{
printf("Createdn");
}
T_MyStruct::~T_MyStruct()
{
printf("Destroyn");
}
int main()
{
MyStruct myStruct;
}
constructor
destructor
Created
Destroy
Command prompt
77
Struct and static member
Static function & static
variable
Static variable is not
counted is struct
alignment and struct
size
typedef struct T_MyStruct
{
int val1;
static char val2;
static void SayHello() {}
}MyStruct;
int main()
{
MyStruct myStruct;
printf("%d", sizeof(myStruct));
MyStruct::SayHello();
}
78
Struct and Access privilege
C++ only, not available in C
Three access privilege methods
• public: visible for all
• private: visible inside struct only
• protected: visible inside struct and
retrieved struct (OOP)
• Default is public
o For example: valx is public
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
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
C/C++ function
<return-type> function_name([<type> <param>], […])
void foo() {}
void foo(int a, int b, char c)
{}
int foo()
{
return 1;
}
No return function
Required return
81
Default parameters
#include <cstdio>
void foo(int a,
int b = 1 ,
int c = 2 );
void foo(int a, int b, int c)
printf("%d %d %dn",
a, b, c);
}
void main()
{
foo(0);
foo(0, 10);
foo(0, 10, 100);
}
Set default value
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
void foo(int a, int b = 1, int c )
{
printf("%d %d %dn", 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
Variable number of
parameters
#include <cstdio>
#include <cstdarg>
int sum(int num_param, ... )
{
int sum = 0, val = 0;
va_list marker;
va_start(marker, num_param);
for (register int i = 0; i < num_param; i++)
{
val = va_arg(marker, int);
sum += val;
}
va_end(marker);
return sum;
}
void main()
{
printf("%dn", sum(1, 10));
printf("%dn", sum(3, 1, 2, 3));
}
84
Parameter classification
Value parameter
Reference parameter
Constant
parameter
Const Reference
parameter
Pointer parameter
85
Parameter classification
Pass-by-value
A copy of parameter is made
Value parameter
Reference parameter
Constant parameter
Const Reference
parameter
Pointer parameter
void foo(int n)
{
n++;
}
void main()
{
int x = 2;
foo(x);
printf("%dn", x);
}
x = 2
2x
2x
2n
2x
3n
2x
foo
86
Parameter classification
Pass-by-reference
Actually parameter itself is passed
Use reference operator “&”
Value parameter
Reference parameter
Constant parameter
Const Reference
parameter
Pointer parameter
void foo(int &n)
{
n++;
}
void main()
{
int x = 2;
foo(x);
printf("%dn", x);
}
x = 3
2x 2
x
n
x
3
n
3x
foo
87
Parameter classification
Pass-by-value
A copy of parameter is made and
strict as const.
Value parameter
Reference parameter
Constant parameter
Const Reference
parameter
Pointer parameter
void foo(int const n)
{
n++;
}
void main()
{
int x = 2;
foo(x);
printf("%dn", x);
}
Fail, can not
modified
const value
2x
2x
2n
2x
3n
foo 88
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 Reference
parameter
Pointer parameter
void foo(int const &n)
{
//todo
}
89
Parameter classification
In common, Pass-by-value
A copy of parameter is made
Value of parameter is an address of a
memory block
Value parameter
Reference parameter
Constant parameter
Const Reference
parameter
Pointer parameter
void foo(int *n)
{
//todo
}
Value of parameter will not be
change,
but memory block which pointed
by parameter could be modified.
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%xn", A, B);
foo(A, B);
printf("0x%x 0x%xn", A, B);
}
A’
B’
A’
B’
A
B
A
B
Copy value
(addr. of data)
foo
0x29faa8 0x29faa0
0x29faa8 0x29faa0
Command prompt
91
Pointer Parameter
#include <cstdio>
void foo(int *A)
{
A[2] = 10;
}
void main()
{
int A[] = {1, 2, 3};
printf(“%dn", A[2]);
foo(A);
printf(“%dn", A[2]);
}
A’
A
foo
1
2
3A’[2] = 10 10
A
A[2] = 3
A[2] = 10
Copy value
(addr. of data)
92
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 <cstdio>
void foo(int *&A, int *&B)
{
int *tmp = A; A = B; B = tmp;
}
void main()
{
int arr1[] = {1, 2, 3};
int arr2[] = {10, 11};
int *A = arr1;
int *B = arr2;
printf("0x%x 0x%xn", A, B);
foo(A, B);
printf("0x%x 0x%xn", A, B);
}
A
B
A
B
A
B
A
B
foo
0x31fc90 0x31fc88
0x31fc88 0x31fc90
Command prompt
93
Function overloading
C++ only
Allow multiple functions with the same name, so long
as they have different parameters.
void Todo(int a)
{}
void Todo(int a, int b)
{}
94
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.cpp
header.h
void Todo1();
void Todo2();
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)
#include <cstdio>
extern void TodoExtern();
int main()
{
TodoExtern();
return 1;
}
Main.cpp
#include <cstdio>
void TodoExtern()
{
printf("TodoExternn");
}
Extern.cpp
96
Extern “C”
Name mangling:
• Aka “name decoration”
• The way of encoding additional information in a name of
function, struct, class…
In C++:
• For adapting overload, class/struct functions, name of
function will be “encoding”
int f (void) { return 1; }
int f (int) { return 0; }
int __f_v (void) { return 1; }
int __f_i (int) { return 0; }
97
Extern “C”
 For mixing “C” and “C++” source (Object C also)  use extern "C"
 Extern “C” talk to compiler that use C style for its scope
• No “name mangling”
• No overloading
 Extern “C” is also “extern”  function could be implement in another module
#include <stdio.h>
void ExternC()
{
printf("ExternCn");
}
Ansi_c.c
extern "C"
{
void ExternC();
void Todo()
{
printf("%d", i);
}
}
C_plusplus.cpp
98
Extern “C” in practice
#ifdef __cplusplus
extern "C" {
#endif
// your code here
#ifdef __cplusplus
}
#endif
__cplusplus: default C++ preprocessor definition
99
Pointer to function
A variable store address of a function
Advantage
• Flexible
• User for event handling mechanism
// C
void DoIt (float a, char b, char c){……}
void (*pt2Function)(float, char, char) = DoIt;
// using
pt2Function(0, 0, 0);
100