c++ language tutorial - storage.googleapis.com · c++ language tutorial mickey nguyen 3 6.2.14 old...

262
C++ Language Tutorial Mickey Nguyen 1 C++ Language Tutorial Written by: Mickey Nguyen (linkedin: [email protected]) August, 2013

Upload: ngoduong

Post on 12-May-2018

219 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

1

C++ Language Tutorial

Written by: Mickey Nguyen

(linkedin: [email protected])

August, 2013

Page 2: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

2

1 Introduction .......................................................................................................................................... 9

2 Differences between C++ and Java ..................................................................................................... 11

3 Eclipse IDE, hello world project .......................................................................................................... 15

4 Microsoft Studio IDE, hello world project ........................................................................................... 19

5 C/C++ naming convention ................................................................................................................... 22

6 Basics of C++ ....................................................................................................................................... 22

6.1 Input/Output ............................................................................................................................... 22

6.2 Data Types ................................................................................................................................... 27

6.2.1 C/C++ basic data types ........................................................................................................ 27

6.2.2 Struct ................................................................................................................................... 29

6.2.2.1 Struct example ................................................................................................................ 29

6.2.2.2 Another example of struct which can have both data and method ............................... 30

6.2.2.3 Another example of struct, struct can inherit to struct, or inherist to class .................. 32

6.2.3 Union ................................................................................................................................... 33

6.2.4 enum ................................................................................................................................... 34

6.2.5 Class .................................................................................................................................... 35

6.2.6 Static data member and static function .............................................................................. 37

6.2.7 Typedef ............................................................................................................................... 39

6.2.8 Preprocessor directives ....................................................................................................... 39

6.2.9 Predefined macro name ..................................................................................................... 41

6.2.10 Constant .............................................................................................................................. 41

6.2.11 Array .................................................................................................................................... 42

6.2.12 New section of Pointer ........................................................................................................ 43

6.2.12.1 Use pointer as local variable. ...................................................................................... 44

6.2.12.2 Purpose of using passing pointer ................................................................................ 46

6.2.12.3 Use ptr as class data member ..................................................................................... 48

6.2.13 New section of reference .................................................................................................... 51

6.2.13.1 Use reference as local variable ................................................................................... 52

6.2.13.2 Use reference as parameter of function (passing reference) ..................................... 53

6.2.13.3 Purpose of using passing reference ............................................................................ 54

6.2.13.4 Use reference as class data member .......................................................................... 56

6.2.13.5 Example to show the differences between reference and pointer ............................ 58

Page 3: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

3

6.2.14 Old section of Pointer ......................................................................................................... 59

6.2.14.1 Compare passing value, pointer,reference ................................................................. 62

6.2.14.2 Simple example of pointer to int ................................................................................ 63

6.2.14.3 Example pointer of struct ........................................................................................... 64

6.2.14.4 Example pointer of class ............................................................................................. 66

6.2.14.5 Example2 of pointer .................................................................................................... 70

6.2.14.6 Example3 of pointer .................................................................................................... 72

6.2.14.7 Example4 of pointer .................................................................................................... 73

6.2.14.8 Example5 of pointer .................................................................................................... 75

6.2.14.9 Example6 of pointer .................................................................................................... 77

6.2.15 Auto_ptr .............................................................................................................................. 79

6.2.15.1 auto_ptr issue ............................................................................................................. 81

6.2.16 Heap memory Vs Stack memory ......................................................................................... 81

6.2.17 String ................................................................................................................................... 84

6.3 Decision making (if..else and switch case) .................................................................................. 89

6.4 Loops ........................................................................................................................................... 90

6.4.1 Simple example of loops ..................................................................................................... 90

6.4.2 Another example of loops ................................................................................................... 91

6.5 Pass by value Vs Pass by Reference ............................................................................................ 93

6.6 Pass by Reference Vs Pass by pointer ......................................................................................... 95

6.6.1 Example1 of passing reference and passing pointer .......................................................... 95

6.6.2 Example2 of passing reference and passing pointer .......................................................... 97

6.6.3 Example3 of passing reference and passing pointer .......................................................... 98

6.7 Passing an array ........................................................................................................................ 100

7 Advance C++ ...................................................................................................................................... 101

7.1 C++ class and object oriented fundamental ............................................................................. 101

7.1.1 Class .................................................................................................................................. 102

7.1.1.1 Example1 simplest class ................................................................................................ 102

7.1.1.2 Example2 of Simplest Inheritance ................................................................................ 102

7.1.1.3 Example3 of simplest inheritance ................................................................................. 103

7.1.1.4 Example4 of object instance and all type of methods access to public section ........... 105

7.1.1.5 Example5 of friend function and friend class access to public section ........................ 107

Page 4: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

4

7.1.1.6 Example6 of child’s instance and child’s method access to parent public section...... 109

7.1.1.7 Example7 of wihin class all type of methods access to private section ....................... 110

7.1.1.8 Example8 of friend function and friend class access to Private section ....................... 112

7.1.1.9 Example9 of within class, its methods access to protected section ............................. 113

7.1.1.10 Example10 of friend function and friend class access to protected section ............ 115

7.1.1.11 Example11 child class access to parent protected ................................................... 117

7.1.1.12 Example12 about inheritance virtual function ......................................................... 118

7.1.1.13 Example13 about inheritance without virtual function ............................................ 120

7.1.1.14 Example14 about inheritance abstract base class .................................................... 123

7.2 Review about class and inheritance again ................................................................................ 125

7.2.1 Public ................................................................................................................................. 126

7.2.2 Private ............................................................................................................................... 126

7.2.3 Protected ........................................................................................................................... 126

7.2.4 Example of inheritance without virtual function .............................................................. 127

7.2.5 Example of inheritance with virtual function ................................................................... 129

7.2.5.1 Example of inheritance without virtual function .......................................................... 129

7.2.5.2 Example of inheritance with virtual function ............................................................... 130

7.2.6 Abstract class (pure virtual) .............................................................................................. 132

7.2.6.1 Example1 of abstract class ............................................................................................ 132

7.2.6.2 Example2 of abstract class ............................................................................................ 134

7.2.6.3 Overloading constructor ............................................................................................... 136

7.2.6.3.1 Example1 of overloading constructor ..................................................................... 136

7.2.6.3.2 Example 2 of overloading constructor .................................................................... 138

7.2.6.4 Virtual Destructor ......................................................................................................... 140

7.2.6.4.1 Example of not using virtual destructor ................................................................. 140

7.2.6.4.2 Example of using virtual destructor ........................................................................ 142

7.2.6.5 There is no virtual constructor in C++ ........................................................................... 143

7.2.7 Friend function .................................................................................................................. 143

7.3 File stream ................................................................................................................................. 145

7.3.1 Example of open file for writing ........................................................................................ 145

7.3.2 Example of open file for reading ....................................................................................... 146

7.3.3 Friend class ........................................................................................................................ 147

Page 5: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

5

7.3.4 Example of using legacy object ......................................................................................... 149

7.3.5 This pointer ....................................................................................................................... 151

7.3.6 Overloading functions Vs Function Template ................................................................... 153

7.3.6.1 Example of overloading functions. ............................................................................... 153

7.3.6.2 Example of Template Function ..................................................................................... 155

7.3.6.3 Another example of Template Class/Typename ........................................................... 156

7.4 Multiple inheritance.................................................................................................................. 157

7.4.1 Example1 of multiple inheritance ..................................................................................... 157

7.4.2 Example2 of multiple inheritance ..................................................................................... 159

7.5 Bit fields .................................................................................................................................... 160

7.5.1 Example1, print out year 2013 in binary ........................................................................... 160

7.5.2 Xor operation .................................................................................................................... 162

7.5.2.1 Example of xor operation again (turn on/off bit) ......................................................... 164

7.5.2.2 Example of reading out data in certain bits of bytes .................................................... 166

7.5.2.3 Example of packing data into 2 bytes without shifting and masking ........................... 169

7.5.2.4 Example of pack 10 bytes of header into char array .................................................... 171

7.6 Error handling, try throw catch, assert ..................................................................................... 175

7.7 Namespace ................................................................................................................................ 176

7.7.1 Example1 of using namespace .......................................................................................... 176

7.7.2 Example2 of using namespace .......................................................................................... 177

7.8 Singleton object ........................................................................................................................ 178

7.9 Example of implementing Jovial compool in C++ ..................................................................... 180

7.9.1 Using static function to implement Jovial compool .......................................................... 180

7.9.2 Using singleton object to implement Jovial compool ....................................................... 182

7.10 Copy constructor Vs Assignment operator ............................................................................... 185

7.10.1 Example1 of copy constructor and assignment operator ................................................. 185

7.11 Prevent other people to copy/use your internal objects. ........................................................ 187

7.12 Casting ....................................................................................................................................... 189

7.12.1 const_cast ......................................................................................................................... 189

7.12.2 static_cast ......................................................................................................................... 190

7.12.3 dynamic_cast .................................................................................................................... 191

7.12.4 reinterpret_cast ................................................................................................................ 193

Page 6: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

6

7.13 Standard Template Library (STL) ............................................................................................... 194

7.13.1 Vector ................................................................................................................................ 194

7.13.2 List ..................................................................................................................................... 196

7.13.3 Map ................................................................................................................................... 198

7.13.4 Queue (FIFO) ..................................................................................................................... 200

7.13.5 Deque ................................................................................................................................ 201

7.13.6 Stack (LIFO) ....................................................................................................................... 203

7.14 Thread ....................................................................................................................................... 204

7.14.1 Window thread example2 (_beginthreadex) .................................................................... 204

7.14.2 Window thread example3 Createthread (standard C) ..................................................... 206

7.14.3 Linux thread ...................................................................................................................... 208

7.15 Semaphore ................................................................................................................................ 209

7.15.1 Window semaphore .......................................................................................................... 209

7.15.2 Linux semaphore ............................................................................................................... 211

7.16 Critical section ........................................................................................................................... 213

7.16.1 Window critical section ..................................................................................................... 213

7.17 Mutex ........................................................................................................................................ 215

7.17.1 Window mutex .................................................................................................................. 215

7.17.2 Linux mutex critical section ............................................................................................... 217

7.18 Interprocess Communication (IPC) ........................................................................................... 219

7.18.1 Window socket (winsock2) ............................................................................................... 219

7.18.1.1 TCP Server ................................................................................................................. 219

7.18.1.2 TCP client ................................................................................................................... 220

7.18.1.3 UDP Server ................................................................................................................ 222

7.18.1.4 UDP client .................................................................................................................. 224

7.18.2 Linux UPD socket ............................................................................................................... 225

7.18.2.1 UDP server ................................................................................................................ 225

7.18.2.2 UPD client .................................................................................................................. 226

7.18.2.3 TCP Server ................................................................................................................. 228

7.18.2.4 TCP Client .................................................................................................................. 229

7.18.3 Linux Shared memory ....................................................................................................... 230

7.18.3.1 Server shared memory .............................................................................................. 230

Page 7: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

7

7.18.3.2 Client shared memory ............................................................................................... 231

7.18.4 Linux Message queue ........................................................................................................ 232

7.18.4.1 Receive from queue .................................................................................................. 232

7.18.4.2 Sending to queue ...................................................................................................... 233

8 C++ 11 ............................................................................................................................................... 234

8.1 auto type and decltype ............................................................................................................. 235

8.2 for_each .................................................................................................................................... 236

8.3 Lambda expression ................................................................................................................... 237

8.3.1 Example1,how to define lambda function expression ..................................................... 237

8.3.2 Example2, how to use lambda function ........................................................................... 238

8.3.3 Example3,another example of using lambda function ..................................................... 239

8.4 Range-Based for loop ................................................................................................................ 240

8.4.1 Example1, range –based for loop ..................................................................................... 240

8.4.2 Example2,modify array data ............................................................................................. 241

8.5 Initialization ............................................................................................................................... 242

8.5.1 Example1, initialization ..................................................................................................... 242

8.5.2 Example2, new way of initialize data members ............................................................... 243

8.6 Using base class methods and constructors ............................................................................. 243

8.7 override specifier ...................................................................................................................... 245

8.8 Final keyword ............................................................................................................................ 246

8.8.1 Example1, don’t allow override final method .................................................................. 246

8.8.2 Example2, don’t allow inherit to final class ...................................................................... 247

8.9 move ......................................................................................................................................... 248

8.9.1 example1, move simple data as string .............................................................................. 248

8.9.2 example2, move one vector to another vector ................................................................ 249

8.10 enum class ................................................................................................................................. 250

8.11 Define function with delete keyword ....................................................................................... 250

8.12 Thread ....................................................................................................................................... 251

8.12.1 Example1, without calling thread join ( ) .......................................................................... 252

8.12.2 Example2 of calling thread join( ) ..................................................................................... 253

8.12.3 Example3, calling thread detach( ).................................................................................... 254

8.12.4 Example4, multi-threading ............................................................................................... 255

Page 8: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

8

8.12.5 Multithreading and mutex ................................................................................................ 256

8.13 unique_ptr ................................................................................................................................ 258

8.14 shared_ptr ................................................................................................................................. 259

8.15 weak_ptr ................................................................................................................................... 261

Table 1 Data types ...................................................................................................................................... 28

Page 9: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

9

1 Introduction This tutorial has been prepared for people who want to learn C++ start from basic to advanced

concepts. I am going to use a lot of examples to discuss with you in each area. I am strongly

believed in practical way more than theory.

I am going to use Eclipse IDE to write, compile and run. You can download Eclipse IDE at

http://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/l

una/SR2/eclipse-cpp-luna-SR2-win32-x86_64.zip

After download, unzip this Eclipse Luna file.

Don’t launch Eclipse yet. You need to download the CPP compiler and set up the path first.

Then download MinGW at http://www.mingw.org/wiki/Getting_Started , search for mingw-get-

setup.exe or just click this link here to install mingw-get-setup.exe . Run install this mingw.

After run install complete, you need go to system environment and setup the path in order for eclipse

to pick up MinGW C++ compiler.

Next, you need to download cygwin at http://www.cygwin.com/ , because mingw is a lighter version. It

did not have all the libraries to support all your needs. Run install this setup-x86_64.exe

Finally, after completed install mingw and cygwin, you need go to system environment and setup the

path in order for eclipse to pick up MinGW C++ compiler or cygwin compiler.

o Click Start

o Click Control Panel

o Click System

o Click Advance system settings; you will see

Page 10: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

10

Page 11: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

11

Add these to the path. C:\MinGW\bin;C:\MinGW\msys\1.0\bin; C:\cygwin64\bin;

Now, you are ready to go.

2 Differences between C++ and Java I don’t compare every single thing. I will list out some of the different that good to know for your

learning and job interview.

C++ Java

Class ending with “;”

class cMary {};

Don’t need “;” at the end of class

class cMary {}

struct sMary {}; No struct in Java

union uMary {}; No union in Java

Global function Don’t allow global function. Any function has to have to

Page 12: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

12

void FuncA(); belong to class.

class cMary { void FuncA() { /*body implementation */ } }

Pointer *

int *ptr = NULL;

There is no pointer in Java

this pointer

class cMary { public: int money; //money data member void FuncA(int money) //same name money but it is parameter { this->money = money; //this->money is telling compiler the "money" of data member } };

Java have “this” but it is reference not a pointer. Use dot

instead of -> operator.

class cMary { public int money; //money data member public void FuncA(int money) //same name money but it is parameter { this.money =money; //this.money is telling compiler the "money" of data member } }

Class’s access modifiers:

public, private, protected

By the default without specify in C++, it is

private access.

Class’s access modifiers:

public, private, protected, Package

By the default without specify in Java, it is package access

namespace Don’t have it.

Don’t have it Package

It acting very similar like namespace in C++.

Inheritant – using public keyword

class A {}; class B : public A {};

Inheritant – use extends keyword

class A {} class B extends A {}

Abstract class (pure virtual)

class A {virtual void FuncA() = 0; };

Abstract class (use keyword abstract) abstract class A {abstract void FuncA ();}

pure virtual function Abstract function

Page 13: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

13

virtual function By the fault it is already virtual

Multiple inheritant No multiple inheritant allow

Have copy constructor by default Don’t have default copy constructor. Implement it if it is

a need. Or you can use other cool ways to achieve this.

Using implement Cloneable interface.

Don’t have interace interface interface iMary { int i =10; public void FuncA(); } class cMickey implements iMary { public void FuncA() { }

}In Java, we have interface. It is very much like class. You

can have data members and methods. You can initialize

the data members but you cannot have the implement

body of the methods. All the methods defined in

interface, the class “implements” the interface, have to

have to implement all the methods that defined in the

interface.

A class can implement multiple interfaces. This is the

alternative way to implement multiple inheritance.

Note: starting Java 8 methods of interface can have

implement body if we use keyword “default” infront of

return type.

friend function, friend class Don’t have it

bool boolean

delete No delete. Self garbage collected

char 8 bits char 16 bits Unicode character

long 32 bits long 64 bits

Page 14: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

14

Don’t have it byte 8 bits

There are more C++ data type such as

WORD, DWORD, long long, long double,….

Don’t have it

C++ have unsigned data Java don’t have it

const final

in Java, we use final for const

class instance, can either allocate in stack

or heap

class cMary{}; cMary mary; //stack memory cMary *ptr = new cMary; //heap memory

class cMary{} cMary mary = new cMary(); //class instance is

always in heap memory even though it is not a

pointer

Overload operators Don’t have it

Scope resolution, operator:: Don’t have it

Don’t have it Wrapper class data type. Start with uppercase

Short

Integer

Long

Float

Double

Boolean

Character

Function passing value, pointer, reference Function passing value ONLY

Only one main function for a program Each class can have its own main function. It is handy for

unit-test

Page 15: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

15

3 Eclipse IDE, hello world project Launch Eclipse IDE File->new->C++project

Pick these options, I pick Cygwin GCC because it has better libraries. MinGW is lighter version.

Page 16: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

16

Click Next

Page 17: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

17

Click Finish

Page 18: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

18

Page 19: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

19

4 Microsoft Studio IDE, hello world project Using Microsoft Studio to compile and run my code.

I alsoI used Visual Studio 2012 IDE to write, compile, and run some parts in this tutorial. Look

at the end of this tutorial section 6, I show you how to create an empty console application by

using Visual Studio. Then you can copy and paste my code and run to see the result. You can

use any IDE to compile and execute these examples. Let’s work together!

Launch Visual Studio

Create an console application

Click on File->New->Project.

Select Win32 Console Application.

Page 20: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

20

Change Name, Location, and Solution Name to what you want your project name is and where you want

your project reside. In this example, I keep default name “ConsoleApplication1”, my project will reside

in my local directory C:\Education\

Click Ok, then click Finish

Page 21: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

21

Now, you can copy and paste my code into it, compile and run.

With my project name and my local location, my exe locates at

C:\Education\ConsoleApplication1\Debug. Executable name is “ConsoleApplication1”.

Page 22: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

22

5 C/C++ naming convention In a large scale of project naming convention is very important for reader. It is nice if the whole project

uses same naming convention. Here are a set of rules that I used to use in my code.

Class name starts with small “c” Example: cBank

Struct name starts with small “s” Example: sCustomerInfo

Union name starts with small “u” Example: uBankType

Enum name starts with small “e” Example: eMonthlyReport

Method name starts with upper case Example: DepositMoney

Data member starts with small “m” Example: mSavingBalance

Local variable start with small case Example: interestRate

Pointer variable start with “ptr” Example: ptrCustomerInfo

Try to avoid to use “-“ or “_” in your method name or data member

6 Basics of C++

6.1 Input/Output - cout is for output. - cin is for input. - You can use c language style like printf, scanf,…. - // or /* */ for comments

Launch Eclipse IDE File->new->C++project

Page 23: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

23

Pick these options, I pick Cygwin GCC because it has better libraries. MinGW is lighter version.

Page 24: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

24

Click Next

Page 25: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

25

Click Finish

Page 26: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

26

Update code with these codes #include <iostream> using namespace std; int main() { cout<<"Enter your age: "; int age; cin>>age; cout<<"Your age enter: "<<age<<endl; return 0; } Build and run it Output:

Page 27: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

27

6.2 Data Types

6.2.1 C/C++ basic data types

Beside the list of basic data types in table 1, there are user’s data types such as struct, union, enum,

typedef, class, List, Vector, Map, and so on. I will show you one by one in this tutorial.

Type Name Bytes Other Names Range of Values

int 4 signed –2,147,483,648 to 2,147,483,647

unsigned int 4 unsigned 0 to 4,294,967,295

__int8 1 char –128 to 127

unsigned

__int8 1 unsigned char 0 to 255

__int16 2 short, short int, signed

short int –32,768 to 32,767

unsigned

__int16 2

unsigned short, unsigned

short int 0 to 65,535

__int32 4 signed, signed int, int –2,147,483,648 to 2,147,483,647

unsigned

__int32 4 unsigned, unsigned int 0 to 4,294,967,295

__int64 8 long long, signed long

long

–9,223,372,036,854,775,808 to

9,223,372,036,854,775,807

Page 28: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

28

unsigned

__int64 8 unsigned long long 0 to 18,446,744,073,709,551,615

bool 1 none false or true

char 1 none

–128 to 127 by default

0 to 255 when compiled with /J

signed char 1 none –128 to 127

unsigned char 1 none 0 to 255

short 2 short int, signed short int –32,768 to 32,767

unsigned

short 2 unsigned short int 0 to 65,535

long 4 long int, signed long int –2,147,483,648 to 2,147,483,647

unsigned long 4 unsigned long int 0 to 4,294,967,295

long long 8 none (but equivalent to

__int64)

–9,223,372,036,854,775,808 to

9,223,372,036,854,775,807

unsigned long

long 8

none (but equivalent to

unsigned __int64) 0 to 18,446,744,073,709,551,615

enum varies none See Remarks.

float 4 none 3.4E +/- 38 (7 digits)

double 8 none 1.7E +/- 308 (15 digits)

long double same as

double none same as double

wchar_t 2 __wchar_t 0 to 65,535

WORD 2

DWORD 4

#include <cstdint>

typedef uint8_t CHAR;

typedef uint16_t WORD;

typedef uint32_t DWORD;

typedef int8_t BYTE;

typedef int16_t SHORT;

typedef int32_t LONG;

typedef LONG INT;

typedef INT BOOL;

Table 1 Data types

Page 29: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

29

6.2.2 Struct

In C++, you can define a struct like a class, beside data member you can add methods to struct.

Personally, I hate to see people implementing struct like a class. To me, you define struct for data only.

If you want your object have both data and methods, please define a class.

Note: There are two main parts of struct/class, there are several ways to name them. You can call like

this, either way is fine; 1) methods or member functions, 2) attributes or data members. People call

them either way.

6.2.2.1 Struct example #include <iostream> #include <string> using namespace std; //for cout struct sBAE { //by default it is public. string mIndustry; int mNumEmployees; string mRank; }; int main() { sBAE bae; // struct Instance bae.mIndustry = "DoD"; bae.mNumEmployees = 90000; bae.mRank = "2nd biggest"; cout << "Industry: " << bae.mIndustry << endl; cout << "Number of Employees: " << bae.mNumEmployees << endl; cout << "Ranking: " << bae.mRank << endl; return 0; }

Build and run

Output:

Page 30: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

30

6.2.2.2 Another example of struct which can have both data and method

As I mention before, some developers define struct like a class. Here how you can implement your

struct like a class in C++ but I am not recommended.

#include <iostream> #include <string> using namespace std; //for cout struct sEmployee//you can change struct to class, it should work the same { //by default it is public. or you can specify it public: void SetName(string name); void SetDOB(string dayofbirth); void SetYearOfService(int yrs); void SetSalary(double salary); void PrintInfo(); private: string mName; string mDOB; int mYrs; double mSalary; }; void sEmployee::SetName(string name) { mName = name; } void sEmployee::SetDOB(string dob)

Page 31: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

31

{ mDOB = dob; } void sEmployee::SetYearOfService(int yrs) { mYrs = yrs; } void sEmployee::SetSalary(double salary) { mSalary = salary; } void sEmployee::PrintInfo() { cout << "Name: " << mName << endl; cout << "Day of Birth: " << mDOB << endl; cout << "Years of service: " << mYrs << endl; cout << "Salary: " << mSalary << endl; } int main() { sEmployee emp; // struct Instance emp.SetName("Mickey Nguyen"); emp.SetDOB("01-01-1990"); emp.SetYearOfService(10); emp.SetSalary(50000.01); emp.PrintInfo(); return 0; }

Compile and run

Output:

Page 32: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

32

6.2.2.3 Another example of struct, struct can inherit to struct, or inherist to class

Another example of struct, in this example I want to show that you can have struct inherts to struct or struct inherits to class or other way around. Again, it looks ugly and I don’t recommend it. #include <iostream> using namespace std; class cA { public: cA(); ~cA(); void Print(); }; cA::cA() { } cA::~cA() { } void cA::Print() { cout << "Mickey Nguyen" << endl; } struct cB : public cA { }; int main() { cB b; b.Print();

Page 33: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

33

return 0; } Compile and run Output:

6.2.3 Union

Although similar to struct, the union type is different in that all fields share the same memory position.

Therefore, the size of a union is the size of the largest field it contains.

All fields share the same memory position. This means that the union type can only be used to store

one value at a time, because when the last field set, it will overwrite the value of the others field.

#include <iostream> #include <stdio.h> using namespace std; union uMyUnion { unsigned char c; // 1 byte short s; // 2 bytes int i; // 4 bytes. This is a largest size therefore it is a size of this union }; int main() { uMyUnion u; u.c = 0xFF; //set all 1s in first byte

Page 34: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

34

printf("c field: 0x%X \n", u.c); u.s = 100; cout << "s field: " << u.s << endl; printf("Now c field has weird value, overwrite by s. c field: 0x%X \n", u.c); //c field overwrite by s field u.i = 55555; cout << "i field: " << u.i << endl; cout << "Now both c and s fields have weird values, overwrite by i \n"; //both Ic and s fields overwrite by i field printf("c field: 0x%X \n", u.c); cout << "s field: " << u.s << endl; return 0; }

Compile and run

Output:

6.2.4 enum

Enum is a user-defined type consisting of a fixed list of named constants.

#include <iostream> using namespace std; int main() { enum eDay { //if it is not initialize, it will start by 0 and incremental by 1.

Page 35: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

35

//In this example, I start with 2 for Monday Monday = 2, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }; eDay day; day = Friday; //set it to Friday if (day == Monday) { cout << "It will be a long day!" << endl; } else { cout << "It is not Monday." << endl; cout << "It is " << day << endl; } return 0; }

Compile and run

Output:

6.2.5 Class

Class is similar to struct but by default its access modifiers default to private. Access modifiers in structs

default to public. Here is a simple class. We will go deeper about class inheritance, polymorphism, and

abstract class in later sections.

#include <iostream> #include <string> using namespace std;

Page 36: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

36

class cMickey { public: cMickey(); //constructor ~cMickey();//desctrutor void Print(); private: int mAge; double mWeight; string mName; }; //This is how you should initialize your data member. //You can initial these attributes inside of your constructor but people saying it is good for compiling time if we initialize data member outside ‚{‚ as I am doing in this example. cMickey::cMickey() : mAge(40), //initialize mWeight(185.99), //initialize mName("Mickey Nguyen") //initialize { cout << "Calling constructor!" << endl; //Old style of initialize data member. It should work perfectly fine //mAge=40; //mWeight = 185.99; //mName = ‚Mickey Nguyen‛; } cMickey::~cMickey() { cout << "Calling destructor whenever program exit" << endl; } void cMickey::Print() { cout << "Print class Mickey info" << endl; cout << "Name: " << mName << endl; cout << "Age: " << mAge << endl; cout << "Weight: " << mWeight << endl; } int main() { cMickey m; //class Mickey instance m.Print(); return 0; }

Compile and run

Output:

Page 37: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

37

6.2.6 Static data member and static function

Static data member is shared by all objects of the class. Each time we use it, it will keep the value of last

time it had.

Static member function can be called without object instance. You just use scope resolution operator::

to access it. A static member function can only access static data member, other static member function

and any other functions from outside the class. You can treat it as global function. Static member

function does not have “this” pointer.

#include <iostream> #include <string> using namespace std; class cBAESoftwareTeam { public: cBAESoftwareTeam(); //constructor ~cBAESoftwareTeam();//desctrutor static int TakeADonut(); private: static int mDonuts; //static memeber can be shared among objects };

Page 38: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

38

//If you have separate header file(.h) for your class definition and cpp file for implementation. //You have to initialize static member in cpp file otherwise you will get error. int cBAESoftwareTeam::mDonuts = 1; cBAESoftwareTeam::cBAESoftwareTeam() { } cBAESoftwareTeam::~cBAESoftwareTeam() { } int cBAESoftwareTeam::TakeADonut() { return mDonuts++; } int main() { cBAESoftwareTeam mickey; //class Mickey instance cout << mickey.TakeADonut() << " donut gone!" << endl; cBAESoftwareTeam richard; cout << richard.TakeADonut() << " donuts gone!" << endl; cBAESoftwareTeam tom; cout << tom.TakeADonut() << " donuts gone!" << endl; cout << cBAESoftwareTeam::TakeADonut() << " donuts gone!" << endl; return 0; } Compile and run Output:

Page 39: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

39

6.2.7 Typedef

typedef is a keyword in the C and C++ programming languages. The purpose of typedef is to assign

alternative names to existing types

#include <iostream> using namespace std; typedef unsigned short PositiveNumber; struct sMickeyDefined { PositiveNumber i; }; typedef sMickeyDefined MickeyType; int main() { MickeyType mtype; mtype.i = 100; cout << "i value: " << mtype.i << endl; return 0; } Compile and run Output:

6.2.8 Preprocessor directives

We use preprocessor directives in conditional compilation and macro definition

#define, #undef, #ifdef, #ifndef, #if, #endif, #else and #elif

Page 40: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

40

#include <iostream> #include <string> using namespace std; #define NAME "Mickey Nguyen" #ifndef WIFE_NAME #define WIFE_NAME "Miley Nguyen" #endif #define BAE_SYSTEM 90000 #define ROCKWELL_COLLINS 11000 int main() { cout << NAME << endl; cout << WIFE_NAME << endl; #if BAE_SYSTEM > ROCKWELL_COLLINS cout << "BAE System is bigger than Rockwell Collins" << endl; #else cout << "Rockwell Collins is bigger BAE System" << endl; #endif return 0; }

Compile and run

Output:

Page 41: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

41

6.2.9 Predefined macro name

These macros are very useful in you debug print out.

#include <iostream> #include <string> using namespace std; int main() { cout << "Line number " << __LINE__<<endl; cout << "File Name " << __FILE__ <<endl; cout << "Current date " << __DATE__<<endl; cout << "Current time " << __TIME__ <<endl; return 0; }

Compile and run

Output:

6.2.10 Constant

If you don’t want your variables can be modified define them as const.

#include <iostream> #include <string> using namespace std;

Page 42: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

42

int main() { const int i = 5; //i cannot be modify const int j =10; //j cannot be modify int sum = i +j; cout<<"i+j ="<<sum<<endl; return 0; }

Compile and run

Output:

6.2.11 Array Arrays is a fixed-size sequence containers. It contains all the elements of same type. When you

define an array, you have to specify a max size for your need. If you want to have variances sizes

then you should use other type of containers such as vector, list, so on. I will talk about these

containers in Standard Template Library (STL) section.

#include <iostream> using namespace std; #define MAX1 5 #define MAX2 6 int main()

Page 43: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

43

{ int Array1[MAX1]= {1,2,4,8,10}; //create and initialize up to max1 int Array2[MAX2] = {3,5}; //create and initialize the first two, the rest should be zero for (int i =0; i < MAX1; i++) { cout<<"Array1["<<i<<"] = "<<Array1[i]<<endl; } for (int i =0; i < MAX2; i++) { cout<<"Array2["<<i<<"] = "<<Array2[i]<<endl; } return 0; }

Output:

6.2.12 New section of Pointer

I re-write a brand new section of pointer and reference because I think you need to understand pointer

and reference in C++ is very important. You need to understand them deeply so you can have all

confident to do your work daily. Please read all the words and think about what I am saying.

Pointer? Don’t be scared! I am going to use real life example and hope you can understand it deeply.

OK, pointer just like a mail man. What the mail man can do? He can deliver things to the address that

Page 44: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

44

given to him. So, either you give him the address or you have to tell him to talk to another mail man

because the other mail man know the address.

Where we can use the pointer? Any where, local variable, as a parameter of a function, class data

member, don’t recommend user global variable as pointer.

6.2.12.1 Use pointer as local variable. #include <iostream>

#include <string>

using namespace std;

class cInfo

{

public:

int i;

float f;

double d;

string s;

};

void FuncA()

{

int number = 10;

//a brand new local pointer (mail man) has his own address. but don't

have work to do yet

int *ptr = new int;

cout << "ptr address " << ptr << endl;

// give address to mail man. Ptr now point to address of "number1"

ptr = &number;

cout << "number address " << &number << endl;

cout << "ptr address " << ptr << endl;

cout << "ptr value: " << *ptr << endl;

//use pointer of class or struct

//a brand new local pointer (mail man) knows his own address.

cInfo *ptrInfo = new cInfo();

cInfo info;

info.i = 5;

info.f = 5.5f;

info.d = 6.6;

info.s = "Mary";

// give address to mail man. ptrInfo point to address of "info"

ptrInfo = &info;

cout << "info address " << &info << endl;

cout << "ptrInfo address " << ptrInfo << endl;

cout << "ptrInfo->i value: " << ptrInfo->i << endl;

cout << "ptrInfo->f value: " << ptrInfo->f << endl;

cout << "ptrInfo->d value: " << ptrInfo->d << endl;

cout << "ptrInfo->s value: " << ptrInfo->s << endl;

delete ptr;

Page 45: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

45

delete ptrInfo;

}

void FuncB()

{

int number = 15;

//mail man is not existing yet, did not has his own address, he is

homeless (NULLL) now

int *ptr = NULL;

cout << "ptr address " << ptr << endl;

// give address to mail man. Ptr now point to address of "number1", ptr

is alive and has his address as number

ptr = &number;

cout << "ptr address " << ptr << endl;

cout << "ptr value: " << *ptr << endl;

cout << "number address " << &number << endl;

cInfo *ptrInfo = new cInfo();

//initialize one item, print out all items.

ptrInfo->i =20;

cout << "ptrInfo address " << ptrInfo << endl;

cout << "ptrInfo->i value: " << ptrInfo->i << endl;

cout << "ptrInfo->f value: " << ptrInfo->f << endl;

cout << "ptrInfo->d value: " << ptrInfo->d << endl;

cout << "ptrInfo->s value: " << ptrInfo->s << endl;

delete ptrInfo;

}

int main()

{

FuncA();

FuncB();

return 0;

}

Compile and run

Output:

Page 46: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

46

6.2.12.2 Purpose of using passing pointer

There are two main purpose of passing pointer:

- Best performance because you just pass the address where the pointer currently point to.

Imagine if you pass a big giant class/struct which have huge number of data members by actual

values, there are a lot of copying memories.

- If the function needs to modify its parameter value.

#include <iostream>

#include <string>

using namespace std;

class cInfo

{

public:

int i;

float f;

double d;

string s;

};

void FuncA(int *ptrInt, cInfo *ptrInfo) // use pointer in parameters

{

Page 47: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

47

*ptrInt = 20;

ptrInfo->i = 10;

ptrInfo->f = 9.9f;

ptrInfo->d = 11.11;

ptrInfo->s = "MH";

}

int main()

{

int number = 10; //variable

cInfo info; //variable

info.i = 5;

info.f = 5.5f;

info.d = 6.6;

info.s = "Mary";

int *ptrInt = new int;

ptrInt = &number;

cInfo *ptrInfo = new cInfo();

ptrInfo = &info;

cout << "Values before pass in function: " << endl;

cout << "*ptrInt: " << *ptrInt << endl;

cout << "ptrInfo->i value: " << ptrInfo->i << endl;

cout << "ptrInfo->f value: " << ptrInfo->f << endl;

cout << "ptrInfo->d value: " << ptrInfo->d << endl;

cout << "ptrInfo->s value: " << ptrInfo->s << endl;

//passing actual pointers

FuncA(ptrInt, ptrInfo);

cout << "Values get updated after function return:" << endl;

cout << "*ptrInt: " << *ptrInt << endl;

cout << "ptrInfo->i value: " << ptrInfo->i << endl;

cout << "ptrInfo->f value: " << ptrInfo->f << endl;

cout << "ptrInfo->d value: " << ptrInfo->d << endl;

cout << "ptrInfo->s value: " << ptrInfo->s << endl;

cout<<"check local value after function return"<<endl;

cout << "info.i value: " << info.i << endl;

cout << "info.f value: " << info.f << endl;

cout << "info.d value: " << info.d << endl;

cout << "info.s value: " << info.s << endl;

//or passing address of data that pointers point to

FuncA(&number, &info);

cout << "Values get updated after function return:" << endl;

cout << "*ptrInt: " << *ptrInt << endl;

cout << "ptrInfo->i value: " << ptrInfo->i << endl;

cout << "ptrInfo->f value: " << ptrInfo->f << endl;

cout << "ptrInfo->d value: " << ptrInfo->d << endl;

Page 48: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

48

cout << "ptrInfo->s value: " << ptrInfo->s << endl;

cout<<"check local value after function return"<<endl;

cout << "info.i value: " << info.i << endl;

cout << "info.f value: " << info.f << endl;

cout << "info.d value: " << info.d << endl;

cout << "info.s value: " << info.s << endl;

delete ptrInt;

delete ptrInfo;

return 0;

}

Compile and run

Output:

6.2.12.3 Use ptr as class data member #include <iostream>

#include <string>

using namespace std;

class cInfo

{

public:

int i;

float f;

double d;

Page 49: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

49

string s;

};

class cMary

{

public:

cMary();

~cMary();

void FuncA(cInfo *,int * );

void Info();

public:

int *ptrTest; //use pointer as data member

cInfo *ptrInfoTest; //use pointer as data member

private:

cInfo *ptrInfo; //use pointer as data member

int *ptrInt; //use pointer as data member

};

cMary::cMary():ptrInfo(new cInfo()),ptrInt(new int),ptrTest(new

int),ptrInfoTest(new cInfo())

{

}

cMary::~cMary()

{

delete ptrTest;

delete ptrInfoTest;

delete ptrInfo;

delete ptrInt;

}

void cMary::FuncA( cInfo *ptrInfo,int *ptrInt)

{

//modify the data passing in parameter

this->ptrInfo =ptrInfo;

this->ptrInt = ptrInt;

this->ptrInfo->i = 10;

this->ptrInfo->f =11.11f;

this->ptrInfo->d= 12.12;

this->ptrInfo->s ="MH";

*this->ptrInt = 20;

}

void cMary::Info()

{

cout<<this->ptrInfo->i<<endl;

cout<<this->ptrInfo->f<<endl;

cout<<this->ptrInfo->d<<endl;

cout<<this->ptrInfo->s<<endl;

cout<<*this->ptrInt<<endl;

}

int main()

{

cInfo info;

Page 50: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

50

info.i =5;

info.f =6.6f;

info.d =7.7;

info.s="Mickey";

int number =9;

cMary m; //create a normal instance

m.FuncA(&info,&number);

m.Info();

cout<<endl;

cMary *ptr = new cMary();//create ptr instance

ptr->FuncA(&info,&number);

ptr->Info();

cout<<endl;

//data are ptr type

cInfo *ptrInfo = new cInfo();

ptrInfo->i = 5;

ptrInfo->f = 6.6f;

ptrInfo->d = 7.7;

ptrInfo->s = "Mickey";

int *ptrInt =new int;

*ptrInt =10;

//using normal instance to call

m.FuncA(ptrInfo,ptrInt);

m.Info();

cout<<endl;

//using ptr instance to call

ptr->FuncA(ptrInfo,ptrInt);

ptr->Info();

//without allocate memory in constructor ptrTest(new

int),ptrInfoTest(new cInfo())

//ptrTest and ptrInfoTest are not existing yet, cannot assign value to

them

//all codes at below will be crashed at run time

*m.ptrTest =15;

m.ptrInfoTest->i =3;

m.ptrInfoTest->f =3.33f;

m.ptrInfoTest->d = 4.4;

m.ptrInfoTest->s ="Patrick";

cout<<endl;

cout<<*m.ptrTest<<endl;

cout<<m.ptrInfoTest->i<<endl;

cout<<m.ptrInfoTest->f<<endl;

cout<<m.ptrInfoTest->d<<endl;

cout<<m.ptrInfoTest->s<<endl;

//without allocate memory you can assign it point to existing other

pointer

//m.ptrTest = ptrInt;

//m.ptrInfoTest = ptrInfo;

Page 51: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

51

//delete order is very important

//make sure when delete a pointer, it will not kill other pointer

accidentally if it is in use

delete ptrInt;

delete ptrInfo;

delete ptr;

return 0;

}

Output:

6.2.13 New section of reference

What is reference? Make sure you understand that reference and pointer are two different things.

Here is explanation in real life. Reference to these data type: int, float, double, string, it just likes the

address of a single house. Reference to struct/class , it just likes the address of the main building of

apparterment, which may have many sub-address. So, the different between reference and pointer is

reference to address of either house/main building “WILL NOT” change, the pointer is a mail man, we

can assign pointer to different address.

You can use reference as local variable, passing reference, reference as class data member, try to use

avoid reference as global variable.

Page 52: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

52

6.2.13.1 Use reference as local variable #include <iostream> #include <string> using namespace std; class cInfo { public: int i; float f; double d; string s; }; void FuncA() { int i = 10; int & number = i; //It has to reference to an existing address. In this case it is address of i cout << "address of i: " << &i << endl; cout << "address of number: " << &number << endl; cout << "value of number: " << number << endl; cInfo info; info.i = 5; info.f = 5.5f; info.d = 6.6; info.s = "Mary"; cInfo & refInfo = info;//It has to reference to an existing address. In this case it is address of info cout << "info address " << &info << endl; cout << "refInfo address " << &refInfo << endl; cout << "ptrInfo->i value: " << endl; cout << "ptrInfo->i value: " << refInfo.i << endl; cout << "ptrInfo->f value: " << refInfo.f << endl; cout << "ptrInfo->d value: " << refInfo.d << endl; cout << "ptrInfo->s value: " << refInfo.s << endl; } int main() { FuncA(); return 0; } Compile and run

Output:

Page 53: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

53

6.2.13.2 Use reference as parameter of function (passing reference) #include <iostream> #include <string> using namespace std; class cInfo { public: int i; float f; double d; string s; }; void FuncA(int &number, cInfo & info) // use reference in parameters { cout << "number address " << &number << endl; cout << "number value: " << number << endl; cout << "info address " << &info << endl; cout << "info.i value: " << info.i << endl; cout << "info.f value: " << info.f << endl; cout << "ptinfo.d value: " << info.d << endl; cout << "info.s value: " << info.s << endl; }

Page 54: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

54

int main() { int myNumber = 10; //variable cInfo myInfo; //variable myInfo.i = 5; myInfo.f = 5.5f; myInfo.d = 6.6; myInfo.s = "Mary"; cout << "address of number: " << &myNumber << endl; cout << "address of info: " << &myInfo << endl; FuncA(myNumber, myInfo); //calling passing reference return 0; } Compile and run

Output:

6.2.13.3 Purpose of using passing reference

There are two main purpose of passing reference:

- Best performance because you just pass the address where the pointer currently point to.

Imagine if you pass a big giant class/struct which have huge number of data members by actual

values, there are a lot of copying memories.

- If the function needs to modify its parameter value.

Page 55: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

55

#include <iostream> #include <string> using namespace std; class cInfo { public: int i; float f; double d; string s; }; void FuncA(int & refInt, cInfo & refInfo) // use pointer in parameters { refInt = 20; refInfo.i = 10; refInfo.f = 9.9f; refInfo.d = 11.11; refInfo.s = "MH"; } int main() { int number = 10; //variable cInfo info; //variable info.i = 5; info.f = 5.5f; info.d = 6.6; info.s = "Mary"; cout << "Values before pass in function: " << endl; cout << "number " << number << endl; cout << "info.i value: " << info.i << endl; cout << "info.f value: " << info.f << endl; cout << "pinfo.d value: " << info.d << endl; cout << "info.s value: " << info.s << endl; FuncA(number, info); cout << "Values get updated after function return:" << endl; cout << "number " << number << endl; cout << "info.i value: " << info.i << endl; cout << "info.f value: " << info.f << endl; cout << "pinfo.d value: " << info.d << endl; cout << "info.s value: " << info.s << endl; return 0; }

Page 56: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

56

Compile and run

Output:

6.2.13.4 Use reference as class data member #include <iostream> #include <string> using namespace std; class cInfo { public: int i; float f; double d; string s; }; class cMary { public: cMary(cInfo &, int &); //constructor. I have to have to initialize the reference variable. cInfo & refInfo; //use reference as data member int & refInt; //use reference as data member }; cMary::cMary(cInfo &info, int & i) : refInfo(info), refInt(i) //have to initialize reference data member { }

Page 57: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

57

void FuncA() { int number; //variable cInfo myInfo; //variable cMary m(myInfo,number);//create ruby instance m.refInt = 20; //set 20 for refInt m.refInfo.i =5; //set 5 for refInfo.i m.refInfo.f =5.5; //set 5.5 for refInfo.f m.refInfo.d=6.6; //set 6.6 for refInfo.d m.refInfo.s = "Mary";//set "Ruby" for refInfo.s cout << "number address " << &number << endl; cout << "refInt address " << &m.refInt<<endl; cout << "refInt value: " << m.refInt << endl; cout << "myInfo address " << &myInfo << endl; cout << "refInfo address " << &m.refInfo << endl; cout << "refInfo->i value: " << m.refInfo.i << endl; cout << "refInfo->f value: " << m.refInfo.f << endl; cout << "refInfo->d value: " << m.refInfo.d << endl; cout << "refInfo->s value: " << m.refInfo.s << endl; } int main() { FuncA(); return 0; } Compile and run

Output:

Page 58: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

58

6.2.13.5 Example to show the differences between reference and pointer #include <iostream> #include <string> using namespace std; void FuncA() { int number1 = 5; //variable int number2 = 10; //variable int *ptr = new int; //mail man don't know any address, you can code like this int *ptr =NULL; ,too. ptr = &number1; //tell mail man the address of number1. cout << "ptr has address: " << ptr << endl; cout << "ptr has value: " << *ptr << endl; ptr = &number2; //tell mail man to address of number2. Reassign to new address cout << "ptr has new address: " << ptr << endl; cout << "ptr has new value: " << *ptr << endl; //Reference to one and one address only, you cannot reassign like pointer int & ref = number1; cout << "ref has address: " << &ref << endl; cout << "ref has value: " << ref << endl; //& ref = number2; //will not allow you to have the address of number2 ref = number2; cout << "ref should have the same address: " << &ref << endl; //the address is still the same, unchanged cout << "ref has value: " << ref << endl;

Page 59: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

59

ref = NULL; } int main() { FuncA(); return 0; }

Compile and run

Output:

6.2.14 Old section of Pointer

Important Note: you will see sometime I initialize pointer to NULL, sometime I allocate memory using

“new”. So when you should initial to NULL when you declare a pointer and when you dynamic allocate

memory using “new”? Ans: initial to NULL when you intent to assign it to point to some existing

address assign it to point to existing pointer (NULL is not existing yet, cannot use the pointer until it

point to some living address). Using dynamic allocation memory make it alive by itself and you plan to

assign value to it.

After you went thru the new section of pointer, now I want you to read the old section of pointer that I

wrote it a while ago. You can understand it more deeply I hope.

Page 60: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

60

A pointer is a variable whose value is the value of variable that is currently point to. We will discuss

what is the different of heap memory and stack memory in next section. Most of programmers don’t

even know and don’t even cares where of their local/global variable allocate memory in the heap or in

the stack. We should know these things, sometime you accidentally run out (overflow) of heap/stack

memory.

My wife Sally live in 2222 Canyon Dr. My son Patrick lives in an apartment 3333 Wayne St, his room Number is 101. My daughter Sarah lives in this same apartment 3333, her room number is 106. Because I am their father, I know where they live. If I ask you to stop by their apartment to deliver a few things for my kids but I don’t tell you where they live, you cannot help me. Am I right? Now, if I provide to you my wife address and my kids address to deliver for Sally $1000, a bag of rice for Patrick and a bag of orange for Sarah. Thanks for your help! I know you know how to get to their places and get things done as I asked. So, in this example “Sally” live individual address (just pretend like a single varialbe like int/double/float), “Patrick” and “Sarah” are also variables but both live in same apartment (just think like a struct/class). All of them have to live at some addresses, if you know their address, you can give/change things for them. And in this example, I can go to my wife and kids apartment and deliver things for them but I ask you to do it, in this case you are a “pointer”. I provide to you their addresses; I gave you money, rice and oranges to deliver for them.

Now, we deal with programming language. int num1 = 4; //0xABBCCDDE

struct sNumber { int num2; //0xEFFAABBC int num3; //0xCDDEEFFA };

sNumber s; s.num2 = 5; // initial value s.num3 = 6; // initial value

I just pretend that num1 live at 0xABBCCDDE and num2, num3 live at //0xEFFAABBC and //0xCDDEEFFA So, in programming, if I directly change their values, I can do it easily as follow

num1 = 7; //change directly s.num2 = 8;//change directly s.num3 = 9;//change directly

if I want to use pointer to do it, what I need to do? I need to give pointer their addresses, I also provide the new values so pointer can replace the old value for me. int *ptr1 = NULL; ptr1 = &num1; *ptr1 = 10; sNumber *ptr2 = NULL;

2222 Canyon Dr. Sally Nguyen

3333 Wayne St, Grand

Prairie, TX 75052

100 101

Patrick

102 103

104 105 106

Sarah

107

108 109 110 111

Some addresses in

PC

AB BC CD DE

EF FA AB BC

CD DE EF FA

Page 61: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

61

ptr2 = &s; ptr2->num2 = 11; ptr2->num3 = 12;

#include <iostream> #include <string> using namespace std; int main() { int num1 = 4; //0xABBCCDDE struct sNumber { int num2; //0xEFFAABBC int num3; //0xCDDEEFFA }; sNumber s; s.num2 = 5; // initial value s.num3 = 6; // initial value cout << "num1: " << num1<<endl; cout << "num2: " << s.num2 << endl; cout << "num3: " << s.num3 << endl; cout << endl; cout << "Change directly" << endl; num1 = 7; //change directly s.num2 = 8;//change directly s.num3 = 9;//change directly cout << "num1: " << num1 << endl; cout << "num2: " << s.num2 << endl; cout << "num3: " << s.num3 << endl; //now, using pointer to change their values int *ptr1 = NULL; ptr1 = &num1; //that how you provide address to pointer *ptr1 = 10; sNumber *ptr2 = NULL; ptr2 = &s; //that how you provide address to pointer ptr2->num2 = 11; ptr2->num3 = 12; cout << endl; cout << "After using pointer to update:" << endl; cout << "num1: " << num1 << endl; cout << "num2: " << s.num2 << endl; cout << "num3: " << s.num3 << endl; cout << endl; cout << "You can use weird syntax like this to scare people, haha:" << endl; *(&ptr2->num2) = 13; //exactly as ptr2->num2 = 13; *(&ptr2->num3) = 12; //exactly as ptr2->num3 = 12; cout << "num2: " << s.num2 << endl; cout << "num3: " << s.num3 << endl;

Page 62: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

62

return 0; }

Compile and run

Output:

6.2.14.1 Compare passing value, pointer,reference

#include <iostream> #include <string> using namespace std; int Sum1(int n1, int n2) //pass by value { int sum = n1 + n2; return sum; } int Sum2(int * ptr1, int * ptr2) //pass by pointer { //* infront of ptr1 give you a value, without * infront of ptr1, it gives you its address (&). //Please don't do like this &ptr1, just imagine it look like this &&ptr1. //I told you already, if your variable is a ptr, without * infront of it, it gives you its address int sum = *ptr1 + *ptr2; return sum;

Page 63: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

63

} int Sum3(int &n1, int &n2) //pass by reference { int sum = n1 + n2; //*(&n1) = n1. same thing *(&n2) = n2. return sum; } int Sum4(int &n1, int &n2) //pass by reference2 { int sum = *(&n1) + *(&n2); //same thing like n1 + n2. return sum; } int main() { int num1 = 2; int num2 = 3; cout << "Pass by value: " << Sum1(num1, num2) << endl; cout << "Pass by pointer: " << Sum2(&num1, &num2) << endl; cout << "Pass by reference1: " << Sum3(num1, num2) << endl; cout << "Pass by reference2: " << Sum4(num1, num2) << endl; return 0; }

Compile and run

Output:

6.2.14.2 Simple example of pointer to int #include <iostream> #include <string>

Page 64: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

64

using namespace std; int main() { int Luna = 0; //zero dollar; int *ptr1 = NULL;//int *ptr1 = new int; should work fine for you. ptr1 = &Luna; //mail man ptr1, here I give you address of Luna *ptr1 = 100; //mail man ptr1, I want you to give Luna $100 bucks. cout << "Luna: $" << Luna << endl; cout << "Address of Luna " << &Luna << endl; cout << "ptr1 is current point to " << ptr1 << endl; // Remind you again, pointer varialbe without * infront of it, it is its address cout << "ptr1 value :" << *ptr1 << endl; return 0; }

Compile and run

Output:

6.2.14.3 Example pointer of struct #include <iostream> #include <string> using namespace std; int main()

Page 65: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

65

{ struct sKidInfo { string name; int bank; }; sKidInfo info; info.name = "Patrick"; info.bank = 50; sKidInfo *ptrUncle1 = NULL; //sKidInfo *ptrUncle1 = new sKidInfo; should work fine for you ptrUncle1 = &info;//uncle1, I give you kid's info, deliver $100 for Patrick ptrUncle1->bank = 100; //change bank only. Keep name as same for now. If you want to change name, simply do like this uncle1->name ="Garnet"; cout << "Name: " << info.name << endl; //should be still same Patrick. cout << "Bank: " << info.bank << endl; //should be $100 now. cout << endl; sKidInfo * ptrUncleMickey = new sKidInfo; //or =NULL; is ok, too //You want uncleMickey gives $200 buck you don't give him Patrick info. You don't want do like this uncleMickey =&info; //You are mean to me, it is fine, I will ask uncle1, he knows kid's info already. ptrUncleMickey = ptrUncle1; //ptrUncleMickey point to wherever ptrUncle1 point to. Basically, ptrUncleMickey get Patrick infomation from ptrUncle1 ptrUncleMickey->bank = 200; //ptrUncleMickey give Patrick $200 cout << "Now look at the bank of Patrick" << endl; cout << "Name: " << info.name << endl; //should be still same Patrick. cout << "Bank: " << info.bank << endl; //should be $100 now.

delete ptrUncleMickey;

return 0; }

Compile and run

Output:

Page 66: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

66

6.2.14.4 Example pointer of class #include <iostream> using namespace std; class cData1 { public: int a; float b; }; class cData2 { public: cData1 d1; //contain one data member type cData1 }; class cData3 { public: cData1 *d1Ptr; //contain one ptr data member type cData1 }; int main() { cData1 *ptr1 = NULL; //point to NULL which mean did not point to a specific address yet cData2 *ptr2 = NULL; //point to NULL which mean did not point to a specific address yet cData3 *ptr3 = NULL; //point to NULL which mean did not point to a specific address yet cData2 d2; d2.d1.a = 5;

Page 67: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

67

d2.d1.b = 9.99; ptr2 = &d2; //ptr2 point to address & of d2 ptr1 = &ptr2->d1; //ptr1 now point to address & of d1. d1 is not a pointer that why you need & infront of it cout << "ptr1->a: " << ptr1->a << endl; cout << "ptr1->b: " << ptr1->b << endl; cData1 d1; d1.a = 6; d1.b = 10.99; cData3 d3; d3.d1Ptr = &d1; //you need to understand ptr has to point to some address the same data type with its ptr. ptr3 = &d3; //you need to understand ptr has to point to some address the same data type with its ptr. ptr1 = NULL;//reset to null ptr1 = ptr3->d1Ptr;//now ptr1 point to wherever d1ptr point to. Why I don't have & infront of ptr3? because d1ptr is already a pointer. cout << "ptr1->a: " << ptr1->a << endl; cout << "ptr1->b: " << ptr1->b << endl; cData1 *ptr4 = NULL; //point to NULL which mean did not point to a specific address yet ptr4 = ptr1;//ptr4 point to wherever ptr1 point to cout << endl; cout << "ptr4->a: " << ptr4->a << endl; cout << "ptr4->b: " << ptr4->b << endl; return 0; }

Compile and run

Output:

Page 68: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

68

In early days of my career I don’t like pointer much because it is hard for me to understand. As time

went by, I learned something and want to share with you. Hopefully, after you go thur all examples in

this pointer section, you should say it is a piece of cake.

Note: anytime you dynamic allocate memory “new/malloc”, you are using heap memory, local variable,

parameter use stack memory.

OK, I want to give you some explanation before we start. Why we need pointer? Pointer is useful

when we pass an object thru function. We just pass the address of the object only not the actual value.

Deep copy is very expensive in term of performance that why we need to pass the address. A very

simple of example, just a single data type int (not a huge object which include many attributes/data

members). I just want to show you about pointer. Example, a variable num type int “int num”; you

need to understand that computer uses 4 bytes for “num”somewhere int the stack memory, in this case

I assume num’s address is 0xAABBCCDD. If I initialize num =10 which mean at address 0xAABBCCDD

contains 10. Now if I want to change num to 100, normally you just do num =100, the computer will

change the value at address 0xAABBCCDD for you. Now, I have my ptr type int (*int) and I assign

ptr=&num which mean ptr point to address 0xAABBCCDD. Now, beside direct/normal way to change

num to 100 like I did earlier num=100, I am able to use ptr to update the value to 100, do like this *ptr

=100; without “*” ptr is address, if you have “*” infront of it which mean dereference to get the real

value. *ptr =100 which mean update “real value” 100 to address (0xAABBCCDD) of ptr is currently point

to. I give you another example in real life; assume “num int” is “Mickey Nguyen”, and address

0xAABBCCDD is my home address 3333 Wayne St. You can replace/kick “Mickey Nguyen” who is living in

3333 Wayne st to Mr. “Nice Guy”, you can do it by yourself/police. So in programming, you can

replace/update value of your variable/parameter to new value anytime you need to via directly/pointer.

Page 69: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

69

(directly=yourself; pointer=police). What happen if you kick “Mickey Nguyen” out of 3333 Wayne st and

don’t fill in any new person, in this case just like you set ptr to NULL. Follow these examples below to

understand pointer.

When you deal with pointer here are things you need to know.

a) Is my pointer is pointing to any address (&) of a variable yet? It is nice to initialize it to NULL

before use it, just make sure it is not pointing to anywhere that you are not aware of.

b) After you assign pointer point to the address of a variable, you need to understand two things.

1) the “address” of variable is never change. 2) you can change the “value” of the variable

directly or via pointer.

c) You can have many pointers point to the same address of one variable and you can use one of

your pointers to change the value of the variable. It will impact the value of all other pointers.

Because all of your pointer are pointing to the same address, they should have the same value.

d) You can assign a new pointer to point to where other pointer is currently pointing to.

e) You can reassign pointer to point to somewhere else.

f) Pointer is very useful when you pass a struct ora class as parameter in your method/function.

Note: Each time you run this program, your variables will be assigned to different address in memory.

#include <iostream> using namespace std; int main() { int * ptr; int num1 = 10; cout << "num :" << num1 << endl; cout << "&num1 :" << &num1 << endl; //Address(&) of num1 ptr = &num1; //make ptr point to num address (&) cout << "Address of ptr: " << ptr << endl; //Now ptr address is same as num1 cout << "value of *ptr: " << *ptr << endl; //Dereferencing a pointer to get actual value in address (&) cout << "num1 :" << num1 << endl; //num1 new value now cout << "&num1 :" << &num1 << " nerver change"<< endl;//Address is never change int num2 = 20; ptr = &num2; //Reassign ptr to address(&) of num2 cout << "&num2 :" << &num2 <<" nerver change" <<endl; //Address(&) of num1 cout << "Address of ptr: " << ptr << " same as num2"<< endl; //Now ptr address is same as num2 return 0;

Page 70: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

70

} Compile and run Output:

6.2.14.5 Example2 of pointer

This example I want to tell you that you can have many pointers point to the same address if you want

to. If you change the value of the where one pointer point to, it will impact to all other pointer because

all of them point to the same one.

Note: Each time you run this program, your variables will be assigned to different address in memory.

#include <iostream> using namespace std; int main() { int * ptr1 = NULL; int * ptr2 =NULL; int * ptr3 = NULL; int num1 = 10; cout << "&num :" << &num1 << endl; //Address(&) of num1 ptr1 = &num1; //make ptr1 point to address (&) of num1 ptr2 = &num1; //ptr2 point to address (&) of num1. ptr3 = ptr2; //ptr3 point to where ptr2 is currently point to which mean both ptr3 and ptr2 now point to the same address of (&) of num1. it is same thing if you do like this ptr3 = &num1; cout << "Address of ptr1: " << ptr1 << endl; //Now ptr1 address is same as address num1

Page 71: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

71

cout << "value of *ptr1: " << *ptr1 << endl; //Dereferencing a pointer to get actual value in address (&) cout << "Address of ptr2: " << ptr2 << endl; //ptr3 address is same as address (&) of num1 cout << "value of *ptr2: " << *ptr2 << endl; //Dereferencing a pointer to get actual value in address (&) cout << "Address of ptr3: " << ptr3 << endl; //Now ptr3 address is same as where the address of ptr2 is currently point to which mean address (&) of num1 cout << "value of *ptr3: " << *ptr3 << endl; //Dereferencing a pointer to get actual value in address (&) *ptr1 = 66666; //override whatever value that ptr1 currently point to by new value 66666. You can use either ptr1, ptr2,ptr3 to change the value.This technic changes value variable via pointer cout << "&num1 :" << &num1 << endl;//Address is never change cout << "num1 :" << num1 << endl; //num1 new value now cout << "New Value: "<<endl<<endl; cout << "Address of ptr1: " << ptr1 << endl; //Now ptr1 address is same as address num1 cout << "value of *ptr1: " << *ptr1 << endl; //Dereferencing a pointer to get actual value in address (&) cout << "Address of ptr2: " << ptr2 << endl; //ptr3 address is same as address (&) of num1 cout << "value of *ptr2: " << *ptr2 << endl; //Dereferencing a pointer to get actual value in address (&) cout << "Address of ptr3: " << ptr3 << endl; //Now ptr3 address is same as where the address of ptr2 is currently point to which mean address (&) of num1 cout << "value of *ptr3: " << *ptr3 << endl; //Dereferencing a pointer to get actual value in address (&) return 0; }

Compile and run

Output:

Page 72: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

72

6.2.14.6 Example3 of pointer

In this example, I want to tell you, there are more than one way to change the value of your variable. Note: Each time you run this program, your variables will be assigned to different address in memory.

#include <iostream> using namespace std; int main() { int * ptr1 = NULL; int * ptr2 = NULL; int num1 = 10; cout << "num1 :" << num1 << endl; cout << "&num1 :" << &num1 << endl; //Address(&) of num1 ptr1 = &num1; //make ptr1 point to address (&) of num1 ptr2 = &num1; //ptr2 point to address (&) of num1. cout << "Address of ptr1: " << ptr1 << endl; //Now ptr1 address is same as address num1 cout << "value of *ptr1: " << *ptr1 << endl; //Dereferencing a pointer to get actual value in address (&) cout << "Address of ptr2: " << ptr2 << endl; //ptr2 address is same as address (&) of num1 cout << "value of *ptr2: " << *ptr2 << endl; //Dereferencing a pointer to get actual value in address (&) cout << "New Value: " << endl << endl; num1 = 7777; //change num1 to new value directly not using pointer to change it. cout << "num1 :" << num1 << endl; //num1 new value now cout << "&num1 :" << &num1 << endl;//Address is never change

Page 73: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

73

cout << "Address of ptr1: " << ptr1 << endl; //Now ptr1 address is same as address num1 cout << "value of *ptr1: " << *ptr1 << endl; //Dereferencing a pointer to get actual value in address (&) cout << "Address of ptr2: " << ptr2 << endl; //ptr2 address is same as address (&) of num1 cout << "value of *ptr2: " << *ptr2 << endl; //Dereferencing a pointer to get actual value in address (&) return 0; }

Compile and run

Output:

6.2.14.7 Example4 of pointer This example, I want to show you another weird way to change value of variable

#include <iostream> using namespace std; int main() { int * ptr1 = NULL; int * ptr2 =NULL;

Page 74: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

74

int num1 = 10; cout << "num1 :" << num1 << endl; //Address(&) of num1 cout << "&num1 :" << &num1 << endl; //Address(&) of num1 ptr1 = &num1; //make ptr1 point to address (&) of num1 ptr2 = &num1; //ptr2 point to address (&) of num1. cout << "Address of ptr1: " << ptr1 << endl; //Now ptr1 address is same as address num1 cout << "value of *ptr1: " << *ptr1 << endl; //Dereferencing a pointer to get actual value in address (&) cout << "Address of ptr2: " << ptr2 << endl; //ptr2 address is same as address (&) of num1 cout << "value of *ptr2: " << *ptr2 << endl; //Dereferencing a pointer to get actual value in address (&) cout << "New Value: " << endl << endl; *(&num1) = 8888;//We want to put new value 8888 to address (&) of num1. It mays look weird to you but read it out you can understand it, "&" which mean address of num1, "*" which mean dereferencing a pointer for real value. just like you set num1 =8888; cout << "num1 :" << num1 << endl; //num1 new value now cout << "&num1 :" << &num1 << endl;//Address is never change cout << "Address of ptr1: " << ptr1 << endl; //Now ptr1 address is same as address num1 cout << "value of *ptr1: " << *ptr1 << endl; //Dereferencing a pointer to get actual value in address (&) cout << "Address of ptr2: " << ptr2 << endl; //ptr2 address is same as address (&) of num1 cout << "value of *ptr2: " << *ptr2 << endl; //Dereferencing a pointer to get actual value in address (&) return 0; }

Compile and run

Output:

Page 75: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

75

6.2.14.8 Example5 of pointer

In this example, I want to show passing a pointer of struct

#include <iostream> #include <string> using namespace std; struct sMickeyInfo { string Name; int Age; double Weight; }; void PrintMickeyInfo(sMickeyInfo *ptr) { cout << "Name: " << ptr->Name << endl; cout << "Age: " << ptr->Age << endl;; cout << "Weight: " << ptr->Weight << endl; } int main() { sMickeyInfo m; sMickeyInfo *ptrM = NULL; //Create ptrM pointer or you can do like this sMickeyInfo *ptrMjr = new sMickeyInfo(); ptrM = &m; //ptr is can be used until it points to some address. You cannot declare sMickeyInfo *ptrM = NULL; then set ptrM->Name ="Mickey Nguyen" because it still point to NULL. m.Name = "Mickey Nguyen"; m.Age = 20; m.Weight = 185.99; PrintMickeyInfo(ptrM); cout << "create new ptrMjr" << endl;

Page 76: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

76

sMickeyInfo *ptrMjr = NULL; //create ptrMjr pointer or you can do like this sMickeyInfo *ptrMjr = new sMickeyInfo(); ptrMjr = &m; //ptrMjr is can be used until it points to some address. PrintMickeyInfo(ptrMjr); cout << "Now both ptrM and ptrMjr are pointing to same m" << endl; cout << "ptrM:" << endl; PrintMickeyInfo(ptrM); cout << "ptrMjr:" << endl; PrintMickeyInfo(ptrMjr); cout << "Now I am going to change values for m, it will impact both ptrM and ptrMjr since both point m" << endl; m.Name = "Mr. Nice guy"; m.Age = 21; m.Weight = 160.99; cout << "ptrM:" << endl; PrintMickeyInfo(ptrM); cout << "ptrMjr:" << endl; PrintMickeyInfo(ptrMjr); return 0; }

Compile and run

Output:

Page 77: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

77

6.2.14.9 Example6 of pointer

In this example I am showing how to pass an object pointer and also the function return is object

pointer.

#include <iostream> #include <string> using namespace std; class cMickeyInfo { public: //using default contructor and default destructor void GetMickeyPrintInfo(); string mName; int mAge; double mWeight; }; void cMickeyInfo::GetMickeyPrintInfo() { cout << "Name: " << mName << endl; cout << "Age: " << mAge << endl; cout << "Weight: " << mWeight << endl; } class cSanta { public: cSanta(); ~cSanta(); void SetKidInfo(cMickeyInfo *info); cMickeyInfo * GetKidInfo(); void SantaPrintInfo(); private: cMickeyInfo *mKidPtr; string mKidName; int mKidAge; double mKidWeight; }; cSanta::cSanta() { mKidPtr = new cMickeyInfo(); } cSanta::~cSanta() { delete mKidPtr; } void cSanta::SetKidInfo(cMickeyInfo * ptrM) { mKidName = ptrM->mName; mKidAge = ptrM->mAge; mKidWeight = ptrM->mWeight; } cMickeyInfo * cSanta::GetKidInfo()

Page 78: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

78

{ return mKidPtr; } void cSanta::SantaPrintInfo() { cout << "Name: " << mKidName << endl; cout << "Age: " << mKidAge << endl; cout << "Weight: " << mKidWeight << endl; } int main() { //directly use cMickeyInfo object cMickeyInfo m; m.mName = "Mickey Nguyen"; m.mAge = 18; m.mWeight = 140.99; m.GetMickeyPrintInfo(); cMickeyInfo *ptr1 = new cMickeyInfo(); //Create ptr1 and allocate memory in the heap. ptr1 = &m; //point to address of m which contains Name,Age, and Weight cout << endl; cSanta s; cMickeyInfo *ptr2 = new cMickeyInfo(); //create ptr2 and and allocate memory in the heap. or you also can create and intialize to NULL, it should work fine. cMickeyInfo *ptr2 = NULL; s.SetKidInfo(ptr1); // pass ptr1 of mickey object to santa object ptr2 = s.GetKidInfo(); //get ptr1 Mickey info thru santa object, then assign mickey ptr1 values to santa ptr2 s.SantaPrintInfo();

delete ptr1;

delete ptr2; return 0; }

Compile and run

Output:

Page 79: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

79

In my conclusion about pointer, I hope I did not hurt your head yet. OK, just thing like this, a house has

address which contain 1 or many people, which mean an address contain a single data or an struct/class

object. If you are the owner of the house, you know house address, you know how many people are in

the house, you can replace/kick them out directly if you want to. If you need police help you to

replace/kick people, all you need is to tell police come to the address that you provide.

6.2.15 Auto_ptr

auto_ptr will automatically cleanup memory when the object is no longer needed.

#include <iostream> #include <memory> using namespace std; class cA { public: int number; }; void MayHasMemoryIssue() { cA *ptr = new cA; //dynamic allocate memory ptr->number = 10; //If there are a lot of code and function calls between this line and delete ptr //..... //.....

Page 80: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

80

//int bigArray[10000000]; //Increase to 10 mil cause propram crash intentionally //If this function is never return or it crashes at somewhere in the middle of //this block then the delete ptr never has a chance to execute. //the memory never release, we have memory leak delete ptr; } void WillNotHasMemoryIssue() { auto_ptr<cA> p1(new cA); //allocate memory for p1 auto_ptr<cA> p2; //did not allocate memory and did not point to anywhere yet. p1->number = 100; cout << "p2 point to address: " << p2.get() << endl; // Print NULL cout << "p1 point to address: " << p1.get() << endl; // Print non-NULL address //int bigArray[10000000]; //Increase to 10 mil cause propram crash intentionally, however, memory will be release automatically p2 = p1; //p2 takes over ownership of p1.Also, release memory of p1 automatically cout << "p2 point to address: " << p2.get() << endl; // Print NULL cout << "p1 point to address: " << p1.get() << endl; // Print non-NULL address //cout << "p1->number: " << p1->number << endl;//p2 took over ownership already. p1 is gone. should get error at run time cout << "p2->number: " << p2->number << endl; } int main() { MayHasMemoryIssue(); //In this example, it will not crash because we did not make it crashes, turn on the bigArray, it will crash WillNotHasMemoryIssue(); return 0; } Compile and run Output:

Page 81: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

81

6.2.15.1 auto_ptr issue

You just see auto_ptr works beautiful; however, it has a big issue when you use the copy constructor or

assignment operator. When you use copy constructor or assignment operator, they transfer ownership

of its data then the original pointer will be destroyed automatically. You cannot have two object

instances with the same identical values. One instance will take over ownership of the other. You will

not see this problem is at compile time, it will happen at runtime. My suggestion that do not use

auto_ptr unless you know exactly what you are doing.

6.2.16 Heap memory Vs Stack memory

At runtime, when you dynamically allocated memory for your variables such as “new” or “malloc”, it will

use heap memory. We need to manage well memory pool, use “delete” or “free” whenever we are

done. When we run out of heap “memory pool” that mean we have memory leak. We did not release

memory back to the pool after finished using them.

Your local variables and parameters of your method/function will use stack memory.

Other areas such as global variable and your code will use other memory we are not interesting to

discuss at this point. You should not worry/care about these areas.

Stack overflow, it happens when you have a big of nested function calls, example, funcA() calls funcB(),

funcB() calls funcC(), so on and so on. Or you use a very big size of array, example int a[10000000000];

When your program crashes after it runs for a while, either you run out of stack memory or your heap

memory is out. These bugs are hard to detect. Make sure you define/specify enough heap size and

stack size. Also, do not let memory leak happen. There are a few tools out there to help you to detect

these issues. Google valgrind and helgrind. These tools are awesome.

Page 82: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

82

#include <iostream> using namespace std; //a,b and result are using stack memory int FuncA(int a, int b) { int result = a+b; return result; } int main() { int *myArray = new int[20]; //you just allocate 80 bytes from the heap. delete myArray; //release 80 bytes back to the heap memory pool. int bigArray[10000]; //bigArray uses stack memory; int myresult = FuncA(10,20); // myresult uses stack memory cout<<"myresult: "<<myresult<<endl; return 0; }

Compile and run

Output:

Same program as above but I am going to increase bigArray to 10000000 to force stack overflow

happen. Now, your program should crash.

Page 83: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

83

#include <iostream> using namespace std; //a,b and result are using stack memory int FuncA(int a, int b) { int result = a + b; return result; } int main() { int *myArray = new int[20]; //you just allocate 80 bytes from the heap. delete myArray; //release 80 bytes back to the heap memory pool. int bigArray[10000000]; //Increase to 10 mil cause propram crash intentionally int myresult = FuncA(10, 20); // myresult uses stack memory cout << "myresult: " << myresult << endl; return 0; }

No output for this run. Program crash because stack overflow (bigArray variable has a huge size).

If you use Visual Studio 2012 to run, here is error message

Page 84: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

84

6.2.17 String

Note: Because last example is failed, make sure you completed stop break debug from previous run

before you run this example.

In C++, you can have 3 ways to code for string to contain my name “Mickey Trong Nguyen”.

char * name1 = "Mickey Trong Nguyen"; char name2[]= "Mickey Trong Nguyen"; string name3 = "Mickey Trong Nguyen";

So, what is the different? You can use either one. It is up to user reference.

#include <iostream> #include <cstring> using namespace std; int main() { char * name1 = "Mickey Trong Nguyen"; char name2[]= "Mickey Trong Nguyen"; string name3 = "Mickey Trong Nguyen"; cout<<"sizeof name1: "<<sizeof(name1)<<endl; cout<<"strlen name1: "<<strlen(name1)<<endl; cout<<"sizeof name2: "<<sizeof(name2)<<endl; cout<<"strlen name2: "<<strlen(name2)<<endl; cout<<"Size name3: "<<name3.size()<<endl; cout<<"length of name3: "<<name3.length()<<endl;

Page 85: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

85

return 0; }

Compile and run

Output:

Very important note:

If you use char*, DO NOT use sizeof to get length of your string. You need to use strlen function to get

the actual length of the string.

If you use char [], the strlen function just returns to you the actual length of the string only. The sizeof

function returns to you the actual length of the string plus null termination ‘\0’. Array has to have a

fixed size define. You have to have ‘\0’ for your char *+. For example, “hello” has 5 character but you

have to have a null termination for it.

#include <iostream> #include <cstring> using namespace std; int main() { char name[] = "hello"; //let compiler figure out the size cout<<"sizeof name: "<<sizeof(name)<<endl;

Page 86: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

86

cout<<"strlen name: "<<strlen(name)<<endl; char buffer1[6]; memcpy(buffer1,name,sizeof(name)); //if use strlen, you need to add 1 for termination character '\0' //memcpy(buffer1,name,strlen(name)+1); cout<<"buffer1: "<<buffer1<<endl; return 0; }

Compile and run

output:

Now, I change buffer to 5, it will compile and run but it will crash when you terminate the program

#include <iostream> #include <cstring> using namespace std; int main() { char name[] = "hello"; //let compiler figure out the size cout<<"sizeof name: "<<sizeof(name)<<endl; cout<<"strlen name: "<<strlen(name)<<endl; char buffer2[5]; memcpy(buffer2,name,sizeof(name)); cout<<"buffer2: "<<buffer2<<endl;

Page 87: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

87

return 0; }

If you run with Visual studio 2012, the error will be like this

Output:

I am highly recommended that you use option three string type. It is very cool and powerful object. You

can convert back forth from string type to char* or char[].

Note: Because last example is failed, make sure you completed stop break debug from previous run

before you run this example.

#include <iostream> #include <cstring> using namespace std; int main() {

Page 88: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

88

//append the string string patrick; patrick ="a happy baby boy"; string myboy = "He is "+ patrick+ " and handsome"; //using "+" for append. So cool, don't have to use strcpy or strcat cout<<myboy<<endl; //string compare excercise string daughter1 = "Sarah Nguyen"; string daughter2 = "Sarah Nguyen"; string daughter3 = "Luna Nguyen"; if (daughter1.compare(daughter2) == 0) { cout<<"Both daughter1 and daughter2 are same name"<<endl; } if (daughter1.compare(daughter3) != 0) { cout<<"Daughter1 and daughter3 are different name"<<endl; } string myname = "Mickey Trong Duc Nguyen"; //let do some searching a substring on the big string if (std::string::npos != myname.find("Duc")) { cout << "Found Duc on my name!" << endl; } //very easy to convert string to array char back and forth. That will help you to use string features then format back //to array char or char* before passes it to next layer which expecting array char data type. //string to char* char* myCharPtr= (char*)myname.c_str(); cout<<"myCharPtr: "<<myCharPtr<<endl; //string to array char char mycharArray[1024]; strcpy(mycharArray, myname.c_str()); cout<<"mycharArray: "<<mycharArray<<endl; //char[] to string char array[ ] = "This is a test of array to string"; string mystring1(array); cout<<mystring1<<endl; //char * to string char *charPtr = "test char* to string"; string mystring2 = charPtr; cout << mystring2 << endl; cout<<"Again, string object is very usefull feature in C++!"<<endl; cout<<"Google it if you need to know about it"<<endl;

Page 89: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

89

return 0; } Compile and run Output:

6.3 Decision making (if..else and switch case) If-else statement and switch case statement are common things to use in programming.

#include <iostream> #include <string> using namespace std; int main() { string today = "Friday"; if (today=="Friday") { cout<<"Chau cooks some good foods"<<endl; } else { cout<<"She is not going to cook. We starve"<<endl; } int number=21; switch (number) { case 10 : cout<<"Just 10"<<endl; break;

Page 90: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

90

case 22 : cout<<"over 21"<<endl; break; case 21 : cout<<"You got blackjack buddy!"<<endl; break; default: break; } return 0; }

Compile and run

Output:

6.4 Loops There are 3 common loops using in C++, for-loop, while-loop,do-while.

6.4.1 Simple example of loops #include <iostream> #include <string> using namespace std; int main() { for (int idx =0; idx <3; idx++) {

Page 91: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

91

cout<<"Hello "<<idx<<endl; } int i =3; while (i > 0) { cout<<"I am in a while loop "<<i<< endl; i--; } int j=0; do { cout<<"Im in do while loop"<<j<<endl; j++; }while (j<3); return 0; }

Compile and run

Output:

6.4.2 Another example of loops #include <iostream> #include <cstring> using namespace std;

Page 92: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

92

//print your name in revert order without recursive call void PrintMyNameInRevert(char myName[]) { for (int i =strlen(myName); i>0; i--) { cout<<myName[i-1]; //this simple function will print your name in revert order } cout<<endl; } //Write recursive function to do the same work as I did in function above. bool done =false; void RecursivePrintMyNameInRevert(char myName[]) { int lenOfMyName = strlen(myName); string myNameStr(myName); //convert array char to string format so we can use it easily. if (done==false) { while(lenOfMyName >= 1) { //start to write from the back of string to all the way to index 0 cout<<myName[lenOfMyName-1]; lenOfMyName--; //tempbuff will deduct one character by 1 each time go through while loop string tempbuff = myNameStr.substr(0,lenOfMyName); //recursive call RecursivePrintMyNameInRevert((char*)tempbuff.c_str()); done=true; return; //done. Don't call recursive anymore } } cout<<endl; } void DoWhileUntilTired () { int i=1; do { cout<<"Enter -1 to get out: "; cin>>i; } while(i>=0); } int main() { char yourname[] = "Mickey Trong Nguyen"; //Without fancy recursive function, for loop excercise PrintMyNameInRevert(yourname); //With fancy recursive function to do the same work. while loop example RecursivePrintMyNameInRevert(yourname); //do while example DoWhileUntilTired();

Page 93: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

93

return 0; } Compile and run Output:

6.5 Pass by value Vs Pass by Reference

You need to know when you should use pass by value or pass by reference to pass your data.

By definition, pass by value means you are making a copy in memory of the actual parameter's value

that is passed in, a copy of the contents of the actual parameter. Use pass by value when you are only

"using" the parameter for some computation, not intend to change value of the parameter.

In pass by reference (also called pass by address), a copy of the address of the actual parameter is

stored. Use pass by reference when you are changing value the parameter that passed to you.

Here are my rules for using the two:

- Using pass by value when you need to pass C++ basic data types in table 1 such as int, double, ….

- Using pass by reference when you need to pass user define data such as struct, class,….

- Using pass by reference when you need to change the value of the parameters that pass in.

#include <iostream> #include <string>

Page 94: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

94

using namespace std; //passing by value int PassByValue(int a, int b) { int result = a + b; return result; } //I use pass by reference to change the value of parameters to other values inside my function. It is useful in situation when you need to change the value of the parameter that pass in to new value after this function finish and return. void PassByReference(int &number, string &name, float &money) //passing by reference { //No matter what I pass into this function, all I want this function to change the values of these parameter that I pass in. cout << "Compare to data you pass in. Their values changed!" << endl; number = 1800; name = "Sarah"; money = 9999.99; } struct sNumbers { //this is simple struct. If this struct have a huge data, and you pass by value instead of address (&) of its //it will make your program run slow int a; double b; //You may add more and more data }; void PassStructData(sNumbers &data) { sNumbers localData; localData = data; cout << "Pass by reference, which mean pass the address storage of parameter." << endl; cout << "a: " << localData.a << endl; cout << "b: " << localData.b << endl; } int main() { int result; result = PassByValue(5, 10); cout << "PassByValue return: " << result << endl; int num = 1000; string name = "Luna"; float money = 10.5; cout << "before, num is: " << num << endl; cout << "before, name is: " << name << endl; cout << "before, money is: " << money << endl; PassByReference(num, name, money); cout << "Now, num is: " << num << endl; cout << "Now, name is: " << name << endl; cout << "Now, money is: " << money << endl;

Page 95: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

95

sNumbers userdata; userdata.a = 10; userdata.b = 9.99; PassStructData(userdata); return 0;

}

Compile and run

Output:

6.6 Pass by Reference Vs Pass by pointer

6.6.1 Example1 of passing reference and passing pointer #include <iostream> using namespace std; struct sBlock { int A; }; class cInfo {

Page 96: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

96

public: void PrintInfo1(sBlock * sBl);//allow you to change the contain of this pointer variable void PrintInfo2(sBlock & sBl);//allow you to change the contain of this reference variable void PrintInfo3(sBlock sBl);//will not allow you to change the contain of this variable }; void cInfo::PrintInfo1(sBlock *Bl) { cout << "PrintInfo1, Before modify" << endl; cout << "Bl->A: " << Bl->A << endl; //modify to 10; Bl->A = 10; } void cInfo::PrintInfo2(sBlock &Bl) { cout << "PrintInfo2, Before modify" << endl; cout << "Bl.A: " << Bl.A << endl; //modify to 20; Bl.A = 20; } void cInfo::PrintInfo3(sBlock Bl) { cout << "PrintInfo3, Before modify" << endl; cout << "Bl.A: " << Bl.A << endl; //modify to 30; Bl.A = 30; } int main() { sBlock bl; bl.A = 5; cInfo info; info.PrintInfo1(&bl);//passing pointer cout << "After modify" << endl; cout << "bl.A: " << bl.A << endl;//New value to 10 because it's been modify to 10 inside function PrintInfo1 cout << endl; info.PrintInfo2(bl);//passing reference cout << "After modify" << endl; cout << "bl.A: " << bl.A << endl;//New value to 20 because it's been modify to 20 inside function PrintInfo2 cout << endl; info.PrintInfo3(bl);//passing value cout << "After modify, should be unchanged" << endl; cout << "bl.A: " << bl.A << endl;//New value to 20 because it's been modify to 20 inside function PrintInfo2 return 0;

Page 97: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

97

} Compile and run

Output:

6.6.2 Example2 of passing reference and passing pointer

#include <iostream> #include <string> using namespace std; int FuncA(int * num) { int result; result= *num; return result; } int FuncB(int & num) { int result; result= num; return result; } int main() { //pass in regular number int mynumber=11; int result; result = FuncA( &mynumber);

Page 98: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

98

cout<<"Result of funcA: "<<result<<endl; result = FuncB(mynumber); cout<<"Result of funcB: "<<result<<endl; //pass in a pointer int *myPtr= NULL; myPtr =&mynumber; result = FuncA(myPtr); cout<<"Result of funcA: "<<result<<endl; result = FuncB(*myPtr); cout<<"Result of funcB: "<<result<<endl; //pass in a reference int & myreference =mynumber; result = FuncA(&myreference); cout<<"Result of funcA: "<<result<<endl; result = FuncB(myreference); cout<<"Result of funcB: "<<result<<endl; return 0; } Compile and run Output:

6.6.3 Example3 of passing reference and passing pointer

- I guess there are a lot of developers are confused the differences between the two. - Pointer can be null, references can't.

Example: int *ptr =NULL; //OK with pointer int &my; //Cannot do for reference

Page 99: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

99

int &my=NULL; //Cannot do for reference

- Pointers can be reassigned, reference cannot.

Example:

#include <iostream> #include <string> using namespace std; int main() { int *ptr =NULL; //OK with pointer int number1 = 11; ptr = &number1; //point to address of number1 cout<<"ptr address: "<<ptr<<endl; int number2 = 22; ptr = &number2; //point to address of number2 cout<<"ptr address: "<<ptr<<endl; int &my= number1; //Address of my is always my. cout<<"my: "<<&my<<endl; //&my=number2; //Cannot do for reference. Still same address my=number2; // Still same address cout<<"my: "<<&my<<endl; return 0; } Compile and run Output:

Page 100: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

100

- Use reference wherever you can, pointers wherever you must. Avoid pointers until you can't. The reason is that pointers makes things harder to follow/read, less safe and far more dangerous manipulations than any other constructs . So the rule of thumbs is to use pointers only if there is no other choice.

6.7 Passing an array #include <iostream> #include <string> #include <fstream> using namespace std; int Sum(int a[10]) { int total=0; for (int i =0; i <10; i++) { total += a[i]; } return total; } int main() { int array[10] ={1,3,5,2,7,6,9,11,4,8}; int total =0; total=Sum(array); cout<<"Sum of array 10 integer is: "<<total<<endl; return 0; } Compile and run Output:

Page 101: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

101

7 Advance C++

7.1 C++ class and object oriented fundamental I take a step back to go slowly about class definition and object oriented concepts. I think we must clear

about fundamental steps before we walk into the advance of C++.

class cMickey { public: //can have either data or method // Who can access to public? Anyone can access to public. see at list at below // Its instance object. // Any of its method (public, private, protected). // Its friend function. // Its friend class. // Its child class who inherit to it (Child's object instance and child's method). int mPublicData; void PublicMethod(); private: //can have either data or method // Who can acces to private? see list at below // Any of its method (public, private, protected). // Its friend function. // Its friend class int mPrivateData; void PrivateMethod(); protected: //can have either data or method // Who can acces to protected? see list at below // Any of its method (public, private, protected). // Its friend function. // Its friend class

Page 102: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

102

// Its child class method int mProtectedData; void ProtectedMethod(); };

7.1.1 Class

The simplest class is an empty class just class name, open, close and semicolon “, -;”

7.1.1.1 Example1 simplest class #include <iostream> using namespace std; class cA { //compiler will give you a default constructor and a default constructor }; int main() { cA a; //a is instance object. It compile fine but this "a" object will not do anything for you because this class has no data or method. } Output:

Nothing

7.1.1.2 Example2 of Simplest Inheritance #include <iostream> #include <string> using namespace std; using namespace std; class cMom { public: void GiveMePho(); void GiveMe100(); }; void cMom::GiveMePho() { cout << "Mom cooks Pho for you!" << endl; } void cMom::GiveMe100() { cout << "Mom gives you $100!" << endl; } class cSon : public cMom {

Page 103: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

103

//child who has nothing but he inherits to Mom }; int main() { cSon me; me.GiveMePho();//child can access to parrent public directly me.GiveMe100();//child can access to parrent public directly return 0; }

Compile and run

Output:

7.1.1.3 Example3 of simplest inheritance #include <iostream> #include <string> using namespace std; class cMom { public: cMom(string, float); ~cMom(); void CookThis(string);//child access directly void GiveThis(float);//child access directly private: string food; //only Mom method can access. Mom's privacy float money;//only Mom method can access. Mom's privacy protected: string GetFood();//child access via its method float GetMoney();//child access via its method };

Page 104: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

104

cMom::cMom(string f, float m) :food(f), money(m)//user constructor,initialize its data members { } cMom::~cMom() { } void cMom::CookThis(string f) { food = f; } void cMom::GiveThis(float m) { money = m; } string cMom::GetFood() { return food; } float cMom::GetMoney() { return money; } class cSon : public cMom { public: cSon(); ~cSon(); void MyFood(); //access Mom protected section void MyMoney();//access Mom protected section }; cSon::cSon() :cMom ("Rice", 10.0) //Set default, mom cooked rice and give $10 { } cSon::~cSon() { } void cSon::MyFood() { cout << GetFood() << endl;//access Mom protected section via son method } void cSon::MyMoney() { cout << GetMoney() << endl;//access Mom protected section via son method } int main() { cSon me; cout << "By default,mom gives those" << endl; me.MyFood(); me.MyMoney(); cout << "jucky, I want these!" << endl; me.CookThis("Pho noodle");//child can access to parrent public directly me.GiveThis(1000.00);//child can access to parrent public directly me.MyFood(); me.MyMoney();

Page 105: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

105

return 0; }

Compile and run

Output:

7.1.1.4 Example4 of object instance and all type of methods access to public section

In this example I am showing its instance object and its other methods within this class. The next

example, I will show friend function and friend class, then the next example I will show child class access

to public.

// Who can access to public? Anyone can access to public. see at list at below // Its instance object. // Any of its method (public, private, protected). // Its friend function. // Its friend class. // Its child class who inherit to it (Child's object instance and child's method).

#include <iostream> using namespace std; class cA { //by default it is private access if you don't specify public,private, or protected public: void Print1(); void Print2(); void Print2_1();

Page 106: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

106

void Print2_2(); private: void Print3(); protected: void Print4(); }; void cA::Print1() { cout << "I am a Print1" << endl; } void cA::Print2() { cout << "I am a Print2" << endl; Print1(); //its public method Print2 access to its public } void cA::Print2_1() { cout << "I am a Print2_1" << endl; Print3(); //its public method Print2_1 access to private } void cA::Print2_2() { cout << "I am a Print2_2" << endl; Print4(); //its public method Print2_2 access to protected } void cA::Print3() { cout << "I am a Print3" << endl; Print1();//its private method Print3 access to its public } void cA::Print4() { cout << "I am a Print4" << endl; Print1(); //Its protected method Print4 access to its public } int main() { cA a; //a is instance object. a.Print1(); // its instance access to public section cout << endl; a.Print2(); // its instance access to public section cout << endl; a.Print2_1(); // its instance access to public section cout << endl; a.Print2_2(); // its instance access to public section //a.Print3(); //No, compiler will give you an error, object instance cannot have direct access to private section. //a.Print4(); //No, compiler will give you an error, object instance cannot have direct access to protected //That why I have to create the public Print2_1 and Print2_2 to access those private and protected. return 0; }

Page 107: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

107

Compile and run

Output:

7.1.1.5 Example5 of friend function and friend class access to public section

In this example, I am showing friend function and friend class access to public section

// Who can access to public? Anyone can access to public. see at list at below // Its instance object. // Any of its method (public, private, protected). // Its friend function. // Its friend class. // Its child class who inherit to it (Child's object instance and child's method).

#include <iostream> using namespace std; class cA { //by default it is private access if you don't specify public,private, or protected public: void Print1(); friend void FriendOfCA(cA); //friend function friend class cB; //friend class }; void cA::Print1() { cout << "I am a Print1" << endl; } //since friend function is not a class member so you don't use class scope ::

Page 108: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

108

void FriendOfCA(cA a) { a.Print1();//Access to public of my friend cA } class cB { public: void Print2(); }; void cB::Print2() { cA a; // create friend object instance so cB can use cA information. In this case, I am going to access to cA public a.Print1(); } int main() { cA a; //a is instance object. a.Print1(); // its instance access to public section FriendOfCA(a);// Friend function cB b; //object instance b.Print2(); return 0; }

Compile and run

Output:

Page 109: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

109

7.1.1.6 Example6 of child’s instance and child’s method access to parent public section

In this example I am trying to show child’s object instance and child’s method can access to parent

public Child’s object instance cannot directly access to parent’s private and protected. Child’s method

can access to parent protected section.

// Who can access to public? Anyone can access to public. see at list at below // Its instance object. // Any of its method (public, private, protected). // Its friend function. // Its friend class. // Its child class who inherit to it (Child's object instance and child's method).

#include <iostream> using namespace std; class cA { //by default it is private access if you don't specify public,private, or protected public: void Print1(); }; void cA::Print1() { cout<<"I am a Print1"<<endl; } class cB : public cA { public: void Print2(); }; void cB::Print2() { Print1(); //access to parrent public } int main() { cB b; //object instance b.Print1();//Direct access to parent public b.Print2();//its method access to parent public return 0; }

Compile and run

Output:

Page 110: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

110

7.1.1.7 Example7 of wihin class all type of methods access to private section

In this example, I am showing within class, its method no mater it is public/private/protected, it can

access to private section

// Who can acces to private? see list at below // Any of its method (public, private, protected). // Its friend function. // Its friend class

#include <iostream> using namespace std; class cA { //by default it is private access if you don't specify public,private, or protected public: void Print1(); void Print2(); void Print2_1(); private: void Print3(); void Print3_1(); protected: void Print4(); }; void cA::Print1() { cout << "I am a Print1" << endl; Print3();//its public method Print1 access to private }

Page 111: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

111

void cA::Print2() { cout << "I am a Print2" << endl; Print3_1(); //its public method Print2 access to its private } void cA::Print2_1() { cout << "I am a Print2_1" << endl; Print4(); //its public method Print2_1 access to protected } void cA::Print3() { cout << "I am a Print3" << endl; } void cA::Print3_1() { cout << "I am a Print3_1" << endl; Print3();//its private method Print3_1 access to private } void cA::Print4() { cout << "I am a Print4" << endl; Print3(); //Its protected method Print4 access to its private } int main() { cA a; //a is instance object. a.Print1(); // its instance access to public section cout << endl; a.Print2(); // its instance access to public section cout << endl; a.Print2_1(); // its instance access to public section //Reminder, object instance CANNOT access to private or protected directly. return 0; }

Compile and run

Output:

Page 112: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

112

7.1.1.8 Example8 of friend function and friend class access to Private section

In this example I want to show friend and friend class access to private section

// Who can acces to private? see list at below // Any of its method (public, private, protected). // Its friend function. // Its friend class

#include <iostream> using namespace std; class cA { public: friend void FriendOfCA(cA); //friend function friend class cB; //friend class private: void Print1(); }; void cA::Print1() { cout << "I am a Print1" << endl; } void FriendOfCA(cA a) { a.Print1();//Access to private of my friend cA }

Page 113: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

113

class cB { public: void Print2(); }; void cB::Print2() { cA a; // create friend object instance so cB can use cA information. In this case, I am going to access to cA protected a.Print1(); } int main() { cA a; //a is instance object. FriendOfCA(a);// Friend function cB b; //object instance b.Print2(); return 0; }

Compile and run

Output:

7.1.1.9 Example9 of within class, its methods access to protected section

In this example, I am showing within class, its method no mater it is public/private/protected, it can

access to protected section. Also, child class can access to parent’s protected section.

Page 114: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

114

// Who can acces to protected? see list at below // Any of its method (public, private, protected). // Its friend function. // Its friend class // Its child class method #include <iostream> using namespace std; class cA { //by default it is private access if you don't specify public,private, or protected public: void Print1(); void Print2(); void Print2_1(); private: void Print3(); protected: void Print4(); void Print4_1(); }; void cA::Print1() { cout << "I am a Print1" << endl; Print4();//its public method Print1 access to protected } void cA::Print2() { cout << "I am a Print2" << endl; Print3(); //its public method Print2 access to its private } void cA::Print2_1() { cout << "I am a Print2_1" << endl; Print4_1(); //its public method Print2_1 access to protected } void cA::Print3() { cout << "I am a Print3" << endl; Print4();//its private method Print3 access to its protected } void cA::Print4() { cout << "I am a Print4" << endl; } void cA::Print4_1() { cout << "I am a Print4_1" << endl; Print4(); //Its protected method Print4_1 access to its protected } class cB :public cA { public: void PrintcB(); };

Page 115: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

115

void cB::PrintcB() { Print4();//access parent protected } int main() { cA a; //a is instance object. a.Print1(); // its instance access to public section cout << endl; a.Print2(); // its instance access to public section cout << endl; a.Print2_1(); // its instance access to public section cout << endl; cB b; b.PrintcB(); return 0; } Compile and run

Output:

7.1.1.10 Example10 of friend function and friend class access to protected section

In this example, I am showing friend function and friend class access to protected section.

// Who can acces to protected? see list at below // Any of its method (public, private, protected). // Its friend function. // Its friend class // Its child class method

Page 116: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

116

#include <iostream> using namespace std; class cA { public: friend void FriendOfCA(cA); //friend function friend class cB; //friend class protected: void Print1(); }; void cA::Print1() { cout << "I am a Print1" << endl; } void FriendOfCA(cA a) { a.Print1();//Access to protected of my friend cA } class cB { public: void Print2(); }; void cB::Print2() { cA a; // create friend object instance so cB can use cA information. In this case, I am going to access to cA protected a.Print1(); } int main() { cA a; //a is instance object. FriendOfCA(a);// Friend function cB b; //object instance b.Print2(); return 0; }

Compile and run

Output:

Page 117: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

117

7.1.1.11 Example11 child class access to parent protected

In this example, I am showing child class access to parent protected via its method

#include <iostream> using namespace std; class cA { //by default it is private access if you don't specify public,private, or protected protected: void Print1(); }; void cA::Print1() { cout<<"I am a Print1"<<endl; } class cB : public cA { public: void Print2(); }; void cB::Print2() { Print1(); //access to parrent protected } int main() { cB b; //object instance b.Print2();

Page 118: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

118

} Compile and run

Output:

7.1.1.12 Example12 about inheritance virtual function

Child class override parent’s virtual method.

#include <iostream> #include <string> using namespace std; class cBAE { public: virtual void WorkOrder(); void Planning(); }; //base class, big boss void cBAE::WorkOrder() { cout << "cBAE parent WorkOrder" << endl; } void cBAE::Planning() { cout << "cBAE planning, pursuit new contract" << endl; } //child class, sw team class cF16SoftwareTeam : public cBAE { public: void WorkOrder(); //will override parent virtual function

Page 119: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

119

void SoftwareTasks(); }; void cF16SoftwareTeam::WorkOrder() { cout << "SW WorkOrder" << endl; } void cF16SoftwareTeam::SoftwareTasks() { cout << "SW SoftwareTask" << endl; } //child class, HR team class cHRTeam : public cBAE { public: void WorkOrder();//will override parent virtual function void PayrollTasks(); }; void cHRTeam::WorkOrder() { cout << "HR WorkOrder" << endl; } void cHRTeam::PayrollTasks() { cout << "HR PayrollTasks" << endl; } int main() { //In this example, I have 3 teams //cBAE is a parent //SW and HR team as child of cBAE //3 team can perform their tasks independently //virtual WorkOrder from parent cBAE can override by child //cBAE is parent can work on its own cBAE bae; bae.WorkOrder(); bae.Planning(); cout << endl; //cF16SoftwareTeam is child of cBAE, it can work on its own team cF16SoftwareTeam sw; sw.WorkOrder(); //Will not override its parent virtual method unless get instruct from cBAE sw.SoftwareTasks(); sw.Planning(); //can access to parent's public directly cout << endl; //cHRTeam is child of cBAE,it can work on its own team cHRTeam hr; hr.WorkOrder();//Will not override its parent virtual method unless get instruct from cBAE hr.PayrollTasks(); hr.Planning(); //can access to parent's public directly cout << endl; cout << "Big boss tell child work order" << endl;

Page 120: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

120

//Now cBAE is a parent and it want to tell each of its child to work as its instruction cBAE *ptr = NULL; ptr = &sw;//to tell sw team work on SW WorkOrder ptr->WorkOrder(); //you will see even though ptr is cBAE but WorkOrder override by sw team. ptr->Planning(); cout << endl; //cBAE now to tell HR team work on HR order. I tell you cBAE is a parent, he is a big boss. ptr = &hr; ptr->WorkOrder(); //you will see even though ptr is cBAE but WorkOrder override by HR team. ptr->Planning(); return 0; } Compile and run

Output:

7.1.1.13 Example13 about inheritance without virtual function

In this example, if I remove virtual function, child class CANNOT override parent’s method who has same

name and parameters (same signature).

#include <iostream> #include <string>

Page 121: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

121

using namespace std; class cBAE { public: void WorkOrder(); //remove virtual void Planning(); }; //base class, big boss void cBAE::WorkOrder() { cout << "cBAE parent WorkOrder" << endl; } void cBAE::Planning() { cout << "cBAE planning, pursuit new contract" << endl; } //child class, sw team class cF16SoftwareTeam : public cBAE { public: void WorkOrder();//cannot override parent same function name because parent did not declare virtual void SoftwareTasks(); }; void cF16SoftwareTeam::WorkOrder() { cout << "SW WorkOrder" << endl; } void cF16SoftwareTeam::SoftwareTasks() { cout << "SW SoftwareTask" << endl; } //child class, HR team class cHRTeam : public cBAE { public: void WorkOrder();//cannot override parent same function name because parent did not declare virtual void PayrollTasks(); }; void cHRTeam::WorkOrder() { cout << "HR WorkOrder" << endl; } void cHRTeam::PayrollTasks() { cout << "HR PayrollTasks" << endl; } int main() { //In this example, I have 3 teams //cBAE is a parent //SW and HR team as child of cBAE //3 team can perform their tasks independently //virtual WorkOrder from parent cBAE can override by child

Page 122: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

122

//cBAE is parent can work on its own cBAE bae; bae.WorkOrder(); bae.Planning(); cout << endl; //cF16SoftwareTeam is child of cBAE, it can work on its own team cF16SoftwareTeam sw; sw.WorkOrder(); //Will not override its parent virtual method unless get instruct from cBAE sw.SoftwareTasks(); sw.Planning(); //can access to parent's public directly cout << endl; //cHRTeam is child of cBAE,it can work on its own team cHRTeam hr; hr.WorkOrder();//Will not override its parent virtual method unless get instruct from cBAE hr.PayrollTasks(); hr.Planning(); //can access to parent's public directly cout << endl; cout << "Big boss tell child work order" << endl; //Now cBAE is a parent and it want to tell each of its child to work as its instruction cBAE *ptr = NULL; ptr = &sw;//to tell sw team work on SW WorkOrder ptr->WorkOrder(); //you will see even though ptr is cBAE but WorkOrder override by sw team. ptr->Planning(); cout << endl; //cBAE now to tell HR team work on HR order. I tell you cBAE is a parent, he is a big boss. ptr = &hr; ptr->WorkOrder(); //you will see even though ptr is cBAE but WorkOrder override by HR team. ptr->Planning(); return 0; } Compile and run

Output:

Page 123: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

123

7.1.1.14 Example14 about inheritance abstract base class

In this example, I am showing abstract base class (pure virtual). Abstract class is a class who has at least

one virtual function and ASSIGN =0. Cannot create object instance for an abstract class.

#include <iostream> #include <string> using namespace std; class cBAE { public: virtual void WorkOrder()=0 ; //pure virtual, now cBAE is an abstract class void Planning(); }; //base class, big boss void cBAE::WorkOrder() { cout << "cBAE parent WorkOrder" << endl; } void cBAE::Planning() { cout << "cBAE planning, pursuit new contract" << endl; } //child class, sw team class cF16SoftwareTeam : public cBAE { public: void WorkOrder();//will override parent pure virtual function void SoftwareTasks(); };

Page 124: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

124

void cF16SoftwareTeam::WorkOrder() { cout << "SW WorkOrder" << endl; } void cF16SoftwareTeam::SoftwareTasks() { cout << "SW SoftwareTask" << endl; } //child class, HR team class cHRTeam : public cBAE { public: void WorkOrder();//will override parent pure virtual function void PayrollTasks(); }; void cHRTeam::WorkOrder() { cout << "HR WorkOrder" << endl; } void cHRTeam::PayrollTasks() { cout << "HR PayrollTasks" << endl; } int main() { //In this example, I have 3 teams //cBAE is a parent //SW and HR team as child of cBAE //3 team can perform their tasks independently //virtual WorkOrder from parent cBAE can override by child //cBAE is abstract class, no long can create object instance for it. compiler error //cBAE bae; //bae.WorkOrder(); //bae.Planning(); cout << endl; //cF16SoftwareTeam is child of cBAE, it can work on its own team cF16SoftwareTeam sw; sw.WorkOrder(); //Will not override its parent virtual method unless get instruct from cBAE sw.SoftwareTasks(); sw.Planning(); //can access to parent's public directly cout << endl; //cHRTeam is child of cBAE,it can work on its own team cHRTeam hr; hr.WorkOrder();//Will not override its parent virtual method unless get instruct from cBAE hr.PayrollTasks(); hr.Planning(); //can access to parent's public directly cout << endl; cout << "Big boss tell child work order" << endl; //Now cBAE is a parent and it want to tell each of its child to work as its instruction

Page 125: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

125

cBAE *ptr = NULL; ptr = &sw;//to tell sw team work on SW WorkOrder ptr->WorkOrder(); //you will see even though ptr is cBAE but WorkOrder override by sw team. ptr->Planning(); cout << endl; //cBAE now to tell HR team work on HR order. I tell you cBAE is a parent, he is a big boss. ptr = &hr; ptr->WorkOrder(); //you will see even though ptr is cBAE but WorkOrder override by HR team. ptr->Planning(); return 0; }

Compile and run

Output:

7.2 Review about class and inheritance again C++ language is a most powerful language in my own opinion; nowadays, there are a lot of built-in features such as Stand Template Library (STL) vector, list, map, queue, and so on. I will have a section about STL in this tutorial. C++ is object oriented, it is easy to maintain and add on or reuse old features. Before I give you real examples, I need you to understand about “public”, “private”, ”protected” access.

Page 126: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

126

Example:

class cA { public: cA(); ~cA(); int mPublicdata; void PublicMethod(); private: int mPrivateData; void PrivateMethod(); protected: void ProtectedMethod(); int mProtecteddata; }; class cB : public cA { public: cB(); ~cB(); int mPublicdata; void PublicMethod(); private: int mPrivateData; void PrivateMethod(); };

7.2.1 Public

Any member function and data member declared in a public section of a class can be accessed by anyone.

7.2.2 Private

Any member function or data member declared in a private section of a class can only be accessed by

“member functions” and friends of that class.

Both Java and C++ have capability to encapsulate data (hiding data from out side world accessing to it).

How? Yes, in private section. You only allow method of “same” class to access your data. The out side

world (other classes) cannot have access to the private section of the other class. That how you can

hindden your data or your detail of implementation.

7.2.3 Protected

It is very much like private but it also allow child class access to it. Any member function or data

member declared in protected section of a class can only be access by member functions and friend of

that class, and also by any member functions and friends of derived classes.

In my conclusion:

When you define a class, you should know exactly what you should have in your public, private, or

protected section. Note: forget about friends of class at this moment, I will talk to it in next section.

Page 127: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

127

- In public section, you should define data members and member functions that you allow

anybody has a right to access to them, which mean any section of that class itself can use its

public section and also any derived class can use its parent public section directly.

- In private section, you should define data members and member functions that you intend for

those methods of this same class, friend function, and friend class use these private data

members and private methods. If I want to have certain methods or data that for my other

methods “internally of the same class” to use only, then I will put those methods or data in

private section of my class. If you want a derived class to use base class methods data member

then you need to define them in public or protected section. Again, I want you have a good

understanding about private section. The “instance” of a class cannot call its private member

functions; only methods among of same class can call its private methods. So, when you define

your functions or data in private section which mean you don’t want anybody able to access to

them, only your other function among “your class” can call/use them.

- In protected section, it is just like private section plus you also allow the child class’s member

functions call/use its parent protected section.

What does inheritance meaning and the benefits of it? When you want to reuse of old/legacy C++ code,

you are going to inheritance the old class. Some C++ programmers confuse about inheritance,

polymorphism, and abstract class. We will go one by one by example.

What is base class and does it has to have virtual function or pure virtual function on its member

function? The answer is base class can be normal like any class. It does not require having virtual

functions or pure virtual functions in its member function. In the next sections I will cover when we

should have virtual function and pure virtual function.

So, when a child class who is trying to use the old features/methods of the parent class, all it needs to do

is inherit to the parent.

7.2.4 Example of inheritance without virtual function

The following example, I define a parent class just as normal class without any virtual or pure virtual

function, I just add a protected section in purpose. I want any method of child class accesses to its

parent class protected section. Reminder, instance of child class can have direct access to its parent

public section. Instance of child class cannot direct access to its parent protected section but its

methods can call any method that defined in its parent public and protected section.

#include <iostream> #include <string> using namespace std; class cDoD { public: cDoD();

Page 128: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

128

~cDoD(); void Acronym(); void SetNumberOfCompanies(int companies); private: int mNumCompanies; protected: int DoDCompanies(); }; class cBAE : public cDoD { public: cBAE(); ~cBAE(); //BAE instance able to access directly to public and also access to its parent protected via its method. int GetTotalDoDCompanies(); }; cDoD::cDoD() { } cDoD::~cDoD() { } void cDoD::Acronym() { cout << "Department of Defense" << endl; } void cDoD::SetNumberOfCompanies(int companies) { mNumCompanies = companies; } int cDoD::DoDCompanies() { return mNumCompanies; } cBAE::cBAE() { } cBAE::~cBAE() { } int cBAE::GetTotalDoDCompanies() { return DoDCompanies(); //Access its parent protected } int main() { cBAE bae; bae.Acronym(); //Direct access to its parent public bae.SetNumberOfCompanies(75); //Direct access to its parent public cout << "Total of DoD companies: " << bae.GetTotalDoDCompanies() << endl; return 0; }

Compile and run

Page 129: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

129

Output:

7.2.5 Example of inheritance with virtual function

So, why should you have virtual function in parent class? The reason for that is if you want a child class

to override the implementation of some methods in parent class then those method have virtual

keyword in front of it. I will show you same example with/without virtual keyword, and show you the

behavior of the two.

7.2.5.1 Example of inheritance without virtual function

It could not override by child class because method Acronym() is not virtual. See the result of the run.

#include <iostream> #include <string> using namespace std; class cDoD { public: void Acronym(); }; class cBAE : public cDoD { public: //using default constructor and destructor void Acronym();

Page 130: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

130

}; void cDoD::Acronym() { cout << "Department of Defense" << endl; } void cBAE::Acronym() { cout << "British Aerospace Engineering" << endl; } int main() { cBAE bae; cDoD *ptrDoD = new cDoD(); ptrDoD = &bae; ptrDoD->Acronym(); return 0; }

Compile and run

Output:

7.2.5.2 Example of inheritance with virtual function

Child class can override the implementation of parent class if parent’s method declare as virtual.

#include <iostream>

Page 131: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

131

#include <string> using namespace std; class cDoD { public: virtual void Acronym(); }; class cBAE : public cDoD { public: //using default constructor and destructor void Acronym(); }; void cDoD::Acronym() { cout << "Department of Defense" << endl; } void cBAE::Acronym() { cout << "British Aerospace Engineering" << endl; } int main() { cBAE bae; cDoD *ptrDoD = new cDoD(); ptrDoD = &bae; ptrDoD->Acronym(); return 0; } Compile and run Output:

Page 132: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

132

In conclusion, if you want child class overrides the methods of parent class then add a virtual keyword in

front of those methods in parent class.

7.2.6 Abstract class (pure virtual)

What is pure virtual? Pure virtual is method start with virtual keyword and it has =0 at the end.

What is abstract class? If a class has at least on pure virtual function, it is an abstract class. The abstract

class will not provide the implementation of pure virtual method. You cannot create the object instance

of abstract class. Any function defined in parent class as pure virtual, the child class has to have the

implementation for it. Child class cannot skip any pure virtual functions in its implementation.

7.2.6.1 Example1 of abstract class

In the following example, I define an abstract class which has “Hoppies” method declare as pure virtual.

I also have two other methods “Name” and “Foods”. Just at least one method defines as pure virtual

the class will become abstract class. You will not provide any implementation of your pure virtual

function. Your derived class will provide the implementation for pure virtual function of your abstract

class.

#include <iostream> #include <string> using namespace std; class cGarnet { public: cGarnet(); //constructor ~cGarnet();//destructor

Page 133: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

133

void Name();//Not override virtual void Foods();//can be overridden virtual void Hoppies() = 0; //pure virtual. Now Garnet class is abstract class. No implementation for pure virtual function }; cGarnet::cGarnet() { } cGarnet::~cGarnet() { } void cGarnet::Name() { cout << "Garnet Name called!" << endl; } void cGarnet::Foods() { cout << "Garnet foods called!" << endl; } class cSarah : public cGarnet { public: cSarah(); ~cSarah(); void Name(); //Garnet did not declare virtual, cannot override Garnet ‚Name‛ function void Foods(); //Will override Garnet virtual function void Hoppies(); //Sarah has to have to implement this method to override pure virtual method defined in Garnet class. Otherwise, it will not compile the code. }; cSarah::cSarah() : cGarnet() { } cSarah::~cSarah() { } void cSarah::Name() { cout << "Sarah Name called!" << endl; } void cSarah::Foods() { cout << "Sarah Foods called!" << endl; } void cSarah::Hoppies() { cout << "Sarah hoppies are Drawing and swimming" << endl; } int main() { cSarah sa; cGarnet *basePtr = &sa; basePtr->Name();

Page 134: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

134

basePtr->Foods(); basePtr->Hoppies(); return 0; }

Compile and run

Output:

7.2.6.2 Example2 of abstract class

In the following example, I define an abstract class with all pure virtual methods without provide any

implementation. In my own opinion, I like the way design abstract class like this, it is very clean.

#include <iostream> #include <string> using namespace std; class cVehicle { public: virtual void Type() = 0; virtual string EngineSize() = 0; virtual unsigned Doors() = 0; virtual double Weight() = 0;

Page 135: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

135

}; class cSUV : public cVehicle { public: cSUV(); ~cSUV(); void Type(); string EngineSize(); unsigned Doors(); double Weight(); private: string mEnginesize; unsigned mDoors; double mWeight; }; cSUV::cSUV() :cVehicle(), mEnginesize("V6"), mDoors(4), mWeight(3500.00) { } cSUV::~cSUV() { } void cSUV::Type() { cout << "I am SUV" << endl; } string cSUV::EngineSize() { return mEnginesize; } unsigned cSUV::Doors() { return mDoors; } double cSUV::Weight() { return mWeight; } int main() { cSUV suv; cVehicle * car = &suv; car->Type(); cout << "Engine size: " << car->EngineSize() << endl; cout << "Doors: " << car->Doors() << endl; cout << "Weight: " << car->Weight() << endl; return 0; }

Compile and run

Output:

Page 136: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

136

7.2.6.3 Overloading constructor

Constructor can be overloaded as function. When you create a new object, you can use an accordingly

constructor that support your need. See my example.

7.2.6.3.1 Example1 of overloading constructor #include <iostream> #include <string> using namespace std; class cCar { public: cCar(); //empty constructor cCar(string engsize, unsigned short doors); //engine size and doors only cCar(string engsize, unsigned short doors, double weight); //engine size, doors, and weight void PrintInfo(); private: string mEngineSize; unsigned short mDoors; double mWeight; }; cCar::cCar() { } cCar::cCar(string engsize, unsigned short doors) { mEngineSize = engsize;

Page 137: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

137

this->mDoors = doors;//if data member and parameter have same name you have to use this pointer to tell which is which. } cCar::cCar(string engsize, unsigned short doors, double weight) { mEngineSize = engsize; this->mDoors = doors;//if data member and parameter have same name you have to use this pointer to tell which is which. this->mWeight = weight;//if data member and parameter have same name you have to use this pointer to tell which is which. } void cCar::PrintInfo() { cout << "Engine size: " << mEngineSize << endl; cout << "Doors: " << mDoors << endl; cout << "Weight: " << mWeight << endl; } int main() { cCar *obj1 = new cCar(); //use first constructer. Empty constructor cout << "Should print out garbage because use empty constructor" << endl; obj1->PrintInfo(); cCar * obj2 = new cCar("V6", 4); cout << "Should print engine size and doors" << endl; obj2->PrintInfo(); cCar *obj3 = new cCar("V8", 4, 4000.00); cout << "Should print engine size, doors, and weight" << endl; obj3->PrintInfo(); delete obj1; delete obj2; delete obj3; return 0; }

Compile and run

Output:

Page 138: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

138

7.2.6.3.2 Example 2 of overloading constructor #include <iostream> #include <string> using namespace std; class cVehicle { public: virtual void Type() = 0; virtual string EngineSize() = 0; virtual unsigned Doors() = 0; virtual double Weight() = 0; }; class cSedan : public cVehicle { public: cSedan(); cSedan(string s, unsigned d, double w); cSedan(unsigned d, double w); ~cSedan(); void Type(); string EngineSize(); unsigned Doors(); double Weight(); private: string mEnginesize; unsigned mDoors; double mWeight; }; cSedan::cSedan() :cVehicle(),

Page 139: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

139

mEnginesize("V6"), mDoors(4), mWeight(3500.00) { } cSedan::cSedan(string s, unsigned d, double w) : cVehicle(), mEnginesize(s), mDoors(d), mWeight(w) { } cSedan::cSedan(unsigned d, double w) : cVehicle(), mDoors(d), mWeight(w) { } cSedan::~cSedan() { } void cSedan::Type() { cout << "I am a Sedan car" << endl; } string cSedan::EngineSize() { return mEnginesize; } unsigned cSedan::Doors() { return mDoors; } double cSedan::Weight() { return mWeight; } int main() { cSedan sedan1; //First constructor cVehicle * car = &sedan1; car->Type(); cout << "Used first constructor to create object" << endl; cout << "Engine size: " << car->EngineSize() << endl; cout << "Doors: " << car->Doors() << endl; cout << "Weight: " << car->Weight() << endl; cout << endl; cSedan sedan2("V8", 6, 5000); car = &sedan2; //now point car base class to sedan2 car->Type(); cout << "Used second constructor to create object" << endl; cout << "Engine size: " << car->EngineSize() << endl; cout << "Doors: " << car->Doors() << endl; cout << "Weight: " << car->Weight() << endl;

Page 140: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

140

cout << endl; cSedan sedan3(4, 5000); car = &sedan3; //now point car base class to sedan3 car->Type(); cout << "Used third constructor to create object" << endl; cout << "Engine size: Unknow because this overloading constructor did not provide it" << car->EngineSize() << endl; cout << "Doors: " << car->Doors() << endl; cout << "Weight: " << car->Weight() << endl; return 0; }

Compile and run

Output:

7.2.6.4 Virtual Destructor

In the C++, both constructor and destructor if you don’t define them compiler will provide them to you.

But if your class has a virtual function, you have to define a virtual destructor by yourself. If you don’t do

it, the compiler gives you a normal destructor (not a virtual destructor). Your program did not clean up

correctly.

7.2.6.4.1 Example of not using virtual destructor

This example is showing that child destructor will not be called.

#include <iostream> #include <string>

Page 141: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

141

using namespace std; class cBase { public: ~cBase(); //if you don't define, compiler will give it to you. virtual void Print() = 0; }; cBase::~cBase() { cout << "Base constructor called" << endl; } class cChild : public cBase { public: cChild(); ~cChild(); void Print(); }; cChild::cChild() :cBase() { } cChild::~cChild() { cout << "Child Destructor called" << endl; } void cChild::Print() { cout << "Printing something" << endl; } int main() { cBase *b = new cChild(); b->Print(); delete b; return 0; }

Compile and run

Output:

Page 142: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

142

7.2.6.4.2 Example of using virtual destructor

This example showing that child destructor will be called.

#include <iostream> #include <string> using namespace std; class cBase { public: virtual ~cBase(); //if you don't define, compiler will give it to you. virtual void Print() = 0; }; cBase::~cBase() { cout << "Base constructor called" << endl; } class cChild : public cBase { public: cChild(); ~cChild(); void Print(); }; cChild::cChild() :cBase() { } cChild::~cChild() { cout << "Child Destructor called" << endl; } void cChild::Print()

Page 143: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

143

{ cout << "Printing something" << endl; } int main() { cBase *b = new cChild(); b->Print(); delete b; return 0; } Compile and run Output:

7.2.6.5 There is no virtual constructor in C++

Compiler should give you error if you try to do that.

7.2.7 Friend function

Friend function is not a member function of a class but it has a right to access to public, private, and

protected section of class that it is friend to.

#include <iostream> #include <string> using namespace std;

Page 144: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

144

class cMom { public: friend void Patrick(cMom); //friend function void Money(); private: void House(); protected: void Car(); }; void cMom::Money() { cout << "Mom have 1 million" << endl; } void cMom::House() { cout << "Mom's address 3423 Pueblo" << endl; } void cMom::Car() { cout << "Mom has a Lexus" << endl; } //since friend function is not a class member so you don't use class scope :: void Patrick(cMom miley) { miley.Car(); miley.House(); miley.Money(); } int main() { cMom ma; Patrick(ma); return 0; }

Compile and run

Output:

Page 145: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

145

7.3 File stream

7.3.1 Example of open file for writing #include <iostream> #include <string> #include <fstream> using namespace std; int main() { ofstream file ("testlogfile.log"); //open output file if (file.is_open()) { file << "This is a first line."; file << endl; file << "This is 2nd line"; file << endl; file.close(); } else { cout << "Unable to open file for writting"; } cout<<"Open testlogfile in same directory of this file"<<endl; return 0; }

Page 146: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

146

Compile and run

Output

7.3.2 Example of open file for reading #include <iostream> #include <string> #include <fstream> using namespace std; int main() { string buffer; ifstream file ("testlogfile.log");//open input file if (file.is_open()) { while (file.good()) { getline (file,buffer); cout << buffer << endl; } file.close(); } else { cout << "Unable to open file for reading"; } return 0; }

Page 147: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

147

Compile and run

Output:

7.3.3 Friend class

Friend of a class cans access to public, private, and protected section of a class that declares it as a

friend. It is only one direction access. For example, class A declares Class B as its friend which means

class A allows class B access to A. Class A cannot access to class B. If I say you are my friend I mean I

allow you to use my house, money, and car. I cannot use your money, house, and car because you did

not say I am your friend.

#include <iostream> #include <string> using namespace std; class cMom { friend class cSarah; //friend class public: void Money(); private: void House(); protected: void Car(); }; void cMom::Money()

Page 148: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

148

{ cout << "Mom have 1 million" << endl; } void cMom::House() { cout << "Mom's address 3423 Pueblo" << endl; } void cMom::Car() { cout << "Mom has a Lexus" << endl; } class cSarah { public: void GetEverythingFromMom(); }; void cSarah::GetEverythingFromMom() { cMom miley; //access to public, private, protected miley.Car(); miley.House(); miley.Money(); } int main() { cSarah sa; sa.GetEverythingFromMom(); return 0; }

Compile and run

Output:

Page 149: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

149

In my conclusion, friend function and friend class are useful but I don’t recommended using them. It is a

lazy way of design (add yourself/your-object as a friend of some classes then use their features). When

you want to use any legacy software please do it in appropriate way such as inheriting to it or include

legacy object in your member data.

7.3.4 Example of using legacy object

At this point you should know how to use inheritance already. This example I am trying to show you to

add legacy object to your new class then use it features.

#include <iostream> #include <string> using namespace std; class cMom { public: void Money(); void House(); void Car(); }; void cMom::Money() { cout << "Mom have 1 million" << endl;

Page 150: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

150

} void cMom::House() { cout << "Mom's address 3423 Pueblo" << endl; } void cMom::Car() { cout << "Mom has a Lexus" << endl; } class cSarah { public: cSarah(); ~cSarah(); void GetEverythingFromMom(); private: cMom * kim; //Try to use Mom features, add Mom pointer in data member }; cSarah::cSarah() { kim = new cMom(); } cSarah::~cSarah() { delete kim; } void cSarah::GetEverythingFromMom() { kim->Car(); kim->House(); kim->Money(); } int main() { cSarah sa; sa.GetEverythingFromMom(); return 0; }

Compile and run

Output:

Page 151: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

151

7.3.5 This pointer

Every object has its “this” pointer. “This” pointer accesses to non-static member functions of class,

struct, or union type. This pointer is useful when return object pointer/reference. It makes code look

cleaner.

#include <iostream> #include <string> using namespace std; class cKimKardashian { public: cKimKardashian(); ~cKimKardashian(); void Donate(double amount); cKimKardashian * DonateMore(double amount); cKimKardashian & DonateMoreAndMore(double amount); void Print(); private: double mMoney; }; cKimKardashian::cKimKardashian() : mMoney(0) { } cKimKardashian::~cKimKardashian() { } void cKimKardashian::Donate(double mMoney) {

Page 152: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

152

this->mMoney += mMoney; //if data member and parameter have same name, you have to use this to tell which "money" is which } cKimKardashian * cKimKardashian::DonateMore(double money) { this->mMoney += money;//add new money to current money. This pointer is useful for return object pointer return this; } cKimKardashian & cKimKardashian::DonateMoreAndMore(double money) { this->mMoney += money;//add new money to current money. This pointer is useful for return object reference return *this; } void cKimKardashian::Print() { cout << "KimKardashian current donate $" << this->mMoney << endl; //don’t have to use this pointer in this situation but it is ok to use it. } int main() { cKimKardashian kim; kim.Donate(100000.00); kim.Print(); kim.DonateMore(100000.00); kim.Print(); kim.DonateMoreAndMore(100000.00); kim.Print(); return 0; }

Compile and run

Output:

Page 153: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

153

7.3.6 Overloading functions Vs Function Template

Overloading functions, function has same name but the parameters are different.

Function template is useful when we pass try to pass generic data type. It cut down number of

overloading functions. Function template is a better choice in my own opinion.

7.3.6.1 Example of overloading functions. #include <iostream> #include <string> using namespace std; class cPrintSomething { public: cPrintSomething(); ~cPrintSomething(); void Print(); void Print(int a); void Print(double a); }; cPrintSomething::cPrintSomething() {

Page 154: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

154

} cPrintSomething::~cPrintSomething() { } void cPrintSomething::Print() { cout << "Print out something" << endl; } void cPrintSomething::Print(int a) { cout << "Print out int: " << a << endl; } void cPrintSomething::Print(double b) { cout << "Print out double: " << b << endl; } int main() { cPrintSomething p; p.Print(); p.Print(5); p.Print(10.99); return 0; }

Compile and run

Output:

Page 155: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

155

7.3.6.2 Example of Template Function

#include <iostream> #include <string> using namespace std; template <class T> class cPrintSomething { public: cPrintSomething(); ~cPrintSomething(); void Print(); void Print(T a); }; template <class T> cPrintSomething<T>::cPrintSomething() { } template <class T> cPrintSomething<T>::~cPrintSomething() { } template <class T> void cPrintSomething<T>::Print() { cout << "Print out something" << endl; } template <class T> void cPrintSomething<T>::Print(T a) { cout << "Print out num: " << a << endl; } int main() { cPrintSomething<string> p; p.Print(); cPrintSomething<int> p2; p2.Print(5); cPrintSomething<double> p3; p3.Print(10.99); return 0; }

Compile and run

Output:

Page 156: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

156

7.3.6.3 Another example of Template Class/Typename

I would like to give you another example of template class/typename. The last example is kind of

messy.

#include <iostream> #include <string> using namespace std; template <class T> void Print(T a) { cout << "Print will print out according type T: " << a << endl; } template <typename T2> //typename works samething as class void Print2(T2 a) { cout << "Print will print out according type T2: " << a << endl; } int main() { Print("Mickey Nguyen"); //T is string Print(5); //T is int Print(10.99); //T is double cout << endl; Print2("Sarah Nguyen"); //T2 is string Print2(6); //T2 is int Print2(11.99); //T2 is double

Page 157: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

157

return 0; }

Compile and run

Output:

7.4 Multiple inheritance It is good to use multiple inheritances. If you create a new class which derives to two base classes, so

your child class can access to both parents in public and protected sections. In some case if these two

base classes have same public data members name or same member functions name, it will give you

problem. To resolve that issue, you need to add a unique namespace outside of each parent class.

7.4.1 Example1 of multiple inheritance #include <iostream> #include <string> using namespace std; class cWife { public: void ProvideMoney(); void ProvideLove(); }; void cWife::ProvideMoney() { cout << "Wife provides Money" << endl; }

Page 158: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

158

void cWife::ProvideLove() { cout << "Wife provides love" << endl; } class cSisterInLaw { public: void ProvideFoods(); }; void cSisterInLaw::ProvideFoods() { cout << "SisInlaw,Come to eat my foods" << endl; } class cMickey : public cWife, public cSisterInLaw { }; int main() { cMickey me; me.ProvideMoney(); //call Wife class me.ProvideLove(); //call Wife class me.ProvideFoods();//call SisterInlaw class return 0; }

Compile and run

Output:

Page 159: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

159

7.4.2 Example2 of multiple inheritance

In this example, both parents class have same member function name. Need to add a unique

namespace to each parent class to resolve the issue.

#include <iostream> #include <string> using namespace std; namespace CHAU { class cWife { public: void ProvideMoney(); void ProvideLove(); }; } void CHAU::cWife::ProvideMoney() { cout << "Wife provides Money" << endl; } void CHAU::cWife::ProvideLove() { cout << "Wife provides love" << endl; } namespace MILEY { class SisterInLaw { public: void provideFoods(); void provideMoney(); //Without separate namespace it will collide with the one in cWife class }; } void MILEY::SisterInLaw::provideFoods() { cout << "Come to eat my foods" << endl; } void MILEY::SisterInLaw::provideMoney() { cout << "With namespace Mickey will able to use provideMoney methods from both parents" << endl; } class cMickey : public CHAU::cWife, public MILEY::SisterInLaw { }; int main() { cMickey me; me.CHAU::cWife::ProvideMoney(); me.CHAU::cWife::ProvideLove(); me.MILEY::SisterInLaw::provideFoods();

Page 160: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

160

me.MILEY::SisterInLaw::provideMoney(); return 0; }

Compile and run

Output:

7.5 Bit fields Usually students did not much chance to exercise bit fields in school. It is nice to understand well this

area; it will help you out when you deal with bits and bytes in real world.

7.5.1 Example1, print out year 2013 in binary

It is very simple, all you need to do is masking the year with this mask 0x8000, this mask in binary is 1000 0000 0000 0000 Ok, do you know binary and hex yet? 0000 binary in hex is 0; 1000 binary in hex is 8 that why your mask is 0x8000 Year 2013, we don’t need to know how the binary look like; however we know there is a set of combination of number of 1s and number 0s is 2013, so I say xxxx xxxx xxxx xxxx (some x is 1, some x is 0) xxxx xxxx xxxx xxxx

Page 161: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

161

& 1000 0000 0000 0000 _______________________ Next time will be like this, then so on until the end xxxx xxxx xxxx xxxx & 0100 0000 0000 0000 _______________________ Until the end like this xxxx xxxx xxxx xxxx & 0000 0000 0000 0001 _______________________ Start from left to right, each time shift mask to right by 1, perform the &, if x is 1 then the result is 1 and print it out, if x is 0 the result will be 0 and print it out.

#include <iostream> #include <string> #include <fstream> using namespace std; void PrintYear2013InBinary(unsigned short year) //2 bytes, and positive number only { unsigned short mask = 0x8000; //1000 0000 0000 0000 cout<<year<<" in binary value: "; for (int i =0; i < 16; i++) { //I want to go through this for loop and perform the and with my mask then shift to the right bye one. //1000 0000 0000 0000 //0100 0000 0000 0000 //0010 0000 0000 0000 //...so on until //0000 0000 0000 0001 if ((year&mask)) //if 1 cout<<"1"; else cout<<"0"; mask = mask >> 1; //go to the right by one until 0000 0000 0000 0001 } cout<<endl; } int main() { PrintYear2013InBinary(2013); return 0; }

Page 162: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

162

Compile and run

Output:

7.5.2 Xor operation

Just an example of c = a xor b. Xor operation is useful to turn certain bit 0 to 1 or 1 to 0.

#include <iostream> #include <string> #include <fstream> using namespace std; void PrintOutInBinary(unsigned short year) //2 bytes, and positive number only { unsigned short mask = 0x8000; //1000 0000 0000 0000 cout<<endl; cout<<year<<" in binary value: "; for (int i =0; i < 16; i++) { //I want to go through this for loop and perform the and with my mask then shift to the right bye one. //1000 0000 0000 0000 //0100 0000 0000 0000 //0010 0000 0000 0000 //...so on until //0000 0000 0000 0001 if ((year&mask)) //if 1 cout<<"1";

Page 163: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

163

else cout<<"0"; mask = mask >> 1; //go to the right by one until 0000 0000 0000 0001 } cout<<endl; } void XorOperation () { //This whole exercise is using big endian or network byte order. If your processor use small endian you need to do byte swap. //Reminder: 1 byte is 8 bits. Max value of 1 byte in decimal is 255; in binary 1111 1111; in hex 0xFF, so in hex each character is 4 bits. unsigned short a; unsigned short b; //I assign some values to a and b as below. a=0xABCD; //1010 1011 1100 1101 b=0xEFAB; //1110 1111 1010 1011 unsigned short c= a^b; //xor operation printf ("\na xor b operation, decimal: %u, hex: 0x%04X (2 bytes format)",c,c); //04X that mean 4 characters (2 bytes.). printf ("\na xor b operation, decimal: %u, hex: 0x%08X (4 bytes format)",c,c); //08X that mean 8 characters (4 bytes). PrintOutInBinary(c); } int main() { XorOperation(); return 0; }

Compile and run

Output:

Page 164: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

164

7.5.2.1 Example of xor operation again (turn on/off bit)

Turn off bit #8 and turn on bit #13

#include <iostream> #include <string> #include <fstream> using namespace std; void PrintOutInBinary(unsigned short year) //2 bytes, and positive number only { unsigned short mask = 0x8000; //1000 0000 0000 0000 cout<<endl; cout<<year<<" in binary value: "; for (int i =0; i < 16; i++) { //I want to go through this for loop and perform the and with my mask then shift to the right bye one. //1000 0000 0000 0000 //0100 0000 0000 0000 //0010 0000 0000 0000 //...so on until //0000 0000 0000 0001 if ((year&mask)) //if 1 cout<<"1"; else cout<<"0";

Page 165: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

165

mask = mask >> 1; //go to the right by one until 0000 0000 0000 0001 } cout<<endl; } void XorOperation () { //This whole exercise is using big endian or network byte order. If your processor use small endian you need to do byte swap. //Reminder: 1 byte is 8 bits. Max value of 1 byte in decimal is 255; in binary 1111 1111; in hex 0xFF, so in hex each character is 4 bits. unsigned short a; //I assign some values to a as below. a=0xABCD; //1010 1011 1100 1101 unsigned short c; //the xor operator is very important in embedded programming. Use to turn on/off bit. //I want you to turn the bit #8 to 0 and bit #13 to 1 (on mean 1, off mean 0) //IF a=0xABCD, or in binary like this 1010 1011 1100 1101, //I want you turn on and off these bits 1 1 keep all other bits same. //The resultof this operation is: 1011 1011 0100 1101. What we need to do to get this result. //Defined the mask in hex of this binary 0001 0000 1000 0000 unsigned short mymask = 0x1080; //0001 0000 1000 0000 c= a^mymask; //xor operation cout<<"Turn off bit #8 and turn on bit #13"; PrintOutInBinary(c); } int main() { XorOperation(); return 0; }

Compile and run

Output:

Page 166: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

166

7.5.2.2 Example of reading out data in certain bits of bytes

#include <iostream> #include <cstring> #include <fstream> using namespace std; void PrintOutInBinary(unsigned short year) //2 bytes, and positive number only { unsigned short mask = 0x8000; //1000 0000 0000 0000 cout << endl; cout << year << " in binary value: "; for (int i = 0; i < 16; i++) { //I want to go through this for loop and perform the and with my mask then shift to the right bye one. //1000 0000 0000 0000 //0100 0000 0000 0000 //0010 0000 0000 0000 //...so on until //0000 0000 0000 0001 if ((year&mask)) //if 1 cout << "1"; else cout << "0"; mask = mask >> 1; //go to the right by one until 0000 0000 0000 0001 } cout << endl;

Page 167: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

167

} void ReadDataFromBytes() { //I'm assumed you know all other operator such as & and | //OK, more exercise to learn about bit mask fields. //If you receive a package which has 10 bytes of header and 1000 bytes of payload data. //Here is 10 bytes of header, and I want you to read out of some specific bits. //[1010 0011] [1011 0001] .... [0110 0101] [1100 1001] //This is sample of byte order. [9] [8] [7] [6] [5] [4] [3] [2] [1] [0] //On the first 2 bytes (byte #0 and #1 on the right) I may have 5 pieces information in there. //[0110 0101] [1100 1001] //byte #1 on the left, byte #0 on the right //In byte #0 (1100 1001), I may have data like this //first 3 bits: data1 //001; decimal is 1 //next two bits: data2 //01; decimal is 1 //last 3 bits: data3 //110; decimal is 6 //So in byte #0 1100 1001 I have data in this order [data3][data2][data1] or [110][01][001] //My byte #1 (0110 0101) I may have data like this //first 5 bits: data4 //00101; decimal is 5 //last 3 bits: data5 //011; decimal is 3 //So in byte#1 0110 0101 I have data in this order [data5][data4] or [011][00101] //See, by eyes you can see data1 to data5 that in byte#1 and byte#0. Now how to code to read them out correctly //for now just care about these two byte, so I just define code for these two byte only. unsigned char Mybytes[2]; memset(Mybytes, 0, sizeof(Mybytes)); Mybytes[0] = 0xC9; //1100 1001 Mybytes[1] = 0x65; //0110 0101 printf("Mybytes[0]: 0x%02X \n", Mybytes[0]); printf("Mybytes[1]: 0x%02X \n", Mybytes[1]); //data1 to data5 they may have their own data type such as int, char, ... you may need to cast/convert them to correct data type //This example I treat them are all positive number. unsigned short data1, data2, data3, data4, data5; //data1, first three bits of byte#0. 1100 1[001] data1 = Mybytes[0] & 0x07; //defined you mask if you are nice. your mask =0x07; //0000 0111 cout << "data1: " << data1 << endl; //data2, next 2 bits of byte#0 110[0 1]001 data2 = (Mybytes[0] >> 3) & 0x03; //your mask =0x03; //0000 0011

Page 168: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

168

//Why you need to shift to the right by 3? Because I want to read out only that two bits. //Orginal byte #0 is 1100 1001. I want the value of these two bits 110[0 1]001 //Two bits that I interesting to before I shift to the right by 3 (110[0 1]001), after I shift,it looks like this (000110[01]). //Basically, move/shift these bits to the rights, padding # of 0 to the left. If move to the right 3 bits, padding on the left 3 zeros. //Three original bits on the rights will override by these bits from the left when it moves to its position. //Now, you have to & with the mask 0x03 to get actual value. when you & with 0000 0011, you just get out the value of two bits. cout << "data2: " << data2 << endl; //data3 last 3 bits of byte#0 [110]0 1001 data3 = (Mybytes[0] >> 5) & 0x07; //I hope you can see why I shift to the right by 5 and &0x07. //Anyway, shift to right by 5, 00000110. then & with 0000 0111 to get the actual value. cout << "data3: " << data3 << endl; //I hope you are pro by now. //data4, the first 5 bits of byte#1 011[0 0101] data4 = Mybytes[1] & 0x1F; //mask 0001 1111 cout << "data4: " << data4 << endl; //data5 next 3 bits of byte#1 [011]0 0101 data5 = (Mybytes[1] >> 5) & 0x07; //mask 0000 0111 cout << "data5: " << data5 << endl; //You can see after I am done so many times of shifting the value of byte#0 and byte#1 still the same. I just move/manipulate those bits to get //in the right position for me to calculate the right value for my need. //If you do some thing like this Mybytes[0]= Mybytes[0]>>3; The value of Mybytes[0] will be changed. printf("Mybytes[0]: 0x%02X \n", Mybytes[0]); printf("Mybytes[1]: 0x%02X \n", Mybytes[1]); //It seems easy if the data in each byte boundary. How about the data in a few bits of this byte and a few bits of other bytes. //0110 0101 1100 1001 still two bytes from last excercise. //Now, I want to read out 6 bits like this from these two bytes. 0110 01[01 1100] 1001. //The value of this 6 bits [01 1100] should be 28 in decimal. //Let's do it. //Unsigned short is two bytes. unsigned short combineTwobytes; combineTwobytes = Mybytes[0] + (Mybytes[1] << 8); //[Mybytes1][Mybytes0] //or //memcpy(&combineTwobytes,Mybytes,sizeof(Mybytes)); //copy two bytes Mybytes to address of combineTwobytes printf("combineTwobytes: 0x%04X \n", combineTwobytes); //now defined your mask to read out that specific 6 bits. unsigned short mask = 0x003F;//Why? 0000 0000 0011 1111 unsigned short sixbitsValue = (combineTwobytes >> 4) & mask; //0000 0110 01[01 1100] & 0000 0000 0011 1111 cout << "sixbitsValue: " << sixbitsValue << endl;

Page 169: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

169

//I hope you are clearly to understand at this point. If you do, you can deal with bits or bytes without any problem. //Those exercise above, to help you to deal with raw data that you receive in your layer, and you need to read out of turn on/off certain bits. } int main() { ReadDataFromBytes(); return 0; }

Compile and run

Output:

7.5.2.3 Example of packing data into 2 bytes without shifting and masking

If you are the one to pack and unpack data, you can code the following way. It is much cleaner without

shifting and masking.

#include <iostream> #include <cstring> #include <fstream> using namespace std; void PrintOutInBinary(unsigned short year) //2 bytes, and positive number only {

Page 170: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

170

unsigned short mask = 0x8000; //1000 0000 0000 0000 cout<<endl; cout<<year<<" in binary value: "; for (int i =0; i < 16; i++) { //I want to go through this for loop and perform the and with my mask then shift to the right bye one. //1000 0000 0000 0000 //0100 0000 0000 0000 //0010 0000 0000 0000 //...so on until //0000 0000 0000 0001 if ((year&mask)) //if 1 cout<<"1"; else cout<<"0"; mask = mask >> 1; //go to the right by one until 0000 0000 0000 0001 } cout<<endl; } void PackingDataIntoBytes () { struct sTwobytesHeader { unsigned short one : 5; //use 5 bits of only unsigned short two : 6; //use six bits unsigned short three : 2; //use two bits unsigned short four : 3; //use 3 bits }; sTwobytesHeader twobytes; printf("sizeof twobytes %d \n",sizeof(twobytes)); //set data without a lot of shifting and masking twobytes.one = 13; twobytes.two = 45; twobytes.three =3; twobytes.four =5; //read it back without a lot of shifting and masking unsigned short readback1 =twobytes.one; unsigned short readback2 =twobytes.two; unsigned short readback3 =twobytes.three; unsigned short readback4 =twobytes.four; cout<<"readback1: "<<readback1<<endl; cout<<"readback2: "<<readback2<<endl; cout<<"readback3: "<<readback3<<endl; cout<<"readback4: "<<readback4<<endl; printf("twobytes in hex 0x%02X \n",twobytes); unsigned short value; memcpy(&value,&twobytes,sizeof(twobytes)); printf("twobytes in dec %d \n",value); PrintOutInBinary(value); } int main() {

Page 171: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

171

PackingDataIntoBytes(); return 0; } Compile and run Output:

7.5.2.4 Example of pack 10 bytes of header into char array #include <iostream> #include <cstring> #include <fstream> using namespace std; void PrintOutInBinary(unsigned short year) //2 bytes, and positive number only { unsigned short mask = 0x8000; //1000 0000 0000 0000 cout<<endl; cout<<year<<" in binary value: "; for (int i =0; i < 16; i++) { //I want to go through this for loop and perform the and with my mask then shift to the right bye one. //1000 0000 0000 0000 //0100 0000 0000 0000 //0010 0000 0000 0000 //...so on until //0000 0000 0000 0001 if ((year&mask)) //if 1 cout<<"1"; else cout<<"0";

Page 172: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

172

mask = mask >> 1; //go to the right by one until 0000 0000 0000 0001 } cout<<endl; } void PackingDataInto10Bytes () { //If you are the one to pack the header, instead of coding a lot of bit field shifting and masking nasty like you did earlier, you can code it very much //cleaner as the this exercise. So you are able to pack/unpack data very easy. //How about build a 10 bytes header. Example, the syntax "unsigned short v3:3; " which mean you use 3 bits even though you declare unsigned short which is two bytes. struct mickeyHeader { unsigned short v1:16; //2 bytes 2 bytes byte# 0,1 unsigned short v2:16; //2 bytes 2 bytes byte# 2,3 unsigned char len:4; //4 bits unsigned char ver:4; //4 bits 1 byte byte# 4 unsigned short v3:3; //3 bits unsigned char v4:5; //5 bits 1 byte byte# 5 unsigned char v5:8; //1 byte 1 byte byte# 6 unsigned char v6:2; //2 bits unsigned char v7:3; //3 bits unsigned char v8:3; //2 bits 1 byte byte#7 unsigned short v9:16; //2 bytes 2 bytes byte# 8,9 }; mickeyHeader myMickeyHeader; printf("sizeof myMickeyHeader: %d\n", sizeof(myMickeyHeader)); //Populate data to it myMickeyHeader.v1 = 100; myMickeyHeader.v2 = 200; myMickeyHeader.len = 9; myMickeyHeader.ver = 6; myMickeyHeader.v3 = 2; myMickeyHeader.v4 = 3; myMickeyHeader.v5 = 10; myMickeyHeader.v6 = 2; myMickeyHeader.v7 = 1; myMickeyHeader.v8 = 4;// this is max number for v8 because you declare to you only 3 bits 111. Same as v7, max value you can populate is 7. myMickeyHeader.v9 = 254; //That is your 10 bytes of data, you can send this truct to next layer. When next layer receive it, it can read it out like struct access.

Page 173: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

173

printf("len = %d\n",myMickeyHeader.len); printf("ver = %d\n",myMickeyHeader.ver); printf("v1= %d\n",myMickeyHeader.v1); printf("v2= %d\n",myMickeyHeader.v2); printf("v3= %d\n",myMickeyHeader.v3); printf("v4= %d\n",myMickeyHeader.v4); printf("v5= %d\n",myMickeyHeader.v5); printf("v6= %d\n",myMickeyHeader.v6); printf("v7= %d\n",myMickeyHeader.v7); printf("v8= %d\n",myMickeyHeader.v8); printf("v9= %d\n",myMickeyHeader.v9); //If you have to put your struct into char[10], here what you need to do unsigned char buffer1[10]; memset(buffer1,0,sizeof (buffer1));//clear 10 bytes to 0 struct mickeyHeader *mptr = new mickeyHeader; mptr->v1=100; mptr->v2=200; mptr->len =9; mptr->ver =6; mptr->v3=2; mptr->v4=3; mptr->v5=10; mptr->v6=2; mptr->v7=1; mptr->v8=4; mptr->v9=254; memcpy(buffer1,reinterpret_cast <unsigned char*> (&myMickeyHeader),sizeof(buffer1)); printf("mptr->len = %d\n",mptr->len); printf("mptr->ver = %d\n",mptr->ver); printf("mptr->v1= %d\n",mptr->v1); printf("mptr->v2= %d\n",mptr->v2); printf("mptr->v3= %d\n",mptr->v3); printf("mptr->v4= %d\n",mptr->v4); printf("mptr->v5= %d\n",mptr->v5); printf("mptr->v6= %d\n",mptr->v6); printf("mptr->v7= %d\n",mptr->v7); printf("mptr->v8= %d\n",mptr->v8); printf("mptr->v9= %d\n",mptr->v9); for (int i=0; i<10;i++) { printf("buffer1[%d] = %02x\n",i, buffer1[i]); } //2nd way of copy a struct header into char array cout<<"2nd way of copy astruct header into char array"<<endl;

Page 174: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

174

unsigned char buffer2[10]; memset(buffer2,0,sizeof (buffer2));//clear 10 bytes to 0 //unpack data, cast object to unsigned char * unsigned char* bufferPtr = static_cast<unsigned char*>(static_cast<void*>(&myMickeyHeader)); memcpy(buffer2,bufferPtr,sizeof(buffer2)); for (int j=0; j<10;j++) { printf("buffer2[%d] = %02x\n",j, buffer2[j]); } } int main() { PackingDataInto10Bytes(); return 0; }

Compile and run

Output:

Page 175: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

175

7.6 Error handling, try throw catch, assert In a large project, you need to handle errors well otherwise when it crashes, you don’t have much clue

what happen.

#include <iostream> #include <string> #include <fstream> using namespace std; void TryThrowCatch() { //Try throw catch char *buf; try { buf = new char[512]; if( buf == 0 ) throw "Memory allocation failure!"; } catch( char * str ) { cout << endl<< "Exception raised: " << str << '\n'; } try { //code. //Whatever happend, I am going to throw it anyway, so you can see throw and catch work throw 20; } catch (int e) { cout<<endl<<"An exception occurred. Number "<<e<<endl; } //int asserttest = 10; //assert (asserttest > 10); } int main() { TryThrowCatch(); return 0; }

Compile and run

Output:

Page 176: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

176

7.7 Namespace Namespace is a cool feature in C++. Most of the time people use namespace for each software layer.

So, when you look at the method get called, you know where that method from which layer. Another

useful purpose of namespace to make data/method is not colliding to each other when they are same

name. Follow my example.

7.7.1 Example1 of using namespace #include <iostream> #include <string> #include <fstream> using namespace std; namespace Patrick { int number = 5; } namespace Sarah { double number = 9.99; } int main() { cout << "Patrick::number: " << Patrick::number << endl; cout << "Sarah::number: " << Sarah::number << endl;

Page 177: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

177

return 0; } Compile and run Output:

7.7.2 Example2 of using namespace

#include <iostream> #include <string> #include <fstream> using namespace std; namespace Ngoc { class cMiley { public: void BankAccount() { cout << "Miley has 2 Millions for Mickey" << endl; } }; } namespace Dat { class cMrJohn { public: void BankAccount() { cout << "MrJohn has 1 thousand for Mickey" << endl; } }; } class cMickey : public Dat::cMrJohn, public Ngoc::cMiley {

Page 178: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

178

}; int main() { cMickey me; //me.BankAccount(); //Without namespace compiler don't know which one to call (ambiguous). Of course Miley is much richer me.Ngoc::cMiley::BankAccount(); return 0; }

Compile and run

Output:

7.8 Singleton object Singleton is a design pattern. It is very useful when you want exactly only object is running in your

system.

#include <iostream> #include <string> #include <fstream> using namespace std; //Singleton class class cMickeySingleton {

Page 179: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

179

public: static cMickeySingleton * GetInstance(); void PrintMyName(); private: cMickeySingleton(); // Private so that it can not be called static cMickeySingleton* instance; cMickeySingleton(const cMickeySingleton &);// Prevent copy-construction cMickeySingleton & operator = (const cMickeySingleton &);// Prevent assignment }; cMickeySingleton * cMickeySingleton::instance = NULL;// initialize static pointer. Have to initialize static data member in global scope. If you have .h and .cpp separate. Initial static data member at begin of .cpp file cMickeySingleton* cMickeySingleton::GetInstance() { if (instance == 0) // is it the first call? { instance = new cMickeySingleton(); // create sole instance } return instance; } cMickeySingleton::cMickeySingleton() { cout << "Mickey constructor, Howdy!\n"; } void cMickeySingleton::PrintMyName() { cout << "My name is Mickey" << endl; } int main() { cout << "You should see your constructor has been called only one time." << endl; cMickeySingleton *mickeysingleton1 = cMickeySingleton::GetInstance(); cMickeySingleton *mickeysingleton2 = cMickeySingleton::GetInstance(); mickeysingleton1->PrintMyName(); mickeysingleton2->PrintMyName(); //or cMickeySingleton::GetInstance()->PrintMyName(); return 0; }

Compile and run

Output:

Page 180: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

180

7.9 Example of implementing Jovial compool in C++

7.9.1 Using static function to implement Jovial compool

Static functions can only access static data member variables. Static data member can be shared among

object instance.

//usually define these in .h file #include <iostream> using namespace std; struct TableW3 //3 WORDS = 6 bytes. { //1 byte unsigned short a : 5; //use 5 bits unsigned short b : 2; //use 2 bits unsigned short c : 1; //use 1 bit char d; //use 8 bits (1 byte) int e; //use all 4 bytes (2 WORDS) }; class cJovialCompool // this class data memory can be shared with all objects instance because I use static function. { public: static void SetNum(int); static int GetNum(); static void SetTb(TableW3); static TableW3 GetTb(); private:

Page 181: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

181

static int m_Num; static TableW3 m_Tb; }; ///////////////////////end of header. //usually .cpp for implementation //static data member have to be set globally at begin of .cpp file before can use it. If you missed this step compiler will give you an error. int cJovialCompool::m_Num = 0; TableW3 cJovialCompool::m_Tb; //implement part, usually in .cpp void cJovialCompool::SetNum(int num) { m_Num = num; } int cJovialCompool::GetNum() { return m_Num; } void cJovialCompool::SetTb(TableW3 tb) { m_Tb = tb; } TableW3 cJovialCompool::GetTb() { return m_Tb; } ////////////////end of .cpp implementation //usually in .cpp for main (driver). int main() { cJovialCompool s; //create instance s to set values s.SetNum(5); TableW3 tb; tb.a = 2; tb.b = 3; tb.c = 1; tb.d = 'a'; tb.e = 99; s.SetTb(tb); cJovialCompool g; //Create instance g to get values cout<<"m_Num: "<<g.GetNum()<<endl; TableW3 value = g.GetTb(); cout << "Tb, a:" << value.a << endl; cout << "Tb, b:" << value.b << endl; cout << "Tb, c:" << value.c << endl; cout << "Tb, d:" << value.d << endl; cout << "Tb, e:" << value.e << endl;

Page 182: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

182

//As you just see g object instance get the same information that s object instance set. }

Compile and run

Output:

7.9.2 Using singleton object to implement Jovial compool //usually define these in .h file #include <iostream> using namespace std; struct TableW3 //3 WORDS = 6 bytes. If you perform sizeof (TableW3) you should see 8 bytes instead of 6 byte. Why? Because it is byte alignment for 64 bits system, it will pading for you another two bytes all 0s in there. { //1 byte unsigned short a : 5; //use 5 bits unsigned short b : 2; //use 2 bits unsigned short c : 1; //use 1 bit char d; //use 8 bits (1 byte) int e; //use all 4 bytes (2 WORDS) }; class cJovialCompool // this class data memory can be shared with all objects instance because I use static function. {

Page 183: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

183

public: static cJovialCompool * GetInstance();//for singleton object void SetNum(int); int GetNum(); void SetTb(TableW3); TableW3 GetTb(); private: cJovialCompool(); // Private so that it can not be called static cJovialCompool* instance; //singleton object instance cJovialCompool(const cJovialCompool &);// Prevent copy-construction cJovialCompool & operator = (const cJovialCompool &);// Prevent assignment int m_Num; //data want to shared TableW3 m_Tb;//data want to shared }; ///////////////////////end of header. //usually .cpp for implementation //static data member have to be set globally at begin of .cpp file before can use it. If you missed this step compiler will give you an error. cJovialCompool * cJovialCompool::instance = NULL; cJovialCompool* cJovialCompool::GetInstance()//singleton object { if (instance == 0) // is it the first call? { instance = new cJovialCompool(); // create sole instance } return instance; } cJovialCompool::cJovialCompool() { cout << "Mickey cJovialCompool constructor, Howdy!\n"; } //implement part, usually in .cpp void cJovialCompool::SetNum(int num) { m_Num = num; } int cJovialCompool::GetNum() { return m_Num; } void cJovialCompool::SetTb(TableW3 tb) { m_Tb = tb; } TableW3 cJovialCompool::GetTb() { return m_Tb;

Page 184: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

184

} ////////////////end of .cpp implementation //usually in .cpp for main (driver). int main() { cJovialCompool *s =cJovialCompool::GetInstance(); //create s ptr of singletonobject instance s->SetNum(5); TableW3 tb; tb.a = 2; tb.b = 3; tb.c = 1; tb.d = 'a'; tb.e = 99; s->SetTb(tb); cJovialCompool *g = cJovialCompool::GetInstance();//create g ptr of singletonobject instance cout<<"m_Num: "<<g->GetNum()<<endl; TableW3 value = g->GetTb(); cout << "Tb, a:" << value.a << endl; cout << "Tb, b:" << value.b << endl; cout << "Tb, c:" << value.c << endl; cout << "Tb, d:" << value.d << endl; cout << "Tb, e:" << value.e << endl; //As you just see g object instance get the same information that s object instance set. }

Compile and run

Output:

Page 185: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

185

7.10 Copy constructor Vs Assignment operator We need to know in which situation we should copy constructor instead of Assignment or the other way

around.

When you create a brand new object and initialize it to the values from other existing object, you need

copy constructor. If you don’t implement copy constructor, compiler will give you one but some cases

you need to implement one for yourself because you need a “deep” copy instead of “shallow” copy.

When you want to copy the values from one object to another “existing” object, you need an

assignment operator. If you don’t implement assignment operator, compiler will give you one but

some cases you need to implement one for yourself because you need a “deep” copy instead of

“shallow” copy.

So, if you don’t need “deep” copy your data, you don’t have to implement copy constructor or

assignment operator. Whenever your class have pointer data member, you need to implement copy

constructor and assignment operator by yourself. Be safe you can provide the implementation of copy

constructor and assignment operator. It is not hard to implement them.

7.10.1 Example1 of copy constructor and assignment operator

In this example, class did not have pointer; therefore, if you don’t implement both copy constructor and

assignment operator, compiler will provide them to you. If you take out the implementation of copy

constructor and assignment operator your program will run and exit fine.

#include <iostream> #include <string>

Page 186: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

186

#include <fstream> using namespace std; class cSum { public: cSum(int, int); ~cSum(); //copy constructor cSum(const cSum &source); //Assignment Operator cSum& operator= (const cSum &Source); int Add(); private: int a; int b; }; cSum::cSum(int first, int second) : a(first), b(second) { } cSum::~cSum() { } int cSum::Add() { int result = a + b; return result; } //Copy construtor cSum::cSum(const cSum &sourceInfo) { cout << "Called copy constructor!" << endl; a = sourceInfo.a; b = sourceInfo.b; } //Assignment operator cSum & cSum::operator= (const cSum &sourceInfo) { cout << "Called Assignment!" << endl; if (this == &sourceInfo) return *this; a = sourceInfo.a; b = sourceInfo.b; return *this;// return the existing object } int main() { cSum firstObj(5, 10); cout << "Sum1: " << firstObj.Add() << endl; //create second instance based on existing object.

Page 187: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

187

cSum secondObj(firstObj); //Second object is new and it takes information of first object. It uses copy constructor cout << "Sum2: " << secondObj.Add() << endl; cSum thirdObj = secondObj; ////Third object is new and it takes information of 2nd object. It uses copy constructor cout << "Sum3: " << thirdObj.Add() << endl; //assignment test cSum fourObj(10, 10); cout << "Sum4: " << fourObj.Add() << endl; //After use assignment operator fourObj = thirdObj;//Four object existing and it take values from third object. It uses assignment operator cout << "Sum4: " << fourObj.Add() << endl; return 0; } Compile and run

Ouput:

7.11 Prevent other people to copy/use your internal objects. If you declare copy construct and assignment in your class but you don’t provide the implementation of

these, nobody can accidentally to do copy constructor or assignment operation.

#include <iostream> #include <string>

Page 188: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

188

#include <fstream> using namespace std; class cMyInternalObject //don't want anybody to use my internal object { public: cMyInternalObject(); ~cMyInternalObject(); //my other methods void Print(); private: //To prevent other people to copy/assign my own internal object. cMyInternalObject(const cMyInternalObject &); cMyInternalObject & operator= (const cMyInternalObject &); }; cMyInternalObject::cMyInternalObject() { } cMyInternalObject::~cMyInternalObject() { } void cMyInternalObject::Print() { cout << "No one can copy/assignment my object to them." << endl; } int main() { cMyInternalObject me; me.Print(); return 0; }

Compile and run

Output:

Page 189: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

189

7.12 Casting Casting is helping you to convert data type from one to another. If you can avoid using casting, please

don’t do any casting. It is very dangerous you are not clear which cast is a correct one to support your

need.

7.12.1 const_cast

Use const_cast to be set or to be removed the constant.

#include <iostream> #include <string> using namespace std; void Print1(const char* name) { cout<<"Print1 has a const argument"<<endl; cout<<name<<endl; } void Print2(char* name) { cout<<"Print2 has a non-const argument"<<endl; cout<<name<<endl; } int main() { char* myName = "Mickey Nguyen"; Print1(const_cast<char*>(myName));//Use const_cast to set it to constant Print2(myName); const char* myWife ="Chau Tran"; Print1(myWife);

Page 190: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

190

Print2(const_cast<char*>(myWife));//Use const_cast to remove the constant return 0; }

Compile and run

Output:

7.12.2 static_cast

It is useful for casting base class pointer to derived class pointer. It is not safe because base class is not

always have what derive class has. But when casting derived class pointer to base class pointer it is safe

because derived class always what base class has. It is also very convenient to convert simple data type

such as int to char, float to double.

#include <iostream> #include <string> using namespace std; class cBase { }; class cDerived : public cBase { }; int main() {

Page 191: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

191

double num; float f = 9.5; num = static_cast<double>(f); // float to double cout << "num: " << num << endl; cBase *b = new cBase(); cDerived *d = new cDerived(); cDerived * d2 = static_cast<cDerived *>(b); // Not safe, Derived can have fields // and methods that are not in Base. cBase * b2 = static_cast<cBase *>(d); // Safe conversion, Derived always // contains all of Base. delete b; delete d; return 0; }

Compile and run

Output:

7.12.3 dynamic_cast

Dynamic_cast is only use for casting derived class pointer to base class pointer.

Page 192: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

192

#include <iostream> #include <string> #include <exception> #include <typeinfo> using namespace std; class cBase { public: virtual void Print() {cout<<"Base Print something"<<endl; } }; class cDerived: public cBase { }; int main() { try { cBase *b; cDerived *d = new cDerived (); b = dynamic_cast< cBase *>(d); //derived class ptr to base class ptr. Always good! if (b==NULL) { cout<<"cast 1 failed"<<endl; //never faild in this cast. } cBase *b2 = new cDerived (); cDerived *d2 = dynamic_cast<cDerived *> (b2); //It should be good if (d2 ==NULL) { cout<<"cast 2 failed"<<endl; //never faild in this cast. } cBase *b3 = new cBase (); cDerived *d3 = dynamic_cast<cDerived *>(b3); if (d3 == NULL) { cout<<"cast3 failed"<<endl; //expected this one failed. } delete b2; delete b3; delete d; }catch (bad_cast& e) //or (exception &e) { cout << "Exception: " << e.what(); } return 0; }

Page 193: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

193

Compile and run

Output:

7.12.4 reinterpret_cast

It is the most dangerous cast, you can use reinterpret cast to convert any pointer to any pointer.

#include <iostream> #include <string> #include <exception> #include <typeinfo> using namespace std; class cBase { public: virtual void Print() {cout<<"Base Print something"<<endl; } }; class cDerived : public cBase { }; int main() { try

Page 194: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

194

{ cBase *b = new cBase (); cDerived *d = new cDerived (); b = reinterpret_cast<cBase *>(d); d = reinterpret_cast<cDerived *>(b); if ((b ==NULL) || (d==NULL)) { cout<<"some bad cast"<<endl;// don't expect to see this } }catch (bad_cast& e) //or (exception &e) { cout << "Exception: " << e.what(); } return 0; }

Output:

Nothing

7.13 Standard Template Library (STL) In the early day of C++, we don’t have STL. STL is so powerful that allow you to resolve many complicate

issues such as link list, queue, Stack, and so on.

Nowadays, STL provides to you many useful built in libraries. It will help you to get your work done

quicker and cleaner. I am going to show you some of STL containers that are very useful in your daily

work. There are many features of each container; I am not going to cover all of them. You need to dig

out yourself when you use them. It is very easy to use STL. Myself I don’t remember all of the features.

My best friend “google” is never let me down.

7.13.1 Vector

In what situation you need to use Vector instead of array? Array is always having a fixed size. You have

to define your “Max” size but you are not always use up to the max. Vector is very much like array but it

is allow you to increase or decrease its size dynamically. Note: most of the time, insert from the back.

There are many APIs of vector container that available for you to use. In this tutorial I don’t intend to

cover every single one. Remember your best friend “google” is available 24/7 for you.

empty() Return (true/false). True, if it is empty

size() Number of items are currently in vector

resize() Increase or decrease vector size

Page 195: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

195

erase() Erase all elements of vector

clear() Erase all elements of vector

front() First element of vector

back() Last element of vector

push_back() Add element to end of vector

pop_back() Remove element from end of vector

More APIs. google them!

#include <iostream> #include <string> #include <vector> using namespace std; int main() { //There are too many built in function that you can do with vector such as push_back, //pop_back, find, insert, replace, erase, sort, clear vector <int> v; //insert 1,2,3,4,5 to empty vector v for (int i =1; i<6; i++) { v.push_back(i); } vector<int>::const_iterator it;//new iterator for (it= v.begin(); it !=v.end();++it) { cout<<*it<<" "; } cout<<"Remove last item."<<endl; //remove the last item in vector v.pop_back(); for (it= v.begin(); it !=v.end();++it) { cout<<*it<<" "; } return 0; } Compile and run Output:

Page 196: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

196

7.13.2 List

It is very much like vector but it is more convenience when you need to insert/remove anywhere in the

list.

empty() Return (true/false). True, if it is empty

size() Number of items are currently in list

resize() Increase or decrease list size

erase() Erase element on list

remove() Remove element on list

unique() Remove duplicate items on list

clear() Erase all elements of list

sort() sort all elements of list

front() First element of list

back() Last element of list

push_front() Add element to front of list

pop_front() Remove element from front of list

push_back() Add element to end of list

pop_back() Remove element from end of list

More APIs. google them!

#include <iostream> #include <string>

Page 197: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

197

#include <list> using namespace std; int main() { list <int> lst; //insert 1,2,3,4,5 to empty list for (int i =1; i<6; i++) { lst.push_back(i); } for (int i =12; i > 6; i--) { lst.push_front(i); } list<int>::const_iterator it;//new iterator for (it= lst.begin(); it !=lst.end();++it) { cout<<*it<<" "; } cout<<endl; cout<<"Remove first item."<<endl; lst.erase(lst.begin()); for (it= lst.begin(); it !=lst.end();++it) { cout<<*it<<" "; } cout<<endl; return 0; }

Compile and run

Output:

Page 198: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

198

7.13.3 Map

There are single map and multiple map. Map is very useful in software development. Whenever you

need to keep track certain things, use map <key, value>

begin() Return iterator to beginning

end() Return iterator to end

empty() Return true/false. True is empty

size() Return size of map.

insert() Insert elements in pair <key,value>

erase() Erase elements.

clear() Clear content. Remove all elements

More APIs. google them!

#include <iostream> #include <string> #include <map> using namespace std; int main() { map <int, string > m; map<int, string >::iterator iter; cout<<"There are many ways to insert key,value to map"<<endl;

Page 199: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

199

m.insert(pair<int, string >(1,"Mickey Nguyen")); m.insert(map<int, string >::value_type(2,"Chau Tran")); m.insert(make_pair(3,("Sarah Nguyen"))); m.insert(make_pair(4,("Patrick Nguyen"))); for(iter= m.begin(); iter != m.end(); ++iter) { cout<<"key: "<<(*iter).first<<", name: "<<(*iter).second<<endl; } //find key cout<<endl<<"find key 3 and erase"<<endl; iter =m.find(3); // m.erase(mi); //or erase it by this way if (iter!= m.end()) { m.erase(3); } cout<<"After erase key = 3"<<endl; for(iter= m.begin(); iter != m.end(); ++iter) { cout<<"key: "<<(*iter).first<<", name: "<<(*iter).second<<endl; } cout<<endl; return 0; }

Compile and run

Output:

Page 200: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

200

7.13.4 Queue (FIFO)

Queue is a container which operates in first-in first-out. You push data in the back, you take data out

from the front.

front() Point to front

back() Point to back

push() Put data in

pop() Take data out

size() Return size of queue

empty() Return True/false. True is empty

More APIs. Google them!

#include <iostream> #include <string> #include <queue> using namespace std; int main() { queue <int> q; q.push(1); q.push(2); q.push(3); q.push(4); q.push(5); int size = q.size(); cout<<endl<<"Queue size: "<<q.size()<<endl; cout<<"q.front: "<<q.front()<<endl; q.pop(); cout<<"q.front: "<<q.front()<<endl; q.pop(); cout<<"q.front: "<<q.front()<<endl; q.pop(); cout<<endl<<"Curent Queue size: "<<q.size()<<endl; cout<<endl; return 0; }

Compile and run

Output:

Page 201: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

201

7.13.5 Deque

You can access both ends in deque.

empty() Return (true/false). True, if it is empty

size() Number of items are currently in list

erase() Erase element

clear() Erase all elements

push_front() Add element to front

pop_front() Remove element from front

push_back() Add element to end

pop_back() Remove element from end

More APIs. google them!

#include <iostream> #include <string> #include <deque> using namespace std; int main() { deque <int> dq;

Page 202: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

202

//insert 1,2,3,4,5 to empty list for (int i =1; i<6; i++) { dq.push_back(i); } for (int i =12; i > 6; i--) { dq.push_front(i); } deque<int>::const_iterator it;//new iterator for (it= dq.begin(); it !=dq.end();++it) { cout<<*it<<" "; } cout<<endl; cout<<"Remove first item."<<endl; dq.erase(dq.begin()); for (it= dq.begin(); it !=dq.end();++it) { cout<<*it<<" "; } cout<<endl; return 0; } Compile and run Output:

Page 203: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

203

7.13.6 Stack (LIFO)

push() Put data in the back

pop() Take data out from the back

size() Return size of queue

top() Last item in the stack

empty() Return True/false. True is empty

More APIs. Google them!

#include <iostream> #include <string> #include <stack> using namespace std; int main() { stack <int> s; s.push(1); s.push(2); s.push(3); s.push(4); s.push(5); int size = s.size(); cout<<endl<<"stack size: "<<s.size()<<endl; cout<<"s.top: "<<s.top()<<endl; s.pop(); cout<<"s.top: "<<s.top()<<endl; s.pop(); cout<<"s.top: "<<s.top()<<endl; s.pop(); cout<<endl<<"Curent stack size: "<<s.size()<<endl; cout<<endl; return 0; }

Compile and run

Output:

Page 204: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

204

7.14 Thread

7.14.1 Window thread example2 (_beginthreadex)

_beginthreadex is much more safe and control then using _beginthread

#include <iostream> #include <string> #include<windows.h> //for thread #include <process.h> //for _beginthreadex using namespace std; unsigned WINAPI ThreadFunction1 (LPVOID lpvThreadParm) { int i =0; while(i <20) { cout<<"Insisde ThreadFunction1 function ..... "<<endl; Sleep (1000); i++; } return 0; } unsigned WINAPI ThreadFunction2 (LPVOID lpvThreadParm) { int i =0; int number = (int)lpvThreadParm;

Page 205: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

205

while(i <20) { cout<<"Insisde ThreadFunction2 function ..... "<<endl; cout<<"number is "<<number<<endl; Sleep (1000); i++; } return 0; } int main() { HANDLE hThread[2]; unsigned threadID; int number =5; hThread[0]= (HANDLE)_beginthreadex(NULL, //security attribute 0, //stack size ThreadFunction1, //thread function NULL, //argument for thread function 0, //State suspend or run &threadID ); //threadID hThread[1]= (HANDLE)_beginthreadex(NULL, 0, ThreadFunction2, (void *)number, CREATE_SUSPENDED,//thread2 created in suspended state &threadID ); //resume to start ResumeThread(hThread[1]); WaitForMultipleObjects(2,hThread,TRUE,INFINITE);//2 is number of thread handle CloseHandle(hThread[0]); CloseHandle(hThread[1]); return 0; }

Compile and run

Output:

Page 206: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

206

7.14.2 Window thread example3 Createthread (standard C) #include <iostream> #include <string> #include<windows.h> //for thread using namespace std; DWORD WINAPI ThreadFunction1 (LPVOID lpvThreadParm) { int i =0; while(i <20) { cout<<"Insisde ThreadFunction1 function ..... "<<endl; Sleep (1000); i++; } return 0; } DWORD WINAPI ThreadFunction2 (LPVOID lpvThreadParm) { int i =0; int number = (int)lpvThreadParm; while(i <20) { cout<<"Insisde ThreadFunction2 function ..... "<<endl; cout<<"number is "<<number<<endl; Sleep (1000); i++; }

Page 207: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

207

return 0; } int main() { HANDLE hThread[2]; DWORD threadID[2]; int number =5; hThread[0]= CreateThread(NULL, //security attribute 0, //stack size ThreadFunction1, //thread function NULL, //argument for thread function 0, //State suspend or run &threadID[0] ); //threadID hThread[1]= CreateThread(NULL, 0, ThreadFunction2, (void *)number, CREATE_SUSPENDED,//thread2 created in suspended state o set to 0 &threadID[1] ); //resume to start ResumeThread(hThread[1]); WaitForMultipleObjects(2,hThread,TRUE,INFINITE);//2 is number of thread handle CloseHandle(hThread[0]); CloseHandle(hThread[1]); return 0; }

Compile and run

Output:

Page 208: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

208

7.14.3 Linux thread

Use Pthread (POSIX)

#include <stdio.h> #include <stdlib.h> #include <pthread.h> void *ThreadCallback( void *ptr ); int main() { pthread_t thread1, thread2; int value1, value2; value1 = pthread_create( &thread1, // thread Id NULL, //attribute ThreadCallback, //callback (void *)"number 1"); //optional argument for callback value2 = pthread_create( &thread2, NULL, ThreadCallback, (void *)"Number 2"); pthread_join( thread1, NULL); pthread_join( thread2, NULL); return 0; } void *ThreadCallback( void *ptr ) { printf("Create thread %s \n",(char*)ptr); }

Output:

Page 209: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

209

[User@mobox cppstudy]$ g++ -lpthread thread1.cpp

[User@mobox cppstudy]$ ./a.out

Create thread Number 2

Create thread number 1

7.15 Semaphore Using waiting mechanism to signal the thread to enter the critical section (sharing resource) or to wait

until his turn to enter. The thread before enter the sharing resource with other threads will check if the

sem counter is available (not 0); if the sem counter is not 0, then he locks that section and does

decrement sem counter by 1, then thread can enter that sharing resource, when he finishs his work and

leaving the critical section, he does increments sem by 1 then he signal other thread who is waiting to

enter the critical section to enter.

Real life example dirty but it is easy to understand: If there are 3 rest rooms (sharing resource) are

sharing 5 custmers (threads). That 3 rest rooms have 3 keys. So, each time customer (thread) wants to

enter the rest room, you give him a key. When he finishes using the rest room he returns the key back to

you. If one rest room are using, there are 2 keys left, if two rest rooms are using, then only 1 key left, if

all three rest room are using, then the next customer has to wait until the other customer return the

key.

7.15.1 Window semaphore #include <iostream> #include <string> #include<windows.h> //for thread #include <process.h> //for _beginthreadex #define MAX_SEM_COUNT 10 using namespace std; HANDLE hSemaphore; CRITICAL_SECTION cs; // global CRITICAL_SECTION DWORD WINAPI ThreadFunction1(LPVOID lpvThreadParm) { int i =0; while(i <20) { DWORD rc = WaitForSingleObject( hSemaphore, // handle to semaphore INFINITE); // no time-out switch(rc) { case WAIT_OBJECT_0: cout<<"Inside ThreadFunction1 function ..... "<<endl;

Page 210: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

210

break; // wait completed successfully case WAIT_TIMEOUT: // no timeouts possible since INFINITE was used cout<<"WaitForSingleObject failed at "<<__FILE__<<__LINE__; break; } rc = ReleaseSemaphore(hSemaphore, // handle to semaphore 1, // increase count by one NULL); // not interested in previous count if (!rc) { cout<<"WaitForSingleObject failed at "<<__FILE__<<__LINE__; } Sleep (1000); i++; } return 0; } DWORD WINAPI ThreadFunction2(LPVOID lpvThreadParm) { int i =0; while(i <20) { DWORD rc = WaitForSingleObject( hSemaphore, // handle to semaphore INFINITE); // no time-out switch(rc) { case WAIT_OBJECT_0: cout<<"Inside ThreadFunction2 function ..... "<<endl; break; // wait completed successfully case WAIT_TIMEOUT: // no timeouts possible since INFINITE was used cout<<"WaitForSingleObject failed at "<<__FILE__<<__LINE__; break; } rc = ReleaseSemaphore(hSemaphore, // handle to semaphore 1, // increase count by one NULL); // not interested in previous count if (!rc) { cout<<"WaitForSingleObject failed at "<<__FILE__<<__LINE__; } Sleep (1000); i++; } return 0; } int main() { HANDLE hThread[2]; DWORD threadID[2]; hSemaphore = CreateSemaphore(NULL, // no security attributes

Page 211: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

211

1, // initial count MAX_SEM_COUNT, // maximum count NULL); // unnamed semaphore if (!hSemaphore) { cout<<"CreateSemaphore failed at "<<__FILE__<<__LINE__; } hThread[0]= CreateThread(NULL,0, ThreadFunction1, NULL,0, &threadID[0] ); hThread[1]= CreateThread(NULL,0, ThreadFunction2, NULL,0, &threadID[1] ); WaitForMultipleObjects(2,hThread,TRUE,INFINITE); CloseHandle(hThread[0]); CloseHandle(hThread[1]); return 0; }

Compile and run

Output:

7.15.2 Linux semaphore //g++ semaphore1.cpp -o sm -lpthread #include <pthread.h> #include <semaphore.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> #include <iostream>

Page 212: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

212

using namespace std; void *FunctionThread(void*); sem_t sem; int number =0; int main() { // initialize semaphore to 2 sem_init(&sem, 0, //0, share between threads same process (exe), none 0, shared between processes 2); //if number of key set to 1, it acts like mutex pthread_t threadId[2]; pthread_create(&threadId[0], NULL, FunctionThread, NULL); pthread_create(&threadId[1], NULL, FunctionThread, NULL); pthread_join(threadId[0], NULL); pthread_join(threadId[1], NULL); sem_destroy(&sem); //destroy semaphore return 0; } void * FunctionThread(void * i) { int c=0; while(c < 5) { sem_wait(&sem); // down semaphore, wait number++; cout<<"number: "<<number<<endl; c++; sleep(1); sem_post(&sem); // release sem, up semaphore. } }

Output:

[User@mobox cppstudy]$ g++ semaphore1.cpp -o sm -lpthread

[User@mobox cppstudy]$ ./sm

number: 1

number: 2

number: 3

Page 213: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

213

number: 4

number: 5

number: 6

number: 7

number: 8

number: 9

number: 10

[User@mobox cppstudy]$

7.16 Critical section

7.16.1 Window critical section #include <iostream> #include <string> #include<windows.h> //for thread #include <process.h> //for _beginthreadex using namespace std; //Critical sections are cannot be named so you cannot use them to synchronize several processes. //This example, all three thread are in same one process (exe). //Use mutex if you have more than one exe void Print() { cout<<"Somebody just called me!"<<endl; } CRITICAL_SECTION cs; // global CRITICAL_SECTION unsigned WINAPI Callback1(LPVOID lpvThreadParm) { int i =0; while(i <20) { EnterCriticalSection(&cs); cout<<"Callback1 is calling Print function ..... "<<endl; //will call some function Print(); // access critical section LeaveCriticalSection(&cs); Sleep (1000); i++; } return 0; } unsigned WINAPI Callback2(LPVOID lpvThreadParm)

Page 214: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

214

{ int i =0; while(i <20) { EnterCriticalSection(&cs); cout<<"Callback2 is calling Print function ..... "<<endl; //will call some function Print(); // access critical section LeaveCriticalSection(&cs); Sleep (1000); i++; } return 0; } unsigned WINAPI Callback3(LPVOID lpvThreadParm) { int i =0; while(i <20) { EnterCriticalSection(&cs); cout<<"Callback3 is calling Print function ..... "<<endl; //will call some function Print(); // access critical section LeaveCriticalSection(&cs); Sleep (1000); i++; } return 0; } int main() { HANDLE hThread[3]; unsigned threadID; InitializeCriticalSection(&cs); hThread[0]= (HANDLE)_beginthreadex(NULL,0, Callback1, NULL,0, &threadID ); hThread[1]= (HANDLE)_beginthreadex(NULL,0, Callback2, NULL,0, &threadID ); hThread[2]= (HANDLE)_beginthreadex(NULL,0, Callback3, NULL,0, &threadID ); WaitForMultipleObjects(3,hThread,TRUE,INFINITE); CloseHandle(hThread[0]); CloseHandle(hThread[1]); CloseHandle(hThread[2]); DeleteCriticalSection(&cs); return 0; } Compile and run Output:

Page 215: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

215

7.17 Mutex The behavior is similar to “binary” Semaphore but there is one thing is different (binary which mean only

one key). Mutex, there is same thread lock and unlock the sharing section at the time. There is no

waiting or signal like semaphore. Semaphore, if you define only 1 key, then it behaves very much like

mutex. But with semaphore implementation, one thread locks (acquire) the key, other thread able to

unlock (release) the key.

With dirty example like I did in Semaphore section, if only one rest room (sharing resource) and one key,

you have 5 customers want to access. Each customer has equal chance, each customer will try to lock to

use, then unlock when they leave that sharing section.

7.17.1 Window mutex #include <iostream> #include <string> #include<windows.h> //for thread #include <process.h> //for _beginthreadex HANDLE hMutex = NULL; using namespace std; int number =0; CRITICAL_SECTION cs; // global CRITICAL_SECTION unsigned WINAPI FunctionThread(LPVOID lpvThreadParm) { int i =0; while(i < 5)

Page 216: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

216

{ // Request ownership of mutex. DWORD rc =::WaitForSingleObject(hMutex, // handle to the Mutex INFINITE); // wait forever (no timeout) switch(rc) { case WAIT_OBJECT_0: // wait completed successfully number++; cout<<"number: "<<number<<endl; if (lpvThreadParm !=NULL) cout<<(int)lpvThreadParm<<endl; break; // received ownership case WAIT_TIMEOUT: // timeouts impossible since INFINITE used cout<<"WaitForSingleObject failed at "<<__FILE__<<__LINE__; break; } // Release ownership of mutex rc = ::ReleaseMutex(hMutex); if (!rc) { cout<<"WaitForSingleObject failed at "<<__FILE__<<__LINE__; } Sleep (1000); i++; } return 0; } int main() { HANDLE hThread[3]; unsigned threadID[2]; int var =5; hMutex = CreateMutex( NULL, // no security attributes FALSE, // this mutex is not initially owned by the creating thread NULL); // unnamed mutex that will not be shared across processes if (!hMutex) { cout<<" CreateMutex failed at "<<__FILE__<<__LINE__; } hThread[0]= (HANDLE)_beginthreadex(NULL,0, FunctionThread, NULL,0, &threadID[0] ); hThread[1]= (HANDLE)_beginthreadex(NULL,0, FunctionThread, (void *)var,0, &threadID[1] ); WaitForMultipleObjects(2,hThread,TRUE,INFINITE); CloseHandle(hThread[0]); CloseHandle(hThread[1]); CloseHandle(hMutex); return 0; }

Compile and run

Page 217: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

217

Output:

7.17.2 Linux mutex critical section #include <pthread.h> #include <semaphore.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> #include <iostream> using namespace std; void * FunctionThread(void*); pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; int number =0; int var=5; int main() { pthread_mutex_init(&lock, NULL); pthread_t threadId[2]; pthread_create(&threadId[0], NULL, FunctionThread, NULL); pthread_create(&threadId[1], NULL, FunctionThread, (void *)&var); pthread_join(threadId[0], NULL); pthread_join(threadId[1], NULL); pthread_mutex_destroy(&lock); //destroy mutex return 0; }

Page 218: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

218

void * FunctionThread(void * i) { int c=0; while(c < 5) { pthread_mutex_lock( &lock ); //enter critical section number++; cout<<"number: "<<number<<endl; if (i!=NULL) { cout<<"var: "<<*(int*)i<<endl; } c++; sleep(1); pthread_mutex_unlock( &lock ); // leaving critical section. } }

Output:

[User@mobox cppstudy]$ g++ mutex.cpp -o mu -lpthread

[User@mobox cppstudy]$ ./mu

number: 1

var: 5

number: 2

var: 5

number: 3

var: 5

number: 4

var: 5

number: 5

var: 5

number: 6

number: 7

number: 8

Page 219: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

219

number: 9

number: 10

[User@mobox cppstudy]$

7.18 Interprocess Communication (IPC) There are many ways of interprocess communication that you can implement. I just provide a few

samples about interprocess communication.

What is interprocess communication? If you have two executable are running on same/different

machines and you want them to talk to each other. You need to pick which kind of IPC that is a good fit

for you need.

7.18.1 Window socket (winsock2)

7.18.1.1 TCP Server //TCP Server. loop back 127.0.0.1 #include "stdafx.h" #include<io.h> #include<stdio.h> #include<winsock2.h> #include<iostream> using namespace std; #pragma comment(lib,"ws2_32.lib") // Server side // 1. Open a socket // 2. Bind to a address(and port). // 3. Listen for incoming connections. // 4. Accept connections // 5. Read/Send int _tmain(int argc, _TCHAR* argv[]) { WSADATA wsa; SOCKET s , new_socket; struct sockaddr_in server , client; int c; char *message; char client_message[2000]; cout<<"I am a TCP server."<<endl; //Initialize Winsock if (WSAStartup(MAKEWORD(2,2),&wsa) != 0) { cout<<"Failed. Error Code : "<<WSAGetLastError()<<endl; return -1;

Page 220: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

220

} //Create a socket if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET) { cout<<"Could not create socket : " <<WSAGetLastError()<<endl; return -1; } //Prepare the sockaddr_in structure server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons( 1234 ); //Bind if( bind(s ,(struct sockaddr *)&server , sizeof(server)) == SOCKET_ERROR) { cout<<"Bind failed with error code : "<<WSAGetLastError()<<endl; return -1; } for (;;) { //Listen to incoming connections listen(s , 3); //max connection allow is 3 //Accept and incoming connection cout<<"Waiting for incoming connections..."<<endl; c = sizeof(struct sockaddr_in); new_socket = accept(s , (struct sockaddr *)&client, &c); if (new_socket == INVALID_SOCKET) { cout<<"accept failed with error code : "<<WSAGetLastError()<<endl; return -1; } //Reply to client message = "Got your message!"; send(new_socket , message , strlen(message) , 0); } system("PAUSE"); closesocket(s); WSACleanup(); return 0; }

Microsoft Visual studio compile and run Output:

7.18.1.2 TCP client

Page 221: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

221

//TCP client. loop back 127.0.0.1 #include "stdafx.h" #include<stdio.h> #include<winsock2.h> #include<iostream> using namespace std; #pragma comment(lib,"ws2_32.lib") // Client Side // 1. Create a socket // 2. Connect to remote server (loop back in this example) // 3. Send some data //4. Receive a reply int _tmain(int argc, _TCHAR* argv[]) { WSADATA wsa; SOCKET s; struct sockaddr_in server; char *message , server_reply[2000]; int recv_size; cout<<"I am a TCP client."<<endl; //Initializing Winsock if (WSAStartup(MAKEWORD(2,2),&wsa) != 0) { cout<<"Failed. Error Code : "<<WSAGetLastError()<<endl; return -1; } //Create a socket if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET) { cout<<"Could not create socket : " << WSAGetLastError()<<endl; return -1; } server.sin_addr.s_addr = inet_addr("127.0.0.1"); //loop back server.sin_family = AF_INET; server.sin_port = htons( 1234 ); //Connect to remote server if (connect(s , (struct sockaddr *)&server , sizeof(server)) < 0) { cout<<"connect error!"<<endl; return -1; } //Send some data message = "Mickey sent some texts"; if( send(s , message , strlen(message) , 0) < 0) { cout<<"Send failed"<<endl; return -1; } //Receive a reply from the server if((recv_size = recv(s , server_reply , 2000 , 0)) == SOCKET_ERROR)

Page 222: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

222

{ cout<<"recv failed"<<endl; } //Add a NULL terminating character to make it a proper string before printing server_reply[recv_size] = '\0'; cout<<server_reply<<endl; //message from server closesocket(s); WSACleanup(); system("PAUSE"); return 0; }

Microsoft Visual studio compile and run

Output:

7.18.1.3 UDP Server //UPD Server. loop back 127.0.0.1 #include "stdafx.h" #include<io.h> #include<stdio.h> #include<winsock2.h> #include<iostream> using namespace std; #pragma comment(lib,"ws2_32.lib") // Server side // 1. Open a socket // 2. Bind to a address(and port). // 3. Receive from // 4. send reply back to client int _tmain(int argc, _TCHAR* argv[]) { WSADATA wsa; SOCKET s , n; struct sockaddr_in server , client; int c;

Page 223: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

223

char *message; char client_message[2000]; cout<<"I am a TCP server."<<endl; //Initialize Winsock if (WSAStartup(MAKEWORD(2,2),&wsa) != 0) { cout<<"Failed. Error Code : "<<WSAGetLastError()<<endl; return -1; } //Create a socket if((s = socket(AF_INET , SOCK_DGRAM , 0 )) == INVALID_SOCKET) { cout<<"Could not create socket : " <<WSAGetLastError()<<endl; return -1; } //Prepare the sockaddr_in structure server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons( 1234 ); //Bind if( bind(s ,(struct sockaddr *)&server , sizeof(server)) == SOCKET_ERROR) { cout<<"Bind failed with error code : "<<WSAGetLastError()<<endl; return -1; } int len = sizeof(client); for (;;) { n = recvfrom(s,client_message,1000,0,(struct sockaddr *)&client,&len); sendto(s,client_message,n,0,(struct sockaddr *)&client,sizeof(client)); client_message[n]=0;//NULL termination cout<<client_message<<endl; } system("PAUSE"); closesocket(s); WSACleanup(); return 0; }

Microsoft Visual studio compile and run

Output:

Page 224: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

224

7.18.1.4 UDP client //UDP client. loop back 127.0.0.1 #include "stdafx.h" #include<stdio.h> #include<winsock2.h> #include<iostream> using namespace std; #pragma comment(lib,"ws2_32.lib") // Client Side // 1. Create a socket // 2. Connect to remote server (loop back in this example) // 3. Send some data //4. Receive a reply int _tmain(int argc, _TCHAR* argv[]) { WSADATA wsa; SOCKET s,n; struct sockaddr_in server; char *message , server_reply[2000]; int recv_size; cout<<"I am a TCP client."<<endl; //Initializing Winsock if (WSAStartup(MAKEWORD(2,2),&wsa) != 0) { cout<<"Failed. Error Code : "<<WSAGetLastError()<<endl; return -1; } //Create a socket if((s = socket(AF_INET , SOCK_DGRAM , 0 )) == INVALID_SOCKET) { cout<<"Could not create socket : " << WSAGetLastError()<<endl; return -1; } server.sin_addr.s_addr = inet_addr("127.0.0.1"); //loop back server.sin_family = AF_INET; server.sin_port = htons( 1234 ); //Send some data message = "Mickey sent some texts"; if( sendto(s , message , strlen(message) , 0, (struct sockaddr *)&server,sizeof(server)) < 0) { cout<<"Send failed"<<endl; return -1; } //Receive a reply from the server n = recvfrom(s , server_reply , 2000 , 0,NULL,NULL);

Page 225: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

225

server_reply[n]=0; //NULL termination cout<<server_reply<<endl; //message from server closesocket(s); WSACleanup(); system("PAUSE"); return 0; }

Microsoft Visual studio compile and run

Output:

7.18.2 Linux UPD socket

Build both client and server, start server first, then start client.

7.18.2.1 UDP server /* Sample UDP server */ //127.0.0.1 #include <sys/socket.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include<arpa/inet.h> int main(int argc, char**argv) { int sockfd,n; struct sockaddr_in servaddr,cliaddr; socklen_t len; char mesg[1000]; sockfd=socket(AF_INET,SOCK_DGRAM,0); bzero(&servaddr,sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr=htonl(INADDR_ANY); servaddr.sin_port=htons(12345); bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr)); for (;;) { len = sizeof(cliaddr); n = recvfrom(sockfd,mesg,1000,0,(struct sockaddr *)&cliaddr,&len); sendto(sockfd,mesg,n,0,(struct sockaddr *)&cliaddr,sizeof(cliaddr)); mesg[n] = 0; //NULL termination

Page 226: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

226

printf("Received the following:\n"); printf("%s",mesg); } }

Build and start server before start the client:

[User@mobox cppstudy]$ g++ udpserver.cpp -o udps

[User@mobox cppstudy]$ ./udps

Received the following:

This is packet 0

Received the following:

This is packet 1

Received the following:

This is packet 2

Received the following:

This is packet 3

Received the following:

This is packet 4

7.18.2.2 UPD client /* Sample UDP client */ //127.0.0.1 loopback #include <sys/socket.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include<arpa/inet.h> int main(int argc, char**argv) { int sockfd,n; struct sockaddr_in servaddr,cliaddr; char sendline[1000]; char recvline[1000]; if (argc != 2) { printf("usage: udpcli <IP address>\n");

Page 227: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

227

exit(1); } sockfd=socket(AF_INET,SOCK_DGRAM,0); bzero(&servaddr,sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr=inet_addr(argv[1]); servaddr.sin_port=htons(12345); for (int i =0; i < 10; i++) { printf("Sending packet %d\n", i); sprintf(sendline, "This is packet %d\n", i); sendto(sockfd,sendline,strlen(sendline),0, (struct sockaddr *)&servaddr,sizeof(servaddr)); n=recvfrom(sockfd,recvline,sizeof(recvline),0,NULL,NULL); printf("Receive from Server: %s",recvline); } }

Compile and run after start the server:

[User@mobox cppstudy]$ g++ udpclient.cpp -o udpc

[User@mobox cppstudy]$ ./udpc 127.0.0.1

Sending packet 0

Receive from Server: This is packet 0

Sending packet 1

Receive from Server: This is packet 1

Sending packet 2

Receive from Server: This is packet 2

Sending packet 3

Receive from Server: This is packet 3

Sending packet 4

Receive from Server: This is packet 4

[User@mobox cppstudy]$

Page 228: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

228

7.18.2.3 TCP Server

Build server, start it, then start client.

#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <time.h> #include <iostream> using namespace std; int main(int argc, char *argv[]) { int listenfd = 0, connfd = 0; struct sockaddr_in serv_addr; char sendBuff[]= "Mickey sent some texts to Server"; time_t ticks; listenfd = socket(AF_INET, SOCK_STREAM, 0); memset(&serv_addr, '0', sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(5000); bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)); listen(listenfd, 10); while(1) { connfd = accept(listenfd, (struct sockaddr*)NULL, NULL); send(connfd, sendBuff, strlen(sendBuff),0); close(connfd); sleep(1); } return 0; }

Run it!

[User@mobox cppstudy]$ g++ tcpserver.cpp -o tcps

[User@mobox cppstudy]$ ./tcps

Page 229: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

229

7.18.2.4 TCP Client

Build both client and server, start server first, then start client

//127.0.0.1 loop back #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <netdb.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <arpa/inet.h> #include <iostream> using namespace std; int main(int argc, char *argv[]) { int sockfd = 0, n = 0; char recvBuff[1024]; struct sockaddr_in serv_addr; if(argc != 2) { printf("\n Usage: %s <ip of server> \n",argv[0]); return 1; } memset(recvBuff, '0',sizeof(recvBuff)); if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("\n Error : Could not create socket \n"); return 1; } memset(&serv_addr, '0', sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(5000); if(inet_pton(AF_INET, argv[1], &serv_addr.sin_addr)<=0) { printf("\n inet_pton error occured\n"); return 1; } if( connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { printf("\n Error : Connect Failed \n"); return 1; } while ( (n = recv(sockfd, recvBuff, strlen(recvBuff),0)) > 0) {

Page 230: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

230

recvBuff[n]=0;//NULL termination cout<<recvBuff<<endl; } if(n < 0) { printf("\n Read error \n"); } return 0; }

Run it!

[User@mobox cppstudy]$ g++ tcpclient.cpp -o tcpc

[User@mobox cppstudy]$ ./tcpc 127.0.0.1

Mickey sent some texts to Server

[User@mobox cppstudy]$

7.18.3 Linux Shared memory

7.18.3.1 Server shared memory

Start server first then start client.

#include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <stdio.h> #include <unistd.h> #include <string.h> #define SHMSZ 1024 main(int argc, char **argv) { char c, tmp; int shmid; key_t key; char *shm, *s; /* * Shared memory segment at 1234 * "1234". */ key = 1234; /* * Create the segment and set permissions. */

Page 231: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

231

if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0) { perror("shmget"); return 1; } /* * Now we attach the segment to our data space. */ if ((shm = (char*)shmat(shmid, NULL, 0)) == (char *) -1) { perror("shmat"); return 1; } char *message = "hello"; sprintf(shm,"%s",message); return 0; }

Run it!

[User@mobox cppstudy]$ g++ shmserver.cpp -o sms

shmserver.cpp: In function ‘int main(int, char**)’:

shmserver.cpp:40: warning: deprecated conversion from string constant to ‘char*’

[User@mobox cppstudy]$ ./sms

[User@mobox cppstudy]$

7.18.3.2 Client shared memory

Start client after server.

#include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <stdio.h> #include <unistd.h> #include <string.h> #define SHMSZ 1024 main(int argc, char **argv) { char c, tmp; int shmid; key_t key; char *shm, *s;

Page 232: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

232

/* * Shared memory segment at 1234 * "1234". */ key = 1234; /* * Create the segment and set permissions. */ if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0) { perror("shmget"); return 1; } /* * Now we attach the segment to our data space. */ if ((shm = (char*)shmat(shmid, NULL, 0)) == (char *) -1) { perror("shmat"); return 1; } char *message = " world"; strcat(shm,message); printf("\n message = %s\n",shm); return 0; }

Run it!

[User@mobox cppstudy]$ g++ shmclient.cpp -o smc

shmclient.cpp: In function ‘int main(int, char**)’:

shmclient.cpp:39: warning: deprecated conversion from string constant to ‘char*’

[User@mobox cppstudy]$ ./smc

message = hello world

[User@mobox cppstudy]$

7.18.4 Linux Message queue

7.18.4.1 Receive from queue //IPC_msgq_rcv.c #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <stdio.h>

Page 233: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

233

#include <stdlib.h> #define MAXSIZE 128 using namespace std; struct msgbuff { long mtype; char mtext[MAXSIZE]; } ; int main() { int msqid; key_t key; struct msgbuff rcvbuffer; key = 1234; if ((msqid = msgget(key, 0666)) < 0) printf("Error in msgget\n"); //Receive an answer of message type 1. if (msgrcv(msqid, &rcvbuffer, MAXSIZE, 1, 0) < 0) printf("Error to in msgrcv\n"); printf("%s\n", rcvbuffer.mtext); return 0; } Run it! [User@mobox cppstudy]$ g++ msgqueuervc.cpp -o msgqr [User@mobox cppstudy]$ ./msgqr Mickey is sending some texts [User@mobox cppstudy]$

7.18.4.2 Sending to queue //IPC_msgq_send.c #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #define MAXSIZE 128 using namespace std; struct msgbuff { long mtype; char mtext[MAXSIZE];

Page 234: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

234

}; int main() { int msqid; int msgflg = IPC_CREAT | 0666; key_t key; struct msgbuff sbuf; size_t buflen; key = 1234; if ((msqid = msgget(key, msgflg )) < 0) //Get the message queue ID for the given key printf("Error in msgget\n"); //Message Type sbuf.mtype = 1; sprintf(sbuf.mtext,"Mickey is sending some texts"); buflen = strlen(sbuf.mtext) + 1 ; if (msgsnd(msqid, &sbuf, buflen, IPC_NOWAIT) < 0) { printf ("%d, %d, %s, %d\n", msqid, sbuf.mtype, sbuf.mtext, buflen); printf("Error in msgsnd\n"); } else printf("Message Sent\n"); return 0; }

Run it!

[User@mobox cppstudy]$ g++ msgqueuesend.cpp -o msgqs

[User@mobox cppstudy]$ ./msgqs

Message Sent

[User@mobox cppstudy]$

8 C++ 11 Note: I used Microsoft studio 2012 to compile and run all the C++11. This Cygwin did not have 2011

libraries yet.

Page 235: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

235

What is C++11? The compiler is getting smater each day. In 2011, beside STL as we used to use, there

are many new things new libraries, new syntaxes that introduced to programmers. Some libraries are

very much like C#’s library. Personally, I don’t like all of the new changes, some are really cool, some are

Nah whatever, I like the traditional way doing things.

8.1 auto type and decltype - auto type, when you use the word “auto” as your data type, the compiler will smart enough to

figure out which is a correct data type you are trying to use.

- decltype is another way to let the compiler to extract a correct data type that you are using in

your code.

// ConsoleApplication1.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <string> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { //when you use auto type, the compiler will figure out which is a correct data type base on the value assign to it. auto mydecimal = 100; int newdecimal = 5; newdecimal += mydecimal; auto myfloat = 99.99; float newfloat = 10.11; newfloat += myfloat; auto mystring = "Trong Nguyen"; string newstring = "Mickey "; newstring += mystring; cout << "newdecimal: " << newdecimal << endl; cout << "newfloat: " << newfloat << endl; cout << "newstring: " << newstring << endl; //decltype is very much like auto, decltype will extract the data type from () and assign that data type to the variable name decltype(5) myInt = 5; decltype(5) mynewdecimal = 50; //I can set the new value for it. decltype (11.11) myfloatNum = 22.22; decltype (", Tony") mystr = ", Mike"; //you can use different words but have to be the same lenght. This is char *, not a string type newdecimal += myInt; newfloat += myfloatNum; newstring += mystr;

Page 236: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

236

cout << "After using decltype function" << endl; cout << "newdecimal: " << newdecimal << endl; cout << "newfloat: " << newfloat << endl; cout << "newstring: " << newstring << endl; system("PAUSE");//To whole your screen so you can see the output return 0; }

8.2 for_each syntax:

for_each (begin iterator, end iterator,function call);

Note:function call is can be a regular function or a lambda function expression.

This is useful for a short implementation of for loop when you need to search something in the

container such as list,vector,array.

#include "stdafx.h" #include <iostream> #include <string> #include <list> #include<algorithm> using namespace std; void PrintName(string name) { cout << name << endl; } int _tmain(int argc, _TCHAR* argv[]) { list<string> l; l.push_front("Mickey Nguyen"); l.push_front("Chau Nguyen"); l.push_front("Sarah Nguyen"); l.push_front("Patrick Nguyen"); for_each(l.begin(),l.end(), PrintName); //normal way to do it

Page 237: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

237

cout << "Lambda Expression:" << endl; //lambda fucntion to replace PrintName function for_each(l.begin(), l.end(), [] (string name) {cout << name << endl; }); system("PAUSE");//To whole your screen so you can see the output return 0; }

8.3 Lambda expression Using lambda express to make your code is short,clean and easy to read. See those examples at below.

Note: if you worked on C# before, it is very much like C#

Syntax:

[] () {} //[] indicate to compiler, this is lambda expression, () is parameter list, {} is implementation

[&] for refrerence, or [=]for copy value, or [this] for this pointer

// ConsoleApplication1.cpp : Defines the entry point for the console application. //

8.3.1 Example1,how to define lambda function expression #include "stdafx.h" #include <iostream> #include <string> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { //lambda fucntion //[] indicate to compiler that it is lambda function auto MyFunc1 = [] ( ) {cout << "Mickey Nguyen" << endl; }; //() there is an empty parameter list,inside{} did not return anything MyFunc1();

Page 238: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

238

//[] indicate to compiler that it is lambda fucntion //Cannot use auto type for a and b parameters auto MyFunc2 = [] (int a, int b) {cout << a + b << endl; return a + b; };//() there are two parameters, inside {} return a int int result = MyFunc2(5, 5); //can use either int or auto for result MyFunc2(10, 10); //can ignore the return value auto MyFunc3 = [] (int a, int b) {cout << a + b << endl; return a + b; }(10, 5);//feeding parameter cout << MyFunc3 << endl; system("PAUSE");//To whole your screen so you can see the output return 0; }

8.3.2 Example2, how to use lambda function #include "stdafx.h" #include <iostream> #include <string> #include <vector> #include<algorithm> using namespace std; void PrintName(string name) { cout << name << endl; } int _tmain(int argc, _TCHAR* argv[]) { vector<string> v; v.push_back("Mickey Nguyen"); v.push_back("Chau Nguyen"); v.push_back("Sarah Nguyen"); v.push_back("Patrick Nguyen"); for_each(v.begin(), v.end(), PrintName); //normal way to do it cout << "Lambda Expression:" << endl; //lambda fucntion to replace PrintName function for_each(v.begin(), v.end(), [] (string name) {cout << name << endl; }); system("PAUSE");//To whole your screen so you can see the output return 0;

Page 239: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

239

}

8.3.3 Example3,another example of using lambda function // ConsoleApplication1.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <algorithm> #include <iostream> #include <string> #include <vector> using namespace std; bool compare(int i, int j) { return (i > j); //decrease order, (i<j) for increase order } int _tmain(int argc, _TCHAR* argv[]) { //lambda fucntion vector <int> v(5); for (int i = 0; i < 5; i++) { v[i] = i; } //print out before sort cout << "Print out before sort" << endl; for_each(v.begin(), v.end(), [] (int n) {cout << n << endl; }); //lambda sort(v.begin(), v.end(), [] (int i, int j)->bool {return (i > j); });//lambda, you can replace this lambda by the compare func above //print out after sort cout << "Print out after sort" << endl; for_each(v.begin(), v.end(), [] (int n) {cout << n << endl; });//lambda system("PAUSE");//To whole your screen so you can see the output return 0; }

Page 240: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

240

8.4 Range-Based for loop It is very convenient for loop thru the whole container as list,vector, … within its length.

Syntax:

for (auto item : container)

8.4.1 Example1, range –based for loop #include "stdafx.h" #include <iostream> #include<algorithm> #include <vector> #include <map> #include <string> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int array[4] = { 1, 2, 3, 4 }; for (int item : array) //loop thru the array, can use auto for data type, too. int item { cout << item << " "; } cout << endl; vector <int> v; v.push_back(1); v.push_back(2); v.push_back(3); for (auto item : v) //loop thru the vector v, can be used int for data type, too. int item {

Page 241: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

241

cout << item << " "; } map <int, string > m; m.insert(pair<int, string >(1, "Mickey Nguyen")); m.insert(map<int, string >::value_type(2, "Chau Tran")); m.insert(make_pair(3, ("Sarah Nguyen"))); m.insert(make_pair(4, ("Patrick Nguyen"))); cout << endl; for (auto item : m) //use auto type for container type { cout << item.first << " " << item.second << endl; } cout << endl; system("PAUSE");//To whole your screen so you can see the output return 0; }

8.4.2 Example2,modify array data #include "stdafx.h" #include <iostream> #include <string> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int array[5] = { 1, 2, 3, 4, 5 }; //modify the value, using & for (int &item : array) //use auto should work fine,too { item *= 2; } for (int item : array) //use auto should work fine,too { cout << item << " "; } cout << endl; system("PAUSE");//To whole your screen so you can see the output return 0; }

Page 242: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

242

8.5 Initialization In C++11, you can have the whole new way of initializing your data.

8.5.1 Example1, initialization

#include "stdafx.h" #include <iostream> #include<algorithm> #include <vector> #include <map> #include <string> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int i(10);//instead of int i =10 int j{ 20 };//instead of int j =20 cout << i << " " << j << " " << endl; vector <int> v{ 1, 2, 3, 4 }; // initialize vector without go thru push_back for (auto item : v) //using range-based { cout << item << " "; } cout << endl; vector <int> v2 = { 5, 6, 7, 8 }; // initialize vector without go thru push_back for (auto item : v2) //using range-based { cout << item << " "; } cout << endl; system("PAUSE");//To whole your screen so you can see the output return 0; }

Page 243: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

243

8.5.2 Example2, new way of initialize data members

#include "stdafx.h" #include <iostream> #include <string> using namespace std; class cA { public: cA() {} int i = 5; //you cannot do like this before 2011 float j{ 9.9 };//you cannot do like this before 2011 }; int _tmain(int argc, _TCHAR* argv[]) { cA a; cout << "i: " << a.i << endl; cout << "j: " << a.j << endl; cout << endl; system("PAUSE");//To whole your screen so you can see the output return 0; }

8.6 Using base class methods and constructors Using “using” key word; in derived class, you can specify what methods/constructors that you want to

use from base class.

#include "stdafx.h"

Page 244: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

244

#include <iostream> #include <string> using namespace std; class cA { public: cA() {} cA(int a) { cout << "cA constructor with int parameter " << a << endl; } void Print(float i) { cout << "Class A printing float number:" << i << endl; } }; class cB : public cA { public: cB() {} void Print(int j) { cout << "Class B printing int:" << j << endl; } }; class cC : public cA { public: //My compiler does not fully support C++11 yet. with the latest compiler, you just include the line using cA::cA; //you don't have to define the constructor cC() and cC(int), it will use all parent constructors using cA::cA;//now, can create class C instance using cA contructor using cA::Print; //now both Print functions of cC and cA are visible to class C instant cC() {} cC(int c) :cA(c) { cout << "cC constructor with int parameter " <<c<< endl; } void Print(int j) { cout << "Class C printing int:" << j << endl; } }; int _tmain(int argc, _TCHAR* argv[]) { cB b; b.Print(5); b.Print(5.5f);//it could not use parent cA::Print cC c; c.Print(4); c.Print(4.4f); //it using parent cA::Print cC c1(5); cout << endl; system("PAUSE");//To whole your screen so you can see the output return 0; }

Page 245: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

245

8.7 override specifier It a cool idea to include override keyword at the end of function that you intend to override from parent

class. This will ensure that you override a correct method.

#include "stdafx.h" #include <iostream> #include <string> using namespace std; class cA { public: cA() {} virtual void PrintMsg() { cout << "cA PrintMsg" << endl; } virtual void PrintInt() { cout << "cA PrintInt" << endl; } }; class cB : public cA { public: cB() {} void PrintMsg() override { cout << "cB PrintMsg" << endl; } void PrintInt() override { cout << "cB PrintInt" << endl; } //void PrintInt(int i) override { cout << "cB PrintInt" << endl; }//ERROR, wrong signature, cA did not have method for overriding //void PrintFloat() override { cout << "cB Float" << endl; } //ERROR, cA did not have method for overriding }; int _tmain(int argc, _TCHAR* argv[]) { cA *ptr = new cA(); cB b; ptr = &b; //You can replace 3 lines above with this cA *ptr = new cB(); ptr->PrintMsg(); ptr->PrintInt();

Page 246: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

246

cout << endl; system("PAUSE");//To whole your screen so you can see the output return 0; }

8.8 Final keyword This is another cool idea, when you specify the your class/method as “final”, which mean, it as is. You

don’t want other class inherit to final class or override the final method.

8.8.1 Example1, don’t allow override final method

Cannot override final method.

#include "stdafx.h" #include <iostream> #include <string> using namespace std; class cA { public: cA() {} virtual void PrintMsg() { cout << "cA PrintMsg" << endl; } virtual void PrintInt() { cout << "cA PrintInt" << endl; } virtual void PrintFloat() final { cout << "cA PrintFloat" << endl; } }; class cB : public cA { public: cB() {} void PrintMsg() override { cout << "cB PrintMsg" << endl; } void PrintInt() override { cout << "cB PrintInt" << endl; } //void PrintFloat() override { cout << "cB Float" << endl; } //ERROR, cA defined as final, cannot override it }; int _tmain(int argc, _TCHAR* argv[]) { cA *ptr = new cA(); cB b;

Page 247: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

247

ptr = &b; //You can replace 3 lines above with this cA *ptr = new cB(); ptr->PrintMsg(); ptr->PrintInt(); cout << endl; system("PAUSE");//To whole your screen so you can see the output return 0; }

8.8.2 Example2, don’t allow inherit to final class

Cannot inherits to final class

#include "stdafx.h" #include <iostream> #include <string> using namespace std; class cA final //final class, nobody can derived from it { public: cA() {} virtual void PrintMsg() { cout << "cA PrintMsg" << endl; } virtual void PrintInt() { cout << "cA PrintInt" << endl; } virtual void PrintFloat() final { cout << "cA PrintFloat" << endl; } }; class cB //: public cA //No longer able to inherits to cA, it specify as a final class { public: cB() {} void PrintMsg() { cout << "cB PrintMsg" << endl; } //Error! have to remove the keyword override to make it work void PrintInt() { cout << "cB PrintInt" << endl; } //Error! have to remove the keyword override to make it work }; int _tmain(int argc, _TCHAR* argv[]) { cA *ptr = new cA(); ptr->PrintMsg();

Page 248: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

248

ptr->PrintInt(); cB b; b.PrintMsg(); b.PrintInt(); //You can replace 3 lines above with this cA *ptr = new cB(); cout << endl; system("PAUSE");//To whole your screen so you can see the output return 0; }

8.9 move move data from one variable/object/buffer to another one who take over ownership. People said, it is

less expensive then memcpy or assignment.

8.9.1 example1, move simple data as string #include "stdafx.h" #include <iostream> #include <string> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { string str1 = "Mickey Nguyen"; string str2; str2 = str1; cout << "str2: " <<str2<< endl; string str3; str3 = move(str2); //move data from str2 to str3 cout << "str3: " <<str3<< endl; cout << "str2: " << str2<< endl; //str2 don’t have any data after move to str3 cout << endl; system("PAUSE");//To whole your screen so you can see the output return 0; }

Page 249: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

249

8.9.2 example2, move one vector to another vector #include "stdafx.h" #include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { vector <int> v = { 1, 2, 3, 4, 5 }; cout << "v items:" << endl; for(auto item :v) { cout << item << " "; } vector <int> v2 = move(v); //move data from v to v2 cout <<endl<< "now v items:" << endl; for (auto item : v) { cout << item << " "; //don’t have any data after move to v2 } cout << endl << "v2 items:" << endl; for (auto item : v2) { cout << item << " "; } cout << endl; system("PAUSE");//To whole your screen so you can see the output return 0; }

Page 250: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

250

8.10 enum class With enum class you can have two items sharing the same name with different values in two separate

enum

#include "stdafx.h" #include <iostream> #include <string> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { //enum Weather {HOT,COOL,GOOD,BAD}; //could not compile, will not allow to share the same item with different value //enum Girl {GOOD,HOT,BAD,MEAN}; //could not compile, will not allow to share the same item with different value //with enum class, you can compile and use them enum class Weather { HOT, COOL, GOOD, BAD }; enum class Girl { GOOD, HOT, BAD, MEAN }; Weather w; w = Weather::HOT; Girl g; g = Girl::HOT; cout << "Weather HOT: "<< (int)w << endl; cout << "Girl HOT: " << (int)g << endl; system("PAUSE");//To whole your screen so you can see the output return 0; }

8.11 Define function with delete keyword When you define a function with delete keyword, this will ensure that you cannot passing a wrong data

type such as int intend for float or double.

#include "stdafx.h" #include <iostream> #include <string> using namespace std; void OnlyInt(int i) { cout << "int i: " << i<< endl; } void OnlyDouble(double d) { cout << "Double d: " <<d<< endl; } //using delete to allow only correct type to pass in the function.

Page 251: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

251

//without define these "delete" you can passing int,float,double, compiler will truncate or round up without your wills. template < typename T> void OnlyInt(T) = delete; template < typename T> void OnlyDouble(T) = delete; int _tmain(int argc, _TCHAR* argv[]) { OnlyInt(5); OnlyDouble(9.9); //without define delete, you can use these function calls without a problem //OnlyInt(5.5); //with delete defined, these will false to compile //OnlyDouble(9);//with delete defined, these will false to compile system("PAUSE");//To whole your screen so you can see the output return 0; }

8.12 Thread Syntax to create a thread.

threat name (function callback, parameters of your function callback);

The function call back that you plan to pass in your thread can have any type of parameter, and the

return of function call back will be ignored. So, if you want to return something, using passing reference

&.

Example of return of your function callback: void CountingAndSleep(int & i) { while (i <100) i++; cout<<i<<endl; // }

When you create a thread, you need to use ref wrapper.

int i = 1; thread t(CountingAndSleep, std::ref(i));

Page 252: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

252

8.12.1 Example1, without calling thread join ( )

Create a thread without calling thread join. When you don’t call thread join, the main thread will finish

early on its own, the thread you created is no longer a good thread, it cannot terminate at the end.

#include "stdafx.h" #include <iostream> #include <string> #include <thread> using namespace std; void CountingAndSleep() { for (int i = 0; i <= 20000; i++) { if (i == 1 || i == 5000 || i == 10000 || i == 15000 || i == 20000) { cout << i << " "; this_thread::sleep_for(chrono::seconds(5));//sleep for 5 second } } } int _tmain(int argc, _TCHAR* argv[]) { cout << "Main thread begin...." << endl; thread t(CountingAndSleep); //create a thread, function call back has no parameter cout << "Main thread ended..." << endl; system("PAUSE");//To whole your screen so you can see the output return 0; }

Page 253: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

253

8.12.2 Example2 of calling thread join( )

Call thread join right after you create the thread; now, the main thread will wait for the child thread that

you created has a chance to finish its work then both child thread and main thread can be terminated

safely without a error.

#include "stdafx.h" #include <iostream> #include <string> #include <thread> using namespace std; void CountingAndSleep() { for (int i = 0; i <= 20000; i++) { if (i == 1 || i == 5000 || i == 10000 || i == 15000 || i == 20000) { cout << i << " "; this_thread::sleep_for(chrono::seconds(5));//sleep for 5 second } } } int _tmain(int argc, _TCHAR* argv[]) { cout << "Main thread begin...." << endl; thread t(CountingAndSleep); //create a thread t.join();//calling join to tell main thread, hey waiting for me to finish my work cout <<endl<< "Main thread ended..." << endl; system("PAUSE");//To whole your screen so you can see the output

Page 254: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

254

return 0; }

8.12.3 Example3, calling thread detach( )

In this example, after create the thread, I call detach() instead of join(). Calling detach() to tell main

thread that, go ahead to do whatever you like to do, don’t wait for me. I will take care of myself. Bye

main!

#include "stdafx.h" #include <iostream> #include <string> #include <thread> using namespace std; void CountingAndSleep() { for (int i = 0; i <= 20000; i++) { if (i == 1 || i == 5000 || i == 10000 || i == 15000 || i == 20000) { cout << i << " "; this_thread::sleep_for(chrono::seconds(5));//sleep for 5 second } } } int _tmain(int argc, _TCHAR* argv[]) { cout << "Main thread begin...." << endl; thread t(CountingAndSleep); //create a thread t.detach();//calling detach to tell main thread, hey don't wait for me, I am good, I will take care of myself cout <<endl<< "Main thread ended..." << endl; system("PAUSE");//To whole your screen so you can see the output return 0; }

Page 255: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

255

8.12.4 Example4, multi-threading

Multi-threading

#include "stdafx.h" #include <iostream> #include <string> #include <thread> using namespace std; void CallBack(int tid) { for (int i = 0; i < 10; i++) { if (tid == 0) { cout << "Thread " << tid << "---------" << endl; } else if (tid == 1) { cout << "Thread " << tid << "++++++++++" << endl; } cout << endl; } } int _tmain(int argc, _TCHAR* argv[]) { cout << "Main thread begin...." << endl; thread t[2]; t[0]= thread(CallBack,0); t[1] = thread(CallBack, 1); t[0].join();//calling join to tell main thread, hey wait for me! t[1].join();//calling join to tell main thread, hey wait for me! cout <<endl<< "Main thread ended..." << endl; system("PAUSE");//To whole your screen so you can see the output return 0; }

Page 256: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

256

8.12.5 Multithreading and mutex

In this example, both thread 0 and thread 1 try to update the data at the same time. They use mutex to

lock and unlock to prevent the other thread to interrupt when they are update the data. Look at the

out put from the run, you can see tid1 print out the value 380 instead of 500 because tid0 still locks it,

that is what happen.

#include "stdafx.h" #include <iostream> #include <string> #include <thread> #include <mutex>

Page 257: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

257

using namespace std; mutex m; //mutex //global data int data = 0; void CallBack(int tid) { for (int i = 0; i < 10; i++) { if (tid == 0) { cout << "Thread " << tid << "---------" << endl; for (int i = 0; i < 10; i++) { m.lock(); data += 10; m.unlock(); cout << "data accessed by tid 0: " << data << endl; } } else if (tid == 1) { cout << "Thread " << tid << "++++++++++" << endl; for (int i = 0; i < 10; i++) { m.lock(); data += 100; m.unlock(); cout << "data accessed by tid 1: " << data << endl; } } cout << endl; } } int _tmain(int argc, _TCHAR* argv[]) { cout << "Main thread begin...." << endl; thread t[2]; t[0]= thread(CallBack,0); t[1] = thread(CallBack, 1); t[0].join();//calling join to tell main thread, hey wait for me! t[1].join();//calling join to tell main thread, hey wait for me! cout <<endl<< "Main thread ended..." << endl; system("PAUSE");//To whole your screen so you can see the output return 0; }

Page 258: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

258

8.13 unique_ptr unique_ptr it works very much like auto_ptr, it transfers ownership and it will clean up memory after

transferred or go out its scope just as auto_ptr did; however, it fixed the bug that auto_ptr had. When

you try to use copy constructor/assignment operator, unique_ptr will not allow you to use it. If you try

to use copy constructor or assignment operator, you will see the error at compilation time. Note: go

back to auto_ptr section to see how it works.

#include "stdafx.h" #include <iostream> #include <memory> using namespace std; class cA { public: int number; }; void WillNotHasMemoryIssue() { std::unique_ptr<cA> p1(new cA); //allocate memory for p1 std::unique_ptr<cA> p2; //did not allocate memory and did not point to anywhere yet. p1->number = 100; cout << "p2 point to address: " << p2.get() << endl; // Print NULL

Page 259: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

259

cout << "p1 point to address: " << p1.get() << endl; // Print non-NULL address //p2=p1; //Compile error, will not allow copy constructor p2 = move(p1); //use move constructor to transfer ownership instead of using copy constructor cout << "p2 point to address: " << p2.get() << endl; cout << "p1 point to address: " << p1.get() << endl; //null after move its ownership to P2 cout << "p2->number: " << p2->number << endl; p2.reset(); //Deletes the memory. p1.reset(); //Does nothing. Already deleted } int main(int argc, char **argv) { WillNotHasMemoryIssue(); system("PAUSE"); return 0; }

8.14 shared_ptr shared_ptr pointers can share the same object information. When the last shared_ptr is destroyed, you

need to call reset() to destroy all the others.

#include "stdafx.h" #include <iostream> #include <memory> using namespace std; class cA { public: int number; };

Page 260: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

260

int main(int argc, char **argv) { shared_ptr <cA> p1(new cA); p1->number = 100; cout << "p1.get()" << p1.get() << endl; cout << "p1->number: "<<p1->number << endl; cout << "p1.use_count(): " << p1.use_count() << endl; // to see how many shared_ptr points are sharing shared_ptr <cA> p2; cout << "p2.get()" << p2.get() << endl; p2 = p1; cout << "p1.use_count(): " << p1.use_count() << endl; cout << "p2.get()" << p2.get() << endl; cout << "p2->number: " << p2->number << endl; //recheck p1 cout << "P1 and P2 is sharing info, not transfering!" << endl; cout << "p1.get()" << p1.get() << endl; cout << "p1->number: " << p1->number << endl; //release P1, you should see the memory still contain its value because P2 is sharing and not been released it yet. p1.reset(); cout << "p1.get()" << p1.get() << endl; cout << "p2.get()" << p2.get() << endl; //P2 still pointing to it //Now, release P2, memory should clear. So, You have to remember, you need to release all of the shared_ptr p2=nullptr;//or p2.reset(); cout << "p2.get()" << p2.get() << endl; cout << "p1.get()" << p1.get() << endl; system("PAUSE"); return 0; }

Page 261: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

261

8.15 weak_ptr weak_ptr can get into the information of shared_ptr pointer but it it is not sharing ownership with

shared_ptr. You need to convert weak_ptr to shared_ptr to access to that piece of that memory that

shared_ptr is currently own. Make sure to check if the memory that it tried to access is still valid (not

released by the shared_ptr yet).

#include "stdafx.h" #include <iostream> #include <memory> using namespace std; class cA { public: int number; }; int main(int argc, char **argv) { shared_ptr <cA> p1(new cA); p1->number = 100; cout << "p1.get() " << p1.get() << endl; cout << "p1->number: "<<p1->number << endl; cout << "p1.use_count(): " << p1.use_count() << endl; // to see how many shared_ptr points are sharing weak_ptr <cA> p2; p2 = p1; //try to get reference to the piece of memory that shared_ptr own it,. shared_ptr <cA> p3; p3 = p2.lock();//convert weak memory to shared_ptr p3

Page 262: C++ Language Tutorial - storage.googleapis.com · C++ Language Tutorial Mickey Nguyen 3 6.2.14 Old section of Pointer

C++ Language Tutorial Mickey Nguyen

262

if (p3) //make sure the memory still holding the information { p3->number = 200; cout << "p3->number: " << p3->number << endl; } p1.reset();//release the memory p3.reset();//release the memory shared_ptr <cA> p4; p4 = p2.lock();//convert weak memory to shared_ptr p4 if (p4) //make sure the memory still holding the information { p4->number =300; cout << "p4->number: " << p4->number << endl;//should not see this print since p4 should be null } system("PAUSE"); return 0; }