Vous êtes sur la page 1sur 149

Demo

???????????????
1
FunctionX Press
2
Table of Contents
Introduction................................................................................................................. 12

CHAPTER 1: INTRODUCTION TO COMPUTERS ERROR! BOOKMARK


NOT DEFINED.
1.1 Computers: An Overview.........................Error! Bookmark not defined.
1.1.1 Introduction........................................Error! Bookmark not defined.
1.1.2 Introduction to Header Files............Error! Bookmark not defined.
1.1.3 C++ Instructions................................Error! Bookmark not defined.
1.2 C++ Projects ...............................................Error! Bookmark not defined.
1.2.1 Creating a Project..............................Error! Bookmark not defined.
1.2.2 Executing a Program........................Error! Bookmark not defined.
1.2.3 Creating and Executing a Dev-C++ 4 Application...................Error!
Bookmark not defined.
1.2.4 Borland C++ Builder (Console) Applications..... Error! Bookmark
not defined.
1.2.5 Linux C++ (Terminal) Applications.............. Error! Bookmark not
defined.
1.2.6 KDevelop C++ Projects ...................Error! Bookmark not defined.
1.2.7 Microsoft Visual C++ Console ApplicationsError! Bookmark not
defined.
1.2.8 Microsoft Visual C++ .NET Console Applications.................Error!
Bookmark not defined.
1.3 Data Output: An Introduction..................Error! Bookmark not defined.
1.3.1 Using cout...........................................Error! Bookmark not defined.
1.3.2 Comments...........................................Error! Bookmark not defined.
1.3.3 Writing Instructions..........................Error! Bookmark not defined.
1.3.4 Escape Sequences..............................Error! Bookmark not defined.

CHAPTER 2: VARIABLES AND DATA TYPES ...... ERROR! BOOKMARK


NOT DEFINED.
2.1 Variables......................................................Error! Bookmark not defined.
2.1.1 Introduction to Variables .................Error! Bookmark not defined.
2.1.2 C++’ Names .......................................Error! Bookmark not defined.
2.2 Variables and their Data Types ...............Error ! Bookmark not defined.
2.2.1 Introduction........................................Error! Bookmark not defined.
2.2.2 The cin Extractor...............................Error! Bookmark not defined.
2.3 The Numeric Systems ...............................Error! Bookmark not defined.
2.3.1 Introduction........................................Error! Bookmark not defined.
2.3.2 The Binary System............................Error! Bookmark not defined.
2.3.3 The Decimal System.........................Error! Bookmark not defined.
2.3.4 The Hexadecimal System...............Error! Bookmark not defined.
2.3.5 Signed and unsigned.........................Error! Bookmark not defined.
2.4 Representing Numbers ..............................Error! Bookmark not defined.
2.4.1 A Bit ....................................................Error! Bookmark not defined.
2.4.2 A Nibble ..............................................Error! Bookmark not defined.
2.5 A Byte..........................................................Error! Bookmark not defined.
2.5.1 Representing a Byte..........................Error! Bookmark not defined.
2.5.2 Character Variables...........................Error! Bookmark not defined.

© FunctionX, Inc. 3
2.5.3 Escape Sequences..............................Error! Bookmark not defined.
2.5.4 Boolean Variables .............................Error! Bookmark not defined.
2.6 A Word ........................................................Error! Bookmark not defined.
2.6.1 Representing a Word ........................Error! Bookmark not defined.
2.6.2 Short Integers.....................................Error! Bookmark not defined.
2.7 A Double-Word..........................................Error! Bookmark not defined.
2.7.1 Representing a Double-Word..........Error! Bookmark not defined.
2.7.2 Using Integers....................................Error! Bookmark not defined.
2.7.3 Long Integers .....................................Error! Bookmark not defined.
2.7.4 Enumerations.....................................Error! Bookmark not defined.
2.8 Floating-Point Numbers............................Error! Bookmark not defined.
2.8.1 Floating-Point Variables ..................Error! Bookmark not defined.
2.8.2 Double-Precision Numbers .............Error! Bookmark not defined.
2.8.3 Arrays of Characters .........................Error! Bookmark not defined.

CHAPTER 3: TECHNIQUES OF USING VARIABLES ................................13


3.1 Techniques of Using Variables .................................................................... 14
3.1.1 The typedef Type Definition................................................................ 14
3.1.2 Constants ................................................................................................. 15
3.2 Namespaces ..................................................................................................... 17
3.2.1 Creating a namespace............................................................................ 17
3.2.2 Accessing a namespace: The Scope Access Operator..................... 18
3.2.3 The using Keyword................................................................................ 20
3.3 Combining Namespaces ................................................................................ 21
3.3.1 Using Various Namespaces .................................................................. 22
3.3.2 Nesting Namespaces .............................................................................. 26
3.3.3 The std Namespace................................................................................ 29
3.3.4 Introduction to Strings........................................................................... 30

CHAPTER 4: OPERATIONS AND EXPRESSIONS ERROR! BOOKMARK


NOT DEFINED.
4.1 Unary Operators .........................................Error! Bookmark not defined.
4.1.1 Introduction........................................Error! Bookmark not defined.
4.1.2 Unary Operators: The Positive Operator +... Error! Bookmark not
defined.
4.1.3 Unary Operators: The Negative Operator - .. Error! Bookmark not
defined.
4.1.4 Unary Operators: Increment and Decrement ++ and -- ...........Error!
Bookmark not defined.
4.1.5 Unary Operators: The Address Operator &.. Error! Bookmark not
defined.
4.1.6 Unary Operators: The Reference Operator & ..... Error! Bookmark
not defined.
4.1.7 Unary Operators: The sizeof Operator .......... Error! Bookmark not
defined.
4.2 Algebraic Operators ..................................Error! Bookmark not defined.
4.2.1 The Addition......................................Error! Bookmark not defined.
4.2.2 The Subtraction .................................Error! Bookmark not defined.
4.2.3 The Multiplication.............................Error! Bookmark not defined.
4.2.4 The Division.......................................Error! Bookmark not defined.
4.2.5 The Remainder ..................................Error! Bookmark not defined.
4.3 C++ Operators ............................................Error! Bookmark not defined.
4.3.1 Parentheses .........................................Error! Bookmark not defined.
4.3.2 Square Brackets .................................Error! Bookmark not defined.
4.3.3 Curly Brackets ...................................Error! Bookmark not defined.

© FunctionX, Inc. 4
4.3.4 Incrementing a Number....................Error! Bookmark not defined.
4.3.5 Pre and Post-Increment ....................Error! Bookmark not defined.
4.3.6 Decrementing – Pre and Post-Decrementing Error! Bookmark not
defined.
4.3.7 Techniques of Incrementing and Decrementing a Variable ....Error!
Bookmark not defined.
4.4 Bit Manipulations ......................................Error! Bookmark not defined.
4.4.1 Introduction........................................Error! Bookmark not defined.
4.4.2 Bits Operators: The Bitwise NOT Operator ~..... Error! Bookmark
not defined.
4.4.3 Comparing Bits: The Bitwise AND Operator &. Error! Bookmark
not defined.
4.4.4 Comparing Bits: The Bitwise OR Operator | Error! Bookmark not
defined.
4.4.5 Comparing Bits: The Bitwise-Exclusive XOR Operator ^.....Error!
Bookmark not defined.
4.4.6 Bit Shift Operators: The Left Shift << .......... Error! Bookmark not
defined.
4.4.7 Bit Shift Operators: The Right Shift >>........ Error! Bookmark not
defined.
4.5 Variable Casting: An Introduction..........Error! Bookmark not defined.
4.5.1 C Casting ............................................Error! Bookmark not defined.
4.5.2 Operator Precedence and DirectionError! Bookmark not defined.

CHAPTER 5: INTRODUCTION TO FUNCTIONS.. ERROR! BOOKMARK


NOT DEFINED.
5.1 C++’ Functions...........................................Error! Bookmark not defined.
5.1.1 Function Definition...........................Error! Bookmark not defined.
5.1.2 Calling Functions..............................Error! Bookmark not defined.
5.2 Using Functions.........................................Error! Bookmark not defined.
5.2.1 Return Value ......................................Error! Bookmark not defined.
5.2.2 void Functions...................................Error! Bookmark not defined.
5.3 Functions and Arguments.........................Error! Bookmark not defined.
5.3.1 Arguments – Parameters ..................Error! Bookmark not defined.
5.3.2 Passing Arguments by Value ..........Error! Book mark not defined.
5.3.3 Passing Arguments by Reference...Error! Bookmark not defined.
5.3.4 Default Arguments............................Error! Bookmark not defined.
5.3.5 Function Overloading.......................Error! Bookmark not defined.

CHAPTER 6: EXPLORING FUNCTIONS ........ERROR! BOOKMARK NOT


DEFINED.
6.1 Functions and their Arguments ...............Error! Bookmark not defined.
6.1.1 Constant Arguments .........................Error! Bookmark not defined.
6.1.2 Passing Arguments by Constant Reference.. Error! Bookmark not
defined.
6.2 Techniques of Using Functions...............Error! Bookmark not defined.
6.2.1 Inline Functions.................................Error! Bookmark not defined.
6.2.2 Static Variables..................................Error! Bookmark not defined.
6.3 C++ and Files .............................................Error! Bookmark not defined.
6.3.1 Header Files .......................................Error! Bookmark not defined.
6.3.2 File Preprocessors .............................Error! Bookmark not defined.
6.3.3 Source Files ........................................Error! Bookmark not defined.
6.3.4 Source Files ........................................Error! Bookmark not defined.
6.4 Functions and Namespaces ......................Error! Bookmark not defined.
6.4.1 Functions Local Definition..............Error! Bookmark not defined.

© FunctionX, Inc. 5
6.4.2 Global Definitions.............................Error! Bookmark not defined.
6.4.3 Namespaces and External Functions............. Error! Bookmark not
defined.
6.5 C++ Built-in Functions.............................Error! Bookmark not defined.
6.5.1 Asserting a Value or an Expression............... Error! Bookmark not
defined.
6.5.2 Mathematic Functions......................Error! Bookmark not defined.

CHAPTER 7: CONDITIONAL STATEMENTS ........ ERROR! BOOKMARK


NOT DEFINED.
7.1 Logical Operators ......................................Error! Bookmark not defined.
7.1.1 Introduction........................................Error! Bookmark not defined.
7.1.2 The Equality Operator == ................Error! Bookmark not defined.
7.1.3 The Logical Not Operator !.............Error! Bookmark not defined.
7.1.4 For Inequality !=................................Error! Bookmark not defined.
7.1.5 A Lower Value <...............................Error! Bookmark not defined.
7.1.6 Combining Equality and Lower Value <=.... Error! Bookmark not
defined.
7.1.7 A Greater Value > .............................Error! Bookmark not defined.
7.1.8 Greater or Equal Value >=...............Error! Bookmark not defined.
7.2 The Conditional Statements .....................Error! Bookmark not defined.
7.2.1 Introduction to Conditional Statements......... Error! Bookmark not
defined.
7.2.2 if a Condition is True........................Error! Bookmark not defined.
7.2.3 Using the Logical Not ......................Error! Bookmark not defined.
7.2.4 Otherwise: if…else...........................Error! Bookmark not defined.
7.2.5 The Conditional Operator (?:).........Error! Bookmark not defined.
7.2.6 The if…else if and if…else if…else Statements. Error! Bookmark
not defined.
7.2.7 The switch Statement .......................Error! Bookmark not defined.
7.3 Counting and Looping ..............................Error! Bookmark not defined.
7.3.1 The while Statement .........................Error! Bookmark not defined.
7.3.2 The do...while Statement .................Error! Bookmark not defined.
7.3.3 The for Statement..............................Error! Bookmark not defined.

CHAPTER 8: CONSTRUCTING EXPRESSIONS...........................................35


8.1 Combining Statements ................................................................................... 36
8.1.1 Introduction............................................................................................. 36
8.1.2 Nesting Conditions................................................................................. 36
8.1.3 The break Statement .............................................................................. 41
8.1.4 The continue Statement......................................................................... 46
8.1.5 The goto Statement................................................................................ 47
8.2 Logical Conjunction and Disjunction.......................................................... 47
8.2.1 Using the Logical Not ........................................................................... 48
8.2.2 Logical Conjunction: AND .................................................................. 51
8.2.3 Logical Disjunction: OR....................................................................... 53
8.3 Conditional Statements and Functions........................................................ 57
8.3.1 Using Conditions in Functions............................................................. 58
8.3.2 Conditional Returns............................................................................... 62

CHAPTER 9: ARRAYS ......................ERROR! BOOKMARK NOT DEF INED.


9.1 Fundamentals of Arrays............................Error! Bookmark not defined.
9.1.1 Introduction to Arrays ......................Error! Bookmark not defined.
9.1.2 Declaring Arrays ...............................Error! Bookmark not defined.

© FunctionX, Inc. 6
9.1.3 Initializing an Array..........................Error! Bookmark not defined.
9.1.4 Processing an Array..........................Error! Bookmark not defined.
9.2 Operations on Arrays................................Error! Bookmark not defined.
9.2.1 The Size of an Array.........................Error! Bookmark not defined.
9.2.2 Algebraic Operations on Array Members ..... Error! Bookmark not
defined.
9.2.3 Requesting Array Members.............Error! Bookmark not defined.
9.2.4 Arrays and Functions........................Error! Bookmark not defined.
9.3 Multidimensional Arrays..........................Error! Bookmark not defined.
9.3.1 Introduction........................................Error! Bookmark not defined.
9.3.2 Two-Dimensional Arrays ................Error! Bookmark not defined.
9.3.3 Initializing a Two-Dimensional Array .......... Error! Bookmark not
defined.
9.3.4 Multidimensional Arrays.................Error! Bookmark not defined.

CHAPTER 10: POINTERS ................ERROR! BOOKMARK NOT DEFINED.


10.1 Defining Pointers .....................................Error! Bookmark not defined.
10.1.1 ..Introduction........................................Error! Book mark not defined.
10.1.2 ..Definition ...........................................Error! Bookmark not defined.
10.1.3 ..Initializing a Pointer.........................Error! Bookmark not defined.
10.1.4 ..Requesting Pointers Values.............Error! Bookmark not defined.
10.1.5 ..Operations on Pointers.....................Error! Bookmark not defined.
10.1.6 ..Why Use Pointers?...........................Error! Bookmark not defined.
10.2 Pointers and Memory Management......Error! Bookmark not defined.
10.2.1 ..Introduction........................................Error! Bookmark not defined.
10.2.2 ..The new Operator .............................Error! Bookmark not defined.
10.2.3 ..The delete Operator..........................Error! Bookmark not defined.
10.3 Pointers and Functions............................Error! Bookmark not defined.
10.3.1 ..Introduction........................................Error! Bookmark not defined.
10.3.2 ..Passing Arguments as Pointers.......Error! Bookmark not defined.

CHAPTER 11: STRINGS, AN OVERVIEW .....ERROR! BOOKMARK NOT


DEFINED.
11.1 Arrays of Characters................................Error! Bookmark not defined.
11.1.1 ..Introduction........................................Error! Bookmark not defined.
11.1.2 ..Declaring and Initializing an Array of Characters ...................Error!
Bookmark not defined.
11.1.3 ..Requesting an Array of Characters Error! Bookmark not defined.
11.2 Arrays of Characters and Pointers ........Error! Bookmark not defined.
11.2.1 ..Declaration of an Array of Characters .......... Error! Bookmark not
defined.
11.2.2 ..Dynamic Arrays of Characters .......Error! Bookmark not defined.
11.2.3 ..Passing and Array of Characters ....Error! Bookmark not defined.
11.2.4 ..Returning an array of Characters ...Error! Bookmark not defined.
11.3 Multidimensional Arrays of Characters ............... Error! Bookmark not
defined.
11.3.1 ..Double-Dimensional Arrays Declaration ..... Error! Bookmark not
defined.
11.3.2 ..Double-Dimensional Arrays and Functions. Error! Bookmark not
defined.
11.4 Introduction to Strings............................Error! Bookmark not defined.
11.4.1 ..Defining a String...............................Error! Bookmark not defined.
11.4.2 ..String Manipulation Functions.......Error! Bookmark not defined.
11.4.3 ..The Length of a String .....................Error! Bookmark not defined.
11.4.4 ..The strcat() Function........................Error! Bookmark not defined.

© FunctionX, Inc. 7
11.4.5 ..The strncat() Function......................Error! Bookmark not defined.
11.4.6 ..The strcpy Functtion.........................Error! Bookmark not defined.
11.4.7 ..The strncpy() Function.....................Error! Bookmark not defined.
11.4.8 ..The strdup() Function.......................Error! Bookmark not defined.
11.5 Comparing Strings...................................Error! Bookmark not defined.
11.5.1 ..The strcmp() Function......................Error! Bookmark not defined.
11.5.2 ..The strncmp() Function ...................Error! Bookmark not defined.
11.5.3 ..The stricmp() Function ....................Error! Bookmark not defined.
11.5.4 ..The strnicmp() Function ..................Error! Bookmark not defined.
11.6 Working With Individual Characters ...Error! Bookmark not defined.
11.6.1 ..The strchr() Function........................Error! Bookmark not defined.
11.6.2 ..The strrchr() Functionn....................Error! Bookmark not defined.
11.7 Working With Sub-St rings.....................Error! Bookmark not defined.
11.7.1 ..The strstr() Function.........................Error! Bookmark not defined.
11.8 Working With Character Cases.............Error! Bookmark not defined.
11.8.1 ..The strlwr() Function .......................Error! Bookmark not defined.
11.8.2 ..The strupr() Function .......................Error! Bookmark not defined.
11.9 Formatting Strings...................................Error! Bookmark not defined.
11.9.1 ..The sprintf() Function......................Error! Bookmark not defined.

CHAPTER 12: INTRODUCTION TO CLASSES .............................................69


12.1 Classes: An Introduction............................................................................. 70
12.1.1 ..Introduction to Classes.......................................................................... 70
12.1.2 ..Creating a Class...................................................................................... 72
12.1.3 ..Accessing a Class................................................................................... 74
12.1.4 ..Declaring a Class................................................................................... 75
12.1.5 ..Techniques of Initializing a Class....................................................... 84
12.2 Classes and Methods.................................................................................... 86
12.2.1 ..Declaring Methods................................................................................ 86
12.2.2 ..Implementing Methods Locally .......................................................... 87
12.2.3 ..Implementing Methods Globally ........................................................ 90
12.2.4 ..Inline Methods........................................................................................ 93
12.2.5 ..Class Members Interactions................................................................. 95

CHAPTER 13: DATA INPUT/OUTPUT ............ERROR! BOOKMARK NOT


DEFINED.
13.1 Displaying Data........................................Error! Bookmark not defined.
13.1.1 ..General Display Techniques With cout........ Error! Bookmark not
defined.
13.1.2 ..The cout.write() Method..................Error! Bookmark not defined.
13.1.3 ..Data Display Functions: puts().......Error! Bookmark not defined.
13.1.4 ..The printf() Function........................Error! Bookmark not defined.
13.2 Controlling and Formatting Data Output............. Error! Bookmark not
defined.
13.2.1 ..The Width of Data Display .............Error! Bookmark not defined.
13.2.2 ..Filling the Empty Space...................Error! Bookmark not defined.
13.2.3 ..The dec, hex, and oct Operators .....Error! Bookmark not defined.
13.2.4 ..The uppercase Attribute...................Error! Bookmark not defined.
13.2.5 ..The setiosflags() Function...............Error! Bookmark not defined.
13.2.6 ..The resetiosflags() Function............Error! Bookmark not defined.
13.2.7 ..Formatting Floating-Point Numbers.............. Error! Bookmark not
defined.
13.2.8 ..C How to Display Data....................Error! Bookmark not defined.
13.3 Data Input..................................................Error! Bookmark not defined.
13.3.1 ..Using cin ............................................Error! Bookmark not defined.

© FunctionX, Inc. 8
13.3.2 ..The gets() Function...........................Error! Bookmark not defined.
13.3.3 ..C How to Input Data ........................Error! Bookmark not defined.
13.4 A Character: Its Case, Value, and Meaning........ Error! Bookmark not
defined.
13.4.1 ..Character Cases.................................Error! Bookmark not defined.
13.4.2 ..Validating a Character .....................Error! Bookmark not defined.
13.5 Ending a Program....................................Error! Bookmark not defined.
13.5.1 ..Exiting a Program.............................Error! Bookmark not defined.
13.5.2 ..Aborting a Program..........................Error! Bookmark not defined.
13.5.3 ..Terminating a Program....................Error! Bookmark not defined.

CHAPTER 14: EXCEPTIO N HANDLING........ERROR! BOOKMARK NOT


DEFINED.
14.1 Exceptions.................................................Error! Bookmark not defined.
14.1.1 ..Introduction........................................Error! Bookmark not defined.
14.1.2 ..Exceptional Behaviors .....................Error! Bookmark not defined.
14.1.3 ..Facing an Exception .........................Error! Bookmark not defined.
14.2 Predicting Exceptions..............................Error! Bookmark not defined.
14.2.1 ..Local Exceptions...............................Error! Bookmark not defined.
14.2.2 ..Catching Multiple Exceptions........Error! Bookmark not defined.
14.2.3 ..Nesting Exceptions...........................Error! Bookmark not defined.
14.2.4 ..Exceptions and Functions................Error! Bookmark not defined.
14.2.5 ..Obviating the Throwing of Exceptions ......... Error! Bookmark not
defined.

CHAPTER 15: CREATING CLASSES ...............ERROR! BOOKMARK NOT


DEFINED.
15.1 Tuning Objects .........................................Error! Bookmark not defined.
15.1.1 ..Constant Arguments and Classes ...Error! Bookmark not defined.
15.1.2 ..Constant Methods .............................Error! Bookmark not defined.
15.1.3 ..Private Methods ................................Error! Bookmark not defined.
15.1.4 ..Static Member Variables .................Error! Bookmark not defined.
15.1.5 ..Static Methods...................................Error! Bookmark not defined.
15.2 An Object and its Implementation ........Error! Bookmark not defined.
15.2.1 ..A Class' Header File .........................Error! Bookmark not defined.
15.2.2 ..Class Source Code............................Error! Bookmark not defined.
15.3 Get and Set Methods ...............................Error! Bookmark not defined.
15.3.1 ..Class Method Readers......................Error! Bookmark not defined.
15.3.2 ..Class Method Writers.......................Error! Bookmark not defined.

CHAPTER 16: VARIANCES OF CLASSES .....ERROR! BOOKMARK NOT


DEFINED.
16.1 Namespaces and Classes ........................Error! Bookmark not defined.
16.1.1 ..Introduction........................................Error! Bookmark not defined.
16.1.2 ..Namespaces and C++ Files .............Error! Bookmark not defined.
16.1.3 ..A Multiple Body Namespace..........Error! Bookmark not defined.
16.2 Structures...................................................Error! Bookmark not defined.
16.2.1 ..Creating a Structure ..........................Error! Bookmark not defined.
16.2.2 ..Accessing and Initializing a Structure Member.. Error! Bookmark
not defined.
16.2.3 ..Structures and Methods ...................Error! Bookmark not defined.
16.2.4 ..Structure's Explicit Level of Access.............. Error ! Bookmark not
defined.
16.3 Unions........................................................Error! Bookmark not defined.

© FunctionX, Inc. 9
16.3.1 ..Defining a Union...............................Error! Bookmark not defined.
16.3.2 ..Using a Union....................................Error! Bookmark not defined.
16.4 Variables Scope and Lifetime ................Error! Bookmark not defined.
16.4.1 ..Condition Scope................................Error! Bookmark not defined.
16.4.2 ..Block Scope.......................................Error! Bookmark not defined.
16.4.3 ..Function Scope..................................Error! Bookmark not defined.
16.4.4 ..File Scope...........................................Error! Bookmark not defined.

CHAPTER 17: CLASS CONSTRUCTION AND DESTRUCTION. ERROR!


BOOKMARK NOT DEFINED.
17.1 Constructors ..............................................Error! Bookmark not defined.
17.1.1 ..Method Initializer.............................Error! Bookmark not defined.
17.1.2 ..Default Constructor..........................Error! Bookmark not defined.
17.1.3 ..The Constructor Initializer ..............Error! Bookmark not defined.
17.1.4 ..Constructor Overloading .................Error! Bookmark not defined.
17.1.5 ..Techniques of Initializing With a Constructor.... Error! Bookmark
not defined.
17.1.6 ..Constructors, Methods, and Default Values. Error! Bookmark not
defined.
17.2 The Copy Constructor.............................Error! Bookmark not defined.
17.2.1 ..Copying an Object ............................Error! Bookmark not defined.
17.2.2 ..Using a Copy Constructor...............Error! Bookmark not defined.
17.3 Destructors ................................................Error! Bookmark not defined.
17.3.1 ..Introduction........................................Error! Bookmark not defined.
17.3.2 ..Creating a Destructor.......................Error! Bookmark not defined.

CHAPTER 18: OBJECTS AND THEIR ENVIRONMENT...........................97


18.1 Classes and Functions.................................................................................. 98
18.1.1 ..Introduction............................................................................................. 98
18.1.2 ..Passing an Object as an Argument....................................................105
18.1.3 ..Returning an Object.............................................................................107
18.1.4 ..Passing an Object by Reference ........................................................110
18.1.5 ..Passing a Constant Object..................................................................112
18.2 Classes and Pointers...................................................................................113
18.2.1 ..An Object Pointer as an Argument...................................................113
18.2.2 ..Declaring an Object as a Pointer.......................................................117
18.2.3 ..The Size of an Object..........................................................................120
18.3 Object and Self-Management ...................................................................121
18.3.1 ..Self Returning an Object ....................................................................121
18.3.2 ..The this Pointer....................................................................................127

CHAPTER 19: COMBINATIONS OF OBJECTS ..... ERROR! BOOKMARK


NOT DEFINED.
19.1 Arrays and Classes...................................Error! Bookmark not defined.
19.1.1 ..Declaring an Array of Objects........Error! Bookmark not defined.
19.1.2 ..Accessing Members of an Array of Objects Error! Bookmark not
defined.
19.1.3 ..Arrays of Objects and Functions....Error! Bookmark not defined.
19.1.4 ..Arrays, Pointers, and Classes..........Error! Bookmark not defined.
19.2 Arrays of Characters and Classes..........Error! Bookmark not defined.
19.2.1 ..Introduction........................................Error! Bookmark not defined.
19.2.2 ..Declaring Member Arrays...............Error! Bookmark not defined.
19.3 Composing an Object..............................Error! Bookmark not defined.

© FunctionX, Inc. 10
19.3.1 ..Using an Enumerator as an Object Member Error! Bookmark not
defined.
19.3.2 ..Mixing Objects..................................Error! Bookmark not defined.
19.3.3 ..An Object as a Member Variable ...Error! Bookmark not defined.
19.4 Functions, Classes, and Friendship.......Error! Bookmark not defined.
19.4.1 ..Friend Functions of a Class.............Error! Bookmark not defined.
19.4.2 ..A Class as a Friend ...........................Error! Bookmark not defined.

CHAPTER 20: POLYMORPHISM AND ABSTRACTION............... ERROR!


BOOKMARK NOT DEFINED.
20.1 Inheritance.................................................Error! Bookmark not defined.
20.1.1 ..Creating the Parent Object ..............Error! Bookmark not defined.
20.1.2 ..Inheriting an Object..........................Error! Bookmark not defined.
20.1.3 ..The protected Access Level............Error! Bookmark not defined.
20.1.4 ..Multiple Inheritance .........................Error! Bookmark not defined.
20.1.5 ..Nesting Classes .................................Error! Bookmark not defined.
20.1.6 ..Namespaces and Inheritance...........Error! Bookmark not defined.
20.2 Polymorphism..........................................Error! Bookmark not defined.
20.2.1 ..Introduction........................................Error! Bookmark not defined.
20.2.2 ..Virtual Methods................................Error! Bookmark not defined.
20.2.3 ..Virtual Destructors ...........................Error! Bookmark not defined.
20.3 Abstract Classes.......................................Error! Bookmark not defined.
20.3.1 ..Introduction........................................Error! Bookmark not defined.
20.3.2 ..Creating an Abstract Class..............Error! Bookmark not defined.

CHAPTER 21: OPERATOR OVERLOADINGERROR! BOOKMARK NOT


DEFINED.
21.1 Overloading an Operator........................Error! Bookmark not defined.
21.1.1 ..Introduction........................................Error! Bookmark not defined.
21.1.2 ..Defaults Methods: A Review..........Error! Bookmark not defined.
21.1.3 ..Overloading an Operator.................Error! Bookmark not defined.
21.2 Overloading Algebraic Operators .........Error! Bookmark not defined.
21.2.1 ..The Assignment Operator ...............Error! Bookmark not defined.
21.2.2 ..Overloading the Arithmetic Operators .......... Error! Bookmark not
defined.
21.2.3 ..Adding a Constant to an Object .....Error! Bookmark not de fined.
21.2.4 ..The Sum Assignment Operator......Error! Bookmark not defined.
21.2.5 ..Boolean Operators ............................Error! Bookmark not defined.
21.3 The Stream Operators .............................Error! Bookmark not defined.
21.3.1 ..The Stream Output Operator...........Error! Bookmark not defined.
21.3.2 ..The Stream Input Operator..............Error! Bookmark not defined.

APPENDIX................................................................................................................. 131
Appendix A: Clearing the Screen ......................Error! Bookmark not defined.
Using the system() Function .........................Error! Bookmark not defined.
Borland's Function of Clearing the Screen .Error! Bookmark not defined.
Appendix B: Operator Precedence.....................Error! Bookmark not defined.
Appendix C: Relationships on the Numeric Systems ........................................132
Converting A Byte From Binary to Decimal................................................132
Converting Any Number From Binary To Decimal....................................132
Converting A Byte From Binary to Hexadecimal........................................133
Converting Any Number Fro m Binary to Hexadecimal.............................133
Converting A Byte From Decimal to Binary ................................................134
Converting Any Number From Decimal to Binary ......................................134

© FunctionX, Inc. 11
Converting A Byte From Decimal to Hexadecimal.....................................138
Converting Any Number From Decimal to Hexadecimal..........................138
Converting a Byte From Hexadecimal to Binary .........................................138
Converting Any Number From Hexadecimal to Binary .............................139
Converting a Byte From Hexadecimal to Decimal......................................139
Converting Any Number From Hexadecimal to Decimal..........................140

INDEX ......................................................................................................................... 142

© FunctionX, Inc. 12
C++ Fundamentals Introduction

Introduction

This book assumes no prior knowledge of any programming language from you. To use
this book, you must have installed a C++ compiler on your computer in order to follow
the programs in this book. If you are using a Linux or Unix operating systems, everything
should have been installed already as they ship with C and C++ compilers. If you are
using Linux, we recommend you install or make sure that KDevelop is installed or any
other visual programming environment that supports the C++ language. This would make
your programming a little easier. Alternatively, you can get Dev-C++. Microsoft
Windows does not ship with any C++ compiler. You must explicitly make sure that you
have installed a C++ environment. The cheapest you can get is Dev-C++ from the
http://www.bloodshed.com web site.

In this book, Bcb means Borland C++ Builder. MSVC means Microsoft Visual C++.

© FunctionX, Inc. 13
C++ Fundamentals Chapter 3 Techniques of Using Variables

Chapter 3:
Techniques of Using Variables

? Unary Operators

? Algebraic Operators

? C++ Operators

? Bit Manipulations

? Variable Casting: An Introduction

© FunctionX, Inc. 14
C++ Fundamentals Chapter 3 Techniques of Using Variables

3.1 Techniques of Using Variables

3.1.1 The typedef Type Definition


Some of the variables we have used so far and some others we will learn further with
arrays, pointers, and objects can be simplified and reduced to a new one-word identifier.
C++ allows you to define a new variable using typedef. Indeed, typedef is not a new or
other data type. It provides a technique of redefining or renaming any of the known data
types. The syntax of using the typedef is:

typedef DataType NewName;

The typedef keyword is required to let the compiler know that you are creating a new
identifier. The DataType is any of those we have learned so far. It could be an int, an
unsigned int, a char, a double, etc. An example of declaring a typedef is:

typedef int NumberOfStudents;

In this case, NumberOfStudents is just a new name for an int. It can be used as a new
identifier exactly as if you were using an int. Here is an example that redefines an int data
type:

#include <iostream.h>

int main()
{
typedef int NumberOfStudents;

NumberOfStudents Grade1, Grade2;

cout << "Enter the number of students.\n";


cout << "Grade 1: ";
cin >> Grade1;
cout << "Grade 2: ";
cin >> Grade2;

cout << "\nNumber of students:";


cout << "\n1st Grade: " << Grade1;
cout << "\n2nd Grade: " << Grade2 << "\n\n";

return 0;
}

Here are examples of creating new identifiers using typedef:

typedef unsigned int UINT;


typedef unsigned char UCHAR;
typedef unsigned long ULONG;
typedef long double LONGDOUBLE;

© FunctionX, Inc. 15
C++ Fundamentals Chapter 3 Techniques of Using Variables

3.1.2 Constants
A constant is a value that does not change. There are various categories of constants you
will be using in your programs. To make their management easier, these constant values
have been categorized and defined in particular libraries. Throughout this book, you will
be using them.

The algebraic numbers you have been using all the time are constants because they never
change. Examples of constant numbers are 12, 0, 1505, or 88146. Therefore, any number
you can think of is a constant.

Every letter of the alphabet is a constant and is always the same. Examples of constant
letters are d, n, c.

Some characters on your keyboard represent symbols that are neither letters nor digits.
These are constants too. Examples are #, &, |, !.

Some values would be constant by default, but their constancy sometimes depends on the
programmer. For example, one programmer can define a const PI as 3.14; another
programmer can decide that the constant PI would be 3.14159. Therefore, you will be
defining your own constant values as you see fit for the goal you are trying to achieve.

There are two main techniques you use to display a constant value in C++. To simply
display it using the cout << extractor, you can use its value on the right side of the <<
symbols. You can also define it first using an appropriate name, and then using that name
to display the constant.

#include <iostream.h>

int main()
{
cout << 28;

cout << "\nStudent Age: " << 14;


cout << "\n\n";
return 0;
}

The safest technique of using a constant is to give it a name. This allows you to manage it
from one standpoint. For example, if you plan to use a number such as 3.14 that
represents PI, you can simply use the constant 3.14. Imagine you want to use 3.14 in
various sections of the program such as in different functions. If you decide to change the
number from 3.14 to 3.14159 or another value, you would have to find every mention of
3.14; this can lead to a programming error. The alternative is to declare a variable and
assign it the desired value. The new and defined value is called a constant.

There are two main techniques used to create constant values. The old way, which was
used with the C language and widely used in documentation and help files consists of
using the define keyword. The syntax of creating a constant using the define keyword is:

#define ConstantName ConstantValue

The # symbol and the define word are required; they inform the compiler that the
following name represents a constant. The ConstantName represents a valid name for the
desired constant; the name follows the same rules we learned for defining names in C++.
The ConstantValue can be a character, an integer, a floating-point value, or an

© FunctionX, Inc. 16
C++ Fundamentals Chapter 3 Techniques of Using Variables

expression. If the constant value is an integer or a floating-point value, you can type it. If
the value is a character, include it between single-quotes. The definition of the constant
does not end with a semi -colon. Examples of declaring constants are:

#define AGE 12 // AGE represents the constant integer 12


#define ANSWER ‘y’
#define MAXSTUDENTS 35
#define PI 3.14159 // PI represents 3.14159

Another technique of creating a constant is by using the const keyword. The syntax of
using the const keyword is:

const ConstantName = ConstantValue;

Or

const DataType ConstantName = Value;

The const keyword is required to inform the compiler that you are creating a constant.
The ConstantName specifies the name of the constant value; it follows the rules we have
applied for the names of variables. The DataType, although optional, is used to let the
compiler know what kind of variable it is. If you do not specify a data type, the compiler
would assume that the constant is an integer. Therefore, make it a habit to always specify
the data type when creating a constant using the const keyword. The data type can be any
of those we have learned. Use the assignment operator to assign the desired constant to
the name.

Examples of creating constants with the const keyword are:

const float PI = 3.14159;


const unsigned int MaxStudents = 42;
const string Country = “New Zealand”;
const double Distance = 1678212;

Another category of constants are those that are part of the C++ compiler. Those
constants have names they can be recognized with. For example, the minimum value of
the short integer is SHRT_MIN. In the same way, the maximum short integer is identified
by SHRT_MAX. You can use either of these constants as follows:

#include <iostream.h>
#include <limits.h>

int main()
{
cout << "The minimum signed character: " << SCHAR_MIN << "\n";
cout << "The maximum signed character: " << SCHAR_MAX << "\n";
cout << "The minimum short integer is: " << SHRT_MIN << "\n";
cout << "The maximum short integer is: " << SHRT_MAX << "\n\n";
return 0;
}

According to the C++ Standard, the integral constants are defined in the climits library
but they can be defined as one compiler chooses to. For example, in Borland C++
Builder, they are in the _lim.h library. In the KDevelop and Microsoft C++ compilers
they are in the limits.h file.

© FunctionX, Inc. 17
C++ Fundamentals Chapter 3 Techniques of Using Variables

The integer constants defined in the climits library are:

CHAR_BIT INT_MAX LONG_MAX SCHAR_MAX SHRT_MAX


CHAR_MAX INT_MIN LONG_MIN SCHAR_MIN SHRT_MIN
CHAR_MIN UINT_MAX ULONG_MAX UCHAR_MAX USHRT_MAX
MB_LEN_MAX

In the same way, C++ provides constant double-precision numbers in the cfloat library.
These constants are:

DBL_DIG FLT_DIG LDBL_DIG


DBL_EPSILON FLT_EPSILON LDBL_EPSILON
DBL_MANT_DIG FLT _MANT_DIG LDBL_MANT_DIG
DBL_MAX FLT _MAX LDBL_MAX
DBL_MAX_10_EXP FLT _MAX_10_EXP LDBL_MAX_10_EXP
DBL_MAX_EXP FLT _MAX_EXP LDBL_MAX_EXP
DBL_MIN FLT _MIN LDBL_MIN
DBL_MIN_10_EXP FLT _MIN_10_EXP LDBL_MIN_10_EXP
DBL_MIN_EXP FLT _MIN_EXP LDBL_MIN_EXP
FLT_RADIX

The C++ Standard also defines a constant as NULL. This constant is used to designate
that a pointer does not hold a valid value. The NULL constant is defined in the cstddef
library.

3.2 Namespaces
A namespace is a section of code, delimited and referred to using a specific name. A
namespace is created to set apart a portion of code with the goal to reduce, otherwise
eliminate, confusion. This is done by giving a common name to that portion of code so
that, when referring to it, only entities that are part of that section would be referred to.

A namespace is not a variable. It is not a function. It is not a class. It is only a technique


of naming a section of code and referring to that section of code with a name.

3.2.1 Creating a namespace

The syntax of creating a namespace is:

namespace Name { Body }

The creation of a namespace starts with the (required) namespace keyword followed by a
name that would identify the section of code. The name follows the rules we have been
applying to C++ names. A namespace contains a body; this is where the entities that are
part of the namespace would be declared or defined. The body of the namespace starts
with an opening curly bracket “{” and ends with a closing curly bracket “}”. Here is an
example of a simple namespace:

namespace Mine
{
int a;
}

© FunctionX, Inc. 18
C++ Fundamentals Chapter 3 Techniques of Using Variables

The entities included in the body of a namespace are referred to as its memb ers.

3.2.2 Accessing a namespace: The Scope Access Operator


To access a member of a namespace, there are various techniques you can use. The
scope access operator “::” is used to access the members of a namespace. To do this, type
the name of the namespace, followed by the scope access operator “::”, followed by the
member you are want to access. Only the members of a particular namespace are
available when using its name. For example, to access the member “a” of the Mine
namespace above, you can write:

Mine::a;

Once you have access to a namespace member, you can initialize it or display its value
using the cout extractor operator. Here is an example:

#include <iostream.h>

namespace Mine
{
int a;
}

int main()
{
Mine::a = 140;

cout << "Value of a = " << Mine::a;


return 0;
}

This would produce:

Value of a = 140

When creating a namespace, you can add as many members as you see fit. When
necessary, you can use the scope access operator to call anyone of them as needed. Here
is an example:

#include <iostream.h>

namespace InterestAndDiscount
{
double Principal;
double Rate;
int Time;
}

int main()
{
InterestAndDiscount::Principal = 3250;
InterestAndDiscount::Rate = 0.1225; // =12.25%
InterestAndDiscount::Time = 2;

cout << "Loan Processing";


cout << "\nPrincipal: $" << InterestAndDiscount::Principal;

© FunctionX, Inc. 19
C++ Fundamentals Chapter 3 Techniques of Using Variables

cout << "\nRate: " << InterestAndDiscount::Rate*100 << "%";


cout << "\nTime: " << InterestAndDiscount::Time << " years";

return 0;
}

You can also request the values of the members of a namespace from the user.
Remember to use the scope access operator whenever you need to access the member of
a namespace. Here is an example:

#include <iost ream.h>

namespace InterestAndDiscount
{
double Principal;
double Rate;
int Time;
}

int main()
{
cout << "Interest and Discount \n";
cout << "Principal: $";
cin >> InterestAndDiscount::Principal;
cout << "Rate (example 8.75): ";
cin >> InterestAndDiscount::Rate;
cout << "Number of Years: ";
cin >> InterestAndDiscount::Time;

cout << "\nLoan Processing";


cout << "\nPrincipal: $" << InterestAndDiscount::Principal;
cout << "\nRate: " << InterestAndDiscount::Rate << "%";
cout << "\nTime: " << InterestAndDiscount::Time << " years";

return 0;
}

Here is an example of running the program:

Interest and Discount


Principal: $12500
Rate (example 8.75): 7.25
Number of Years: 10

Interest Calculation
Principal: $12500.00
Rate: 7.25%
Time: 10 years

The member variable of a namespace can also mixed with a variable that is locally
declared in a function. All you have to do is make sure that you qualify the member of
the namespace so the compiler would be able to locate it. Here is an example:

#include <iostream.h>

namespace InterestAndDiscount
{

© FunctionX, Inc. 20
C++ Fundamentals Chapter 3 Techniques of Using Variables

double Principal;
double Rate;
int Time;
}

int main()
{
double Interest;
double MaturityValue;

cout << "Interest and Discount \n";


cout << "Principal: $";
cin >> InterestAndDiscount::Principal;
cout << "Rate (example 8.75): ";
cin >> InterestAndDiscount::Rate;
cout << "Number of Years: ";
cin >> InterestAndDiscount::Time;

Interest = InterestAndDiscount::Principal *
(InterestAndDiscount::Rate/100) *
InterestAndDiscount::Time;
MaturityValue = InterestAndDiscount::Principal + Interest;

cout << "\nLoan Processing";


cout << "\nPrincipal: $" << InterestAndDiscount::Principal;
cout << "\nRate: " << InterestAndDiscount::Rate << "%";
cout << "\nTime: " << InterestAndDiscount::Time << " years";
cout << "\nInterest: $" << Interest;
cout << "\nMaturity Value: $" << MaturityValue << "\n\n";

return 0;
}

3.2.3 The using Keyword


The scope access operator “::”provides a safe mechanism to access the members of a
namespace. If the namespace is very long and the application needs constant access, this
might be a little cumbersome. Another technique used to access the members of a
namespace involves using two keywords: using and namespace.

To call a namespace, on the section of the program where you need to access the
members, type:

using namespace NamespaceName;

Both the using and the namespace keywords are required by the compiler. The
NamespaceName represents the name of the namespace whose member(s) you want to
access. Using this technique, the above program can be written:

#include <iostream.h>

namespace InterestAndDiscount
{
double Principal;
double Rate;
int Time;
}

© FunctionX, Inc. 21
C++ Fundamentals Chapter 3 Techniques of Using Variables

int main()
{
using namespace InterestAndDiscount;
double Interest;
double MaturityValue;

cout << "Interest and Discount \n";


cout << "Principal: $";
cin >> Principal;
cout << "Rate (example 8.75): ";
cin >> Rate;
cout << "Number of Years: ";
cin >> Time;

Interest = Principal * (Rate/100) * Time;


MaturityValue = Principal + Interest;

cout << "\nLoan Processing";


cout << "\nPrincipal: $" << Principal;
cout << "\nRate: " << Rate << "%";
cout << "\nTime: " << Time << " years";
cout << "\nInterest: $" << Interest;
cout << "\nMaturity Value: $" << MaturityValue << "\n\n";

return 0;
}

Here is an example of a result:

Interest and Discount


Principal: $2500
Rate (example 8.75): 12.15
Number of Years: 4

Loan Processing
Principal: $2500
Rate: 12.15%
Time: 4 years
Interest: $1215
Maturity Value: $3715

In a variable intensive program (we are still inside of one function only) where a local
variable holds the same name as the member of a namespace that is being accessed with
the using namespace routine, you will be sensitive to the calling of the same name
variable. When manipulating such a name of a variable that is present locally in the
function as well as in the namespace that is being accessed, the compiler will require
more precision from you. You will need to specify what name is being called.

3.3 Combining Namespaces

© FunctionX, Inc. 22
C++ Fundamentals Chapter 3 Techniques of Using Variables

3.3.1 Using Various Namespaces


Various namespaces can be part of the same file and the same application. You can create
each namespace and specify its own members in its delimiting curly brackets. With
various namespaces on the same file or application, you can have the same variables in
different namespaces. Here is an example of two namespaces:

namespace InterestAndDiscount
{
double Principal;
double Rate;
int Time;
double Interest;
double Discount;
double MaturityValue;
}

namespace BuyAndSell
{
double OriginalPrice;
double TaxRate;
double TaxAmount;
double Discount;
double DiscountAmount;
double NetPrice;
}

To access the member of a namespace, use the scope access operator appended to its
name and call the desired member. Here is an example:

#include <iostream.h>

namespace InterestAndDiscount
{
double Principal;
double Rate;
int Time;
double Interest;
double Discount;
double MaturityValue;
}

namespace BuyAndSell
{
double OriginalPrice;
double TaxRate;
double TaxAmount;
double Discount;
double DiscountAmount;
double NetPrice;
}

int main()
{
InterestAndDiscount::Principal = 12500; // $
InterestAndDiscount::Rate = 8.25; // %
InterestAndDiscount::Time = 5; // Years
InterestAndDiscount::Discount = InterestAndDiscount::Rate / 100;

© FunctionX, Inc. 23
C++ Fundamentals Chapter 3 Techniques of Using Variables

InterestAndDiscount::Interest = InterestAndDiscount::Principal *
InterestAndDiscount::Discount *
InterestAndDiscount::Time;
InterestAndDiscount::MaturityValue = InterestAndDiscount::Principal +
InterestAndDiscount::Interest;

cout << "Interest Calculation";


cout << "\nPrincipal: $" << InterestAndDiscount::Principal
<< "\nRate: " << InterestAndDiscount::Rate << "%"
<< "\nDiscount: " << InterestAndDiscount::Discount
<< "\nTime: " << InterestAndDiscount::Time << " years"
<< "\nInterest: $" << InterestAndDiscount::Interest
<< "\nMaturity Value: $" << InterestAndDiscount::MaturityValue;

BuyAndSell::OriginalPrice = 250; // $
BuyAndSell::TaxRate = 16.00; // %
BuyAndSell::Discount = 20.00; // %

BuyAndSell::TaxAmount = BuyAndSell::OriginalPrice *
BuyAndSell::TaxRate / 100;
BuyAndSell::DiscountAmount = BuyAndSell::OriginalPrice *
BuyAndSell::Discount / 100;
BuyAndSell::NetPrice = BuyAndSell::OriginalPrice +
BuyAndSell::TaxAmount -
BuyAndSell::DiscountAmount;

cout << "\n\nBuy and Sell - Receipt";


cout << "\nOriginal Price: $" << BuyAndSell::OriginalPrice
<< "\nDiscount: $" << BuyAndSell::DiscountAmount
<< "\nTax Rate: " << BuyAndSell::TaxRate
<< "\nTax Amount: $" << BuyAndSell::TaxAmount
<< "\nNet Price: $" << BuyAndSell::NetPrice << "\n\n";

return 0;
}

Using the scope access operator like that, you can perform any operation on any member
of one namespace applied to a member of another namespace.

We saw earlier that the using namespace routine allows accessing the members of a
namespace. After typing it, if the name of a variable appears under a using namespace,
the compiler would need to reconcile or identify it; if the name of such a variable is not
recognized as part of the namespace that is being accessed, the program would not
compile. For example, here is an example that uses two using namespace routines:

#include <iostream.h>

namespace InterestAndDiscount
{
double Principal;
double Rate;
int Time;
double Interest;
double Discount;
double MaturityValue;
}

namespace BuyAndSell

© FunctionX, Inc. 24
C++ Fundamentals Chapter 3 Techniques of Using Variables

{
double OriginalPrice;
double T axRate;
double TaxAmount;
double Discount;
double DiscountAmount;
double NetPrice;
}

int main()
{
using namespace InterestAndDiscount;
Principal = 12500; // $
Rate = 8.25; // %
Time = 5; // Years

Discount = Rate / 100;


Interest = Principal * Discount * Time;
MaturityValue = Principal + Interest;

cout << "Interest Calculation";


cout << "\nPrincipal: $" << Principal
<< "\nRate: " << Rate << "%"
<< "\nDiscount: " << Discount
<< "\nTime: " << Time << " years"
<< "\nInterest: $" << Interest
<< "\nMaturity Value: $" << MaturityValue;

using namespace BuyAndSell;


OriginalPrice = 250; // $
TaxRate = 16.00; // %
Discount = 20.00; // %

TaxAmount = OriginalPrice * TaxRate / 100;


DiscountAmount = OriginalPrice * Discount / 100;
NetPrice = OriginalPrice + TaxAmount - DiscountAmount;

cout << "\n\nBuy and Sell - Receipt";


cout << "\nOriginal Price: $" << OriginalPrice
<< "\nDiscount: $" << DiscountAmount
<< "\nTax Rate: " << TaxRate
<< "\nTax Amount: $" << TaxAmount
<< "\nNet Price: $" << NetPrice << "\n\n";

return 0;
}

The above program would not compile because the compiler does not understand what
Discount is being referred to in the second Discount call: is it
InterestAndDiscount::Discount or BuyAndSell::Discount?

If you want to use different namespaces with the using namespace routine, each
namespace will have to control its scope. One solution would be to create a “physical”
scope for each namespace. Here is an example:

#include <iostream.h>

namespace InterestAndDiscount

© FunctionX, Inc. 25
C++ Fundamentals Chapter 3 Techniques of Using Variables

{
...
}

namespace BuyAndSell
{
...
}

int main()
{
{
using namespace InterestAndDiscount;
...

cout << "Interest Calculation";


cout << "\nPrincipal: $" << Principal
<< "\nRate: " << Rate << "%"
<< "\nDiscount: " << Discount
<< "\nTime: " << Time << " years"
<< "\nInterest: $" << Interest
<< "\nMaturity Value: $" << MaturityValue;
}

using namespace BuyAndSell;


...

return 0;
}

Before creating a “physical” scope, we saw that the compiler is able to point out what
problem occurred at compilation time. Fortunately, the compiler is able to explicitly
designate what problem it encountered. In this case there is a conflict in name resolution:
two namespaces have a member of the same name.

The solution, which is commonly used, is to qualify the variable that is causing the
conflict. You can qualify only the second Discount call because the compiler will
associtate the first Discount call with the first using namespace. The safest way is to
qualify both calls to the Discount variable, as follows:

#include <iostream.h>

namespace InterestAndDiscount
{
...
}

namespace BuyAndSell
{
...
}

int main()
{
using namespace InterestAndDiscount;
Principal = 12500; // $
Rate = 8.25; // %
Time = 5; // Years

© FunctionX, Inc. 26
C++ Fundamentals Chapter 3 Techniques of Using Variables

InterestAndDiscount::Discount = Rate / 100;


Interest = Principal * InterestAndDiscount::Discount * Time;
MaturityValue = Principal + Interest;

cout << "Interest Calculation";


cout << "\nPrincipal: $" << Principal
<< "\nRate: " << Rate << "%"
<< "\nDiscount: " << InterestAndDiscount::Discount
<< "\nTime: " << Time << " years"
<< "\nInterest: $" << Interest
<< "\nMaturity V alue: $" << MaturityValue;

using namespace BuyAndSell;


OriginalPrice = 250; // $
TaxRate = 16.00; // %
BuyAndSell::Discount = 20.00; // %

TaxAmount = OriginalPrice * TaxRate / 100;


DiscountAmount = OriginalPrice * BuyAndSell::Discount / 100;
NetPrice = OriginalPrice + TaxAmount - DiscountAmount;

cout << "\n\nBuy and Sell - Receipt";


cout << "\nOriginal Price: $" << OriginalPrice
<< "\nDiscount: $" << DiscountAmount
<< "\nTax Rate: " << TaxRate
<< "\nTax Amount: $" << TaxAmount
<< "\nNet Price: $" << NetPrice << "\n\n";

return 0;
}

3.3.2 Nesting Namespaces


Nesting a namespace is the ability to include a namespace inside (as part of the body) of
another namespace. To do this, create the intended namespace as a member of the
parent namespace. The nested namespace should have its own name and its own body.
Here is an example:

namespace BuyAndSell
{
double OriginalPrice;
double TaxRate;
double TaxAmount;
double Discount;
double DiscountAmount;
double NetPrice;
{
long ItemNumber;
bool QualifyForDiscount;
}
}

To access a member of a nested namespace, first call its parent, type the :: operator, type
the name of the nested namespace, followed by the :: operator, then type the name of the
variable you are trying to access. Here is an example:

© FunctionX, Inc. 27
C++ Fundamentals Chapter 3 Techniques of Using Variables

#include <iostream.h>

namespace BuyAndSell
{
double OriginalPrice;
double TaxRate;
double TaxAmount;
double Discount;
double DiscountAmount;
double NetPrice;
namespace ItemID
{
long ItemNumber;
bool QualifyForDiscount;
}
}

int main()
{
BuyAndSell::OriginalPrice = 780.50;
BuyAndSell::TaxRate = 7.55;
BuyAndSell::Discount = 25; // %
BuyAndSell::ItemID::ItemNumber = 641238;
BuyAndSell::ItemID::QualifyForDiscount = true;

BuyAndSell::TaxAmount = BuyAndSell::OriginalPrice *
BuyAndSell::TaxRate / 100;
BuyAndSell::DiscountAmount = BuyAndSell::OriginalPrice *
BuyAndSell::Discount / 100;
BuyAndSell::NetPrice = BuyAndSell::OriginalPrice +
BuyAndSell::TaxAmount -
BuyAndSell::DiscountAmount;

cout << "Buy and Sell - Receipt";


cout << "\nItem Nunmber: " << BuyAndSell::ItemID::ItemNumber;
cout << "\nDiscount Category: " << BuyAndSell::ItemID::QualifyForDiscount ;
cout << "\nOriginal Price: $" << BuyAndSell::OriginalPrice;
cout << "\nDiscount: $" << BuyAndSell::DiscountAmount;
cout << "\nTax Rate: " << BuyAndSell::TaxRate;
cout << "\nTax Amount $" << BuyAndSell::TaxAmount;
cout << "\nNet Price: $" << BuyAndSell::NetPrice << "\n\n";

return 0;
}

Following the same logic, you can have as many namespaces and as many nested
namespaces in your application as you desire. If you nest a namespace, you can use as
many :: operators to qualify each member of the nested namespace you want. Here is an
example:

#include <iostream.h>

namespace BuyAndSell
{
double OriginalPrice;
double TaxRate;
double TaxAmount;
double Discount;

© FunctionX, Inc. 28
C++ Fundamentals Chapter 3 Techniques of Using Variables

double DiscountAmount;
double NetPrice;
namespace ItemID
{
long ItemNumber;
bool QualifyForDiscount;
namespace DateSold
{
int Month;
int Day;
int Year;
}
}
}

int main()
{
...

BuyAndSell::ItemID::DateSold::Month = 10;
BuyAndSell::ItemID::DateSold::Day = 18;
BuyAndSell::ItemID::DateSold::Year = 2002;

...

return 0;
}

You can also use the using namespace routine by calling each namespace using its
complete name:

#include <iostream.h>

namespace BuyAndSell
{
double OriginalPrice;
double TaxRate;
double TaxAmount;
double Discount;
double DiscountAmount;
double NetPrice;
namespace ItemID
{
long ItemNumber;
bool QualifyForDiscount;
namespace DateSold
{
int Month;
int Day;
int Year;
}
}
}

int main()
{
using namespace BuyAndSell;
using namespace BuyAndSell::ItemID;

© FunctionX, Inc. 29
C++ Fundamentals Chapter 3 Techniques of Using Variables

using namespace BuyAndSell::ItemID::DateSold;

OriginalPrice = 780.50;
TaxRate = 7.55;
Discount = 25; // %
ItemNumber = 641238;
QualifyForDiscount = true;

TaxAmount = OriginalPrice * TaxRate / 100;


DiscountAmount = OriginalPrice * Discount / 100;
NetPrice =OriginalPrice + TaxAmount - DiscountAmount;
Month = 10;
Day = 18;
Year = 2002;

cout << "Buy and Sell - Receipt";


cout << "\nReceipt Date: " << Month << "/" << Day << "/" << Year;
cout << "\nItem Nunmber: " << ItemNumber;
cout << "\nDiscount Category: " << QualifyForDiscount;
cout << "\nOriginal Price: $" << OriginalPrice;
cout << "\nDiscount: $" << DiscountAmount;
cout << "\nTax Rate: " << TaxRate;
cout << "\nTax Amount $" << TaxAmount;
cout << "\nNet Price: $" << NetPrice << "\n\n";

return 0;
}

Otherwise, you can create a using namespace for each namespace and make sure that
each one of them controls its scope. As long as you are using the scope access operator to
identify the variable that is being accessed inside of a using namespace, you can call the
member of any namespace in any scope, provided you qualify it.

3.3.3 The std Namespace


When you create a program, you subsequently create many of the things your program
will need to function. Such things, as we will learn, can include many variables, various
functions, and/or long classes. If you work on your own, you can keep in mind the names
of all of these objects. As we will learn, you must avoid using the same name for two
objects in the same program. This is a risk or behavior that is difficult to control when
many people work on the same program using this same language. To avoid this
situation, the C++ Standard provides a namespace called std. The std namespace
includes a series of libraries that you will routinely and regularly use in your programs.

The following libraries are part of the std namespace:

algorithm iomanip list ostream streambuf


bitset ios locale queue string
complex iosfwd map set typeinfo
deque iostream memory sstream utility
exception istream new stack valarray
fstream iterator numeric stdexcept vector
functional limits

© FunctionX, Inc. 30
C++ Fundamentals Chapter 3 Techniques of Using Variables

The following additional libraries can be used to include C header files into a C++
program:

cassert cios646 csetjmp cstdio ctime


cctype climits csignal cstdlib cwchar
cerrno clocale cstdarg cstring cwctype
cfloat cmath cstddef

Therefore, whenever you need to use a library that is part of the std namespace, instead
of typing a library with its file extension, as in iostream.h, you can just type the name of
the library as in iostream. Then, on the second line, type using namespace std;

As an example, instead of typing

#include <iostream.h>

You can type:

#include <iostream>
using namespace std;

Because this second technique is conform with the C++ Standard, we will use it
whenever we need one of its libraries.

The C++ Standard recommends that no function be provided without a returning value.
For example, although we would bew allowed to define the main() function as in

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

you should define what kind of value main() would return. Therefore, the main()
function should be written as int main() {}

As we will learn when studying functions, when a function has been written with int, it
must provide a result of a natural integer. To do this, in the last line of the body of
main(), you can type return 0;. Therefore, until we study functions, we will write the
main() function at least as follows:

#include <iostream>
using namespace std;
int main() { return 0; }

3.3.4 Introduction to Strings


A string is a character, a group of characters, or an empty space that you want the
compiler to treat “as is”. Besides using an array of characters, a special library called the
Standard Template Library (STL) provides an alternative. You can declare a string using
the string word.

To use a string in your program, first include the string library using the using
namespace std; . In your program, declare a variable starting with the word string
followed by a valid name for the variable. Here are examples:

© FunctionX, Inc. 31
C++ Fundamentals Chapter 3 Techniques of Using Variables

string Continent;
string Company;

When requesting its value from the user, by default, the string data type is used to get
only a one-word variable. Here is an example program that requests a first and last
names:

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

int main()
{
string FirstName, LastName;

cout << "Enter first name: ";


cin >> FirstName;
cout << "Enter last name: ";
cin >> LastName;

cout << "\n\nFull Name: " << FirstName << " " << LastName << "\n\n";
return 0;
}

You can initialize a string variable of any length. One technique is to use the assignment
operator and include the string in double-quotes. Here is an example:

string UN = "United Nations";


cout << "The " << UN << " is an organization headed by a Secretary General";

Another technique involves using parentheses following the name of the string variable,
and including the string in double-quotes. Here is an example:

string BookTitle("Drugs, Sociology, and Human Behavior.");


cout << "For our class next week, please read \"" << BookTitle;cout << "\"";

If you want to request the value of the variable from the user, you should use the getline()
function. To use the getline() function, follow this syntax:

getline(cin, StringName);

Inside of the parentheses, the word cin informs the compiler that the request will come
from an external source, ma inly the user typing from the keyboard. The StringName is
the name you declared the variable with. The getline() function expects that the user will
press Enter to end the sentence; the end line character is ‘\n’.

Here is an example program that requests strings of any length from the user:

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

int main()
{
string MusicAlbum;
string TrackTitle;

© FunctionX, Inc. 32
C++ Fundamentals Chapter 3 Techniques of Using Variables

cout << "Welcome to Radio Request where the listeners select their songs:\n";
cout << "Type the album name: ";
getline(cin, MusicAlbum);
cout << "Type the song title: ";
getline(cin, TrackTitle);

cout << "\nNow for your pleasure, we will play: " << TrackTitle
<< "\nfrom the " << MusicAlbum << " wonderful album.\n\n";

return 0;
}

If you want the user to end the sentence with another character such as * or !, use the
following function

getline(cin, StringName, Delimiter);

The following example uses the = symbol as the end character of the sentence:

string Address;

cout << "Enter your address. To end, type = ";


getline(cin, Address, '=');
cout << "\nSo, you live at: " << Address;

Here is an example:

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

int main()
{
string FirstName, LastName;

cout << "Welcome to College Park Auto-Parts\n";


cout << "Enter the following information about the customer's.\n";
cout << "First Name: ";
cin >> FirstName;
cout << "Last Name: ";
cin >> LastName;

cout << "\n\nCPAP Invoice # 1202";


cout << "\nCustomer Name: " << FirstName << " " << LastName << "\n\n";

return 0;
}

When requesting a string made of various words, such as an address, you can use the
getline() function as follows:

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

int main()

© FunctionX, Inc. 33
C++ Fundamentals Chapter 3 Techniques of Using Variables

{
string FirstName, LastName;
string Address;
string JobPerformed;

cout << "Welcome to College Park Auto-Parts\n";


cout << "Enter the following information about the customer's.\n";
cout << "First Name: ";
cin >> FirstName;
cout << "Last Name: ";
cin >> LastName;
cout << "Address: ";
getline(cin, Address);
cout << "Describe the job performed on the customer's car:\n";
getline(cin, JobPerformed);

cout << "\n\nCPAP Invoice # 1202";


cout << "\nCustomer Name: " << FirstName << " " << LastName;
cout << "\nAddress: " << Address;
cout << "\nJob Performed: " << JobPerformed << "\n\n";

return 0;
}

Practical Learning: Introducing Strings


1. Create a new project in a new directory or folder called Namespace1
2. Save the project as Names
3. If necessary, create a source file. Save the first source file as Main.cpp
4. To create a new namespace, change the Main.cpp file as follows:

#include <iostream>
using namespace std;

namespace Students
{
string FirstName;
string LastName;
char Gender;
}

int main()
{
Students::FirstName = "Laurentine";
Students::LastName = "Sachs";
Students::Gender = 'F';

cout << "Student Registration";


cout << "\nFull Name: "
<< Students::FirstName << " " << Students::LastName;
cout << "\nGender: " << Students::Gender;

return 0;
}

5. Test the program:

© FunctionX, Inc. 34
C++ Fundamentals Chapter 3 Techniques of Using Variables

Student Registration
Full Name: Laurentine Sachs
Gender: F

© FunctionX, Inc. 35
C++ Fundamentals Chapter 9: Constructing Expressions

Chapter 8:
Constructing Expressions

? Combining Statements

? Logical Conjunction and Disjunction

? Conditional Statements and Functions

© FunctionX, Inc. 36
C++ Fundamentals Chapter 9: Constructing Expressions

1.1 Combining Statements

1.1.1 Introduction
There are techniques you can use to combine conditional statements when one of them
cannot fully implement the desired behavior.

We will continue with our traffic light analogy.

1.1.2 Nesting Conditions


A condition can be created inside of another to write a more effective statement. This is
referred to as nesting conditions. Almost any condition can be part of another and
multiple conditions can be included inside of others.

As we have learned, different conditional statements are applied in specific


circumstances. In some situations, they are interchangeable or one can be applied just like
another, which becomes a matter of choice. Statements can be combined to render a
better result with each playing an appropriate role.

To continue with our ergonomic program, imagine that you would really like the user to
sit down and your program would continue only once she answers that she is sitting
down, you can use the do…while statement to wait for the user to sit down; but as the
do…while is checking the condition, you can insert an if statement to enforce your
request. Here is an example of how you can do it:

#include <iostream>
using namespace std;

int main()
{
char SittingDown;

do {
cout << "Are you sitting down now(y/n)? ";
cin >> SittingDown;

if( SittingDown != 'y' )


cout << "Could you please sit down for the next exercise?";
cout << "\n\n";
} while( !(SittingDown == 'y') );

cout << "Wonderful!!!";

return 0;
}

Here is an example of running the program:

Are you sitting down now(y/n)? n


Could you please sit down for the next exercise?

Are you sitting down now(y/n)? n

© FunctionX, Inc. 37
C++ Fundamentals Chapter 9: Constructing Expressions

Could you please sit down for the next exercise?

Are you sitting down now(y/n)? y

Wonderful!!!

One of the reasons you would need to nest conditions is because one would lead to
another. Sometimes, before checking one condition, another primary condition would
have to be met. The ergonomic program we have been simulating so far is asking the user
whether she is sitting down. Once the user is sitting down, you would write an exercise
she would perform. Depending on her strength, at a certain time, one user will be tired
and want to stop while for the same amount of previous exercises, another user would
like to continue. Before continuing with a subsequent exercise, you may want to check
whether the user would like to continue. Of course, this would be easily done with:

#include <iostream>
using namespace std;

int main()
{
char SittingDown;

do {
cout << "Are you sitting down now(y/n)? ";
cin >> SittingDown;

if( SittingDown != 'y' )


cout << "Could you please sit down for the next exercise?";
cout << "\n\n";
}while( SittingDown != 'y' );

cout << "Wonderful. Now we will continue today's exercise...";


cout << "\n...\nEnd of exercise";

char WantToContinue;

cout << "Do you want to continue(y=Yes/n=No)? ";


cin >> WantToContinue;

return 0;
}

If the user answers No, you can stop the program. If she answers Yes, you would need to
continue the program with another exercise. Because the user answered Yes, the
subsequent exercise would be included in the previous condition because it does not
apply for a user who wants to stop. In this case, one “if” could be inserted inside of
another. Here is an example:

#include <iostream>
using namespace std;

int main()
{
char SittingDown;

do {
cout << "Are you sitting down now(y/n)? ";

© FunctionX, Inc. 38
C++ Fundamentals Chapter 9: Constructing Expressions

cin >> SittingDown;

if( SittingDown != 'y' )


cout << "Could you please sit down for the next exercise?";
cout << "\n\n";
}while( SittingDown != 'y' );

cout << "Wonderful. Now we will continue today's exercise...\n";


cout << "\n...\n\nEnd of exercise\n";

char WantToContinue;

cout << "\nDo you want to continue(1=Yes/0=No)? ";


cin >> WantToContinue;

if(WantToContinue == '1')
{
char LayOnBack;

cout << "Good. For the next exercise, you should lay on your back";
cout << "\nAre you laying on your back(1=Yes/0=No)? ";
cin >> LayOnBack;

if(LayOnBack == '1')
cout << "\nGreat.\nNow we will start the next exercise.";
else
cout << "\nWell, it looks like you are getting tired...";
}
else
cout << "\nWe had enough today";

cout << "\nWe will stop the session now \nThanks.\n";

return 0;
}

In the same way, you can nest statements as you see fit. The goal is to provide an
efficient and friendly application. You can insert and nest statements that provide
valuable feedback to the user while minimizing boredom. The above version of the
program can be improved as followed:

#include <iostream>
using namespace std;

int main()
{
char SittingDown;

do {
cout << "Are you sitting down now(y/n)? ";
cin >> SittingDown;

if( SittingDown != 'y' )


cout << "Could you please sit down for the next exercise?";
cout << "\n\n";
}while( SittingDown != 'y' );

cout << "Wonderful. Now we will continue today's exercise...\n";

© FunctionX, Inc. 39
C++ Fundamentals Chapter 9: Constructing Expressions

cout << "\n...\n\nEnd of exercise\n";

char WantToContinue;

cout << "\nDo you want to continue(1=Yes/0=No)? ";


cin >> WantToContinue;

if(WantToContinue == '1')
{
char LayOnBack;

cout << "Good. For the next exercise, you should lay on your back";
cout << "\nAre you laying on your back(1=Yes/0=No)? ";
cin >> LayOnBack;

if(LayOnBack == '0')
{
char Ready;

do {
cout << "Please lay on your back";
cout << "\nAre you ready(1=Yes/0=No)? ";
cin >> Ready;
}while(Ready == '0');
}
else if(LayOnBack == '1')
cout << "\nGreat.\nNow we will start the next exercise.";
else
cout << "\nWell, it looks like you are getting tired...";
}
else
cout << "\nWe had enough today";

cout << "\nWe will stop the session now \nThanks.\n";

return 0;
}

Practical Learning: Nesting Conditions


1. To nest an if…else condition in a do…while statement, change the program as
follows:
#include <iostream>
using namespace std;

int main()
{
char Light;

do {
cout << "What is the current light "
<< "color(g=Green/y=Yellow/r=Red)? ";
cin >> Light;

if( Light == 'g' )


{
cout << "\nThe light is green";
cout << "\nYou can proceed and drive through.\n";

© FunctionX, Inc. 40
C++ Fundamentals Chapter 9: Constructing Expressions

}
else if( Light == 'y' )
{
cout << "\nYellow Light";
cout << "\nBe careful!\n";
}
else if( Light == 'r' )
{
cout << "\nShow respect for the red light";
cout << "\nPlease Stop!!!\n";
}
else
cout << endl << Light << " is not a valid color.\n";
} while( Light == 'r' );

return 0;
}
2. Test the program and return to your development environment
3. To add a while and a for loops, change the program as follows:
#include <iostream>
using namespace std;

int main()
{
char Light;
int Timer;

do {
cout << "What is the current light "
<< "color(g=Green/y=Yellow/r=Red)? ";
cin >> Light;

if( Light == 'g' )


{
cout << "\nThe light is green";
cout << "\nYou can proceed and drive through.\n";
}
else if( Light == 'y' )
{
Timer = 0;

while(Timer < 5)
{
cout << Timer << ". Yellow Light - Be Careful!\n";
Timer++;
}

cout << "\nYellow light ended. Please Stop!!!\n";


}
else if( Light == 'r' )
{
cout << "\nShow respect for the red light";
cout << "\nPlease Stop!!!\n";

for( Timer = 1; Timer < 60; ++Timer)


{
if( Timer < 10 )

© FunctionX, Inc. 41
C++ Fundamentals Chapter 9: Constructing Expressions

cout << " " << Timer << ".Red ";


else
cout << Timer << ".Red ";

if( Timer % 10 == 0 )
cout << endl;
}
cout << "\n - Red light ended -\n\n";
}
else
cout << endl << Light << " is not a valid color.\n";

} while( Light == 'r' );

return 0;
}
4. Test the program and return to development environment.
5. Save your project

1.1.3 The break Statement


The break statement is used to stop a loop for any reason or condition the programmer
sees considers fit. The break statement can be used in a while condition to stop an
ongoing action. The syntax of the break statement is simply:

break;

Although made of only one word, the break statement is a complete statement; therefore,
it can (and should always) stay on its own line (this makes the program easy to read).

The break statement applies to the most previous conditional statement to it; provided
that previous statement is applicable.

The following program would display the letter d continuously unless something or
somebody stops it. A break statement is inserted to stop this ever looping process:

#include <iostream>
using namespace std;

int main()
{
char Letter = 'd';

while( Letter <= 'n' )


{
cout << "Letter " << Letter << endl;
break;
}

return 0;
}

The break statement can also be used in a do…while or a for loop the same way.

© FunctionX, Inc. 42
C++ Fundamentals Chapter 9: Constructing Expressions

The break statement is typically used to handle the cases in a switch statement. We saw
earlier that all cases in a switch would execute starting where a valid statement is found.

Consider the program we used earlier to request a number from 1 to 3, a better version
that involves a break in each case would allow the switch to stop once the right case is
found. Here is a new version of that program:

#include <iostream>
using namespace std;

int main()
{
int Number;

cout << "Type a number between 1 and 3: ";


cin >> Number;

switch (Number)
{
case 1:
cout << "\nYou typed 1.";
break;
case 2:
cout << "\nYou typed 2.";
break;
case 3:
cout << "\nYou typed 3.";
break;
default:
cout << endl << Number << " is out of the requested range.";
}

return 0;
}

Even when using the break statement, the switch allows many case to execute as one. To
do this, as we saw when not using the break, type two cases together. This technique is
useful when validating letters because the letters could be in uppercase or lowercase. This
illustrated in the following program:

#include <iostream>
using namespace std;

int main()
{
char Letter;

cout << "Type a letter: ";


cin >> Letter;

switch( Letter )
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':

© FunctionX, Inc. 43
C++ Fundamentals Chapter 9: Constructing Expressions

case 'o':
case 'O':
case 'u':
case 'U':
cout << "The letter you typed, " << Letter << ", is a vowel\n";
break;

case 'b':case 'c':case 'd':case 'f':case 'g':case 'h':case 'j':


case 'k':case 'l':case 'm':case 'n':case 'p':case 'q':case 'r':
case 's':case 't':case 'v':case 'w':case 'x':case 'y':case 'z':
cout << Letter << " is a lowercase consonant\n";
bre ak;

case 'B':case 'C':case 'D':case 'F':case 'G':case 'H':case 'J':


case 'K':case 'L':case 'M':case 'N':case 'P':case 'Q':case 'R':
case 'S':case 'T':case 'V':case 'W':case 'X':case 'Y':case 'Z':
cout << Letter << " is a consonant in uppercase\n";
break;

default:
cout << "The symbol " << Letter
<< " is not an alphabetical letter\n";
}

return 0;
}

The switch statement is also used with an enumerator that controls cases. This is also a
good place to use the break statement to decide which case applies. An advantage of
using an enumerator is its ability to be more explicit than a regular integer.

To use an enumerator, define it and list each one of its members for the case that applies.
Remember that, by default, the members of an enumerator are counted with the first
member having a value of 0, the second is 1, etc. Here is an example of a switch
statement that uses an enumerator.

#include <iostream>
using namespace std;

enum EmploymentStatus { esFullTime, esPartTime, esContractor, esNS };

int main()
{
int EmplStatus;

cout << "Employee's Contract Status: ";


cout << "\n0 - Full Time | 1 - Part Time"
<< "\n2 - Contractor | 3 - Other"
<< "\nStatus: ";
cin >> EmplStatus;
cout << endl;

switch( EmplStatus )
{
case esFullTime:
cout << "Employment Status: Full Time\n";
cout << "Employee's Benefits: Medical Insurance\n"
<< " Sick Leave\n"

© FunctionX, Inc. 44
C++ Fundamentals Chapter 9: Constructing Expressions

<< " Maternal Leave\n"


<< " Vacation Time\n"
<< " 401K\n";
break;

case esPartTime:
cout << "Employment Status: Part Time\n";
cout << "Employee's Benefits: Sick Leave \n"
<< " Maternal Leave\n";
break;

case esContractor:
cout << "Employment Status: Contractor\n";
cout << "Employee's Benefits: None\n";
break;

case esNS:
cout << "Employment Status: Other\n";
cout << "Status Not Specified\n";
break;

default:
cout << "Unknown Status\n";
}

return 0;
}

Practical Learning: Using the break Statement


1. Create a new project called Statements2
2. Create a new C++ source file called Main
3. To apply the break statement, change the program as follows:
#include <iostream>
using namespace std;

int main()
{
char Light;

cout << "What is the current light color(g=Green/y=Yellow/r=Red)? ";


cin >> Light;

switch( Light )
{
case 'g':
cout << "\nThe light is green";
cout << "\nYou can proceed and drive through.\n";
break;

case 'y':
cout << "\nBe careful!\n";
break;

case 'r':
cout << "\nPlease Stop!!!\n";
break;

© FunctionX, Inc. 45
C++ Fundamentals Chapter 9: Constructing Expressions

default:
cout << endl << Light << " is not a valid color.\n";
}

return 0;
}
4. Test the program and return to development environment.
5. Assuming the user might enter a color in uppercase, change the program as follows:
#include <iostream>
using namespace std;

int main()
{
char Light;

cout << "What is the current light color(g=Green/y=Yellow/r=Red)? ";


cin >> Light;

switch( Light )
{
case 'g':
case 'G':
cout << "\nThe light is green";
cout << "\nYou can proceed and drive through.\n";
break;

case 'y':
case 'Y':
cout << "\nBe careful!\n";
break;

case 'r':
case 'R':
cout << "\nPlease Stop!!!\n";
break;

default:
cout << endl << Light << " is not a valid color.\n";
}

return 0;
}
6. Test the program and return to your development environment.
7. To use an enumerator in a switch statement, change the program as follows:
#include <iostream>
using namespace std;

enum TTrafficLight { tlGreen = 1, tlYellow, tlRed };

int main()
{
int Light;

cout << "What is the current light color(1=Green/2=Yellow/3=Red)? ";


cin >> Light;

© FunctionX, Inc. 46
C++ Fundamentals Chapter 9: Constructing Expressions

switch( Light )
{
case tlGreen:
cout << "\nThe light is green";
cout << "\nYou can proceed and drive through.\n";
break;

case tlYellow:
cout << "\nYellow Light";
cout << "\nBe careful!\n";
break;

case tlRed:
cout << "\nRespect the red light";
cout << "\nPlease Stop!!!\n";
break;

default:
cout << endl << Light << " is not a valid color.\n";
}

return 0;
}
8. Test the program and return to your programming environment.

1.1.4 The continue Statement


The continue statement uses the following syntax:

continue;

When processing a loop, if the statement finds a false value, you can use the continue
statement inside of a while, do…while or a for conditional statements to ignore the
subsequent statement or to jump from a false Boolean value to the subsequent valid
value, unlike the break statement that would exit the loop. Like the break statement, the
continue keyword applies to the most previous conditional statement and should stay on
its own line.

The following programs asks the user to type 4 positive numbers and calculates the sum
of the numbers by considering only the positive ones. If the user types a negative number,
the program manages to ignore the numbers that do not fit in the specified category:

#include <iostream>
using namespace std;

int main()
{
// Declare necessary variables
int posNumber, Sum = 0;

// Request 4 positive numbers from the user


cout << "Type 4 positive numbers.\n";
// Make sure the user types 4 positive numbers
for( int Count = 1; Count <= 4; Count++ )
{

© FunctionX, Inc. 47
C++ Fundamentals Chapter 9: Constructing Expressions

cout << "Number: ";


cin >> posNumber;

// If the number typed is not positive, ignore it


if( posNumber < 0 )
continue;

// Add each number to the sum


Sum += posNumber;
}

// Display the sum


cout << "\nSum of the numbers you entered = " << Sum << "\n\n";

return 0;
}

1.1.5 The goto Statement


The goto statement allows a program execution to jump to another section of the function
in which it is being used.

In order to use the goto statement, insert a name on a particular section of your function
so you can refer to that name. The name, also called a label, is made of one word and
follows the rules we have learned about C++ names (the name can be anything), then
followed by a colon. The following program uses a for loop to count from 0 to 12, but
when it encounters 5, it jumps to a designated section of the program:

#include <iostream>
using namespace std;

int main()
{
cout << "We need to count from 0 to 12\n";
for(int Count = 0; Count <= 12; ++Count)
{
cout << "Count " << Count << endl;

if( Count == 5 )
goto MamaMia;
}

MamaMia:
cout << "Stopped at 5";

return 0;
}

1.2 Logical Conjunction and Disjunction


The conditional Statements we have used so far were applied to single situations. You
can combine statements using techniques of logical thinking to create more complex and
complete expressions. One way to do this is by making sure that two conditions are met
for the whole expression to be true. On the other hand, one or the other of two conditions

© FunctionX, Inc. 48
C++ Fundamentals Chapter 9: Constructing Expressions

can produce a true condition, as long as one of them is true. This is done with logical
conjunction or disjunction.

1.2.1 Using the Logical Not


When a driver comes to a light that he expects to be green, we saw that he would use a
statement such as, "The light is green". If in fact the light is green, we saw that the
statement would lead to a true result. If the light is not green, the "The light is green"
statement produces a false result. This is shown in the following table:

Color Statement Boolean Value

The light is green true

The light is green false

As you may realize already, in Boolean algebra, the result of performing a comparison
depends on how the Condition is formulated. If the driver is approaching a light that he is
expecting to display any color other than green, he would start from a statement such as
"The light is not green". If the light IS NOT green, the expression "The light is not
green" is true (very important). This is illustrated in the following table:

Color Statement Boolean Value

The light is green true

The light is not green

The "The light is not green" statement is expressed in Boolean algebra as “Not the light is
green”. Instead of writing “Not the light is green", in C++, using the logical Not operator
, you would formulate the statement as, !"The light is green". Therefore, if P means “The
light is green”, you can express the negativity of P as !P. The Boolean table produced is:

Boolean
Color Statement Symbol
Value

The light is green true P

The light is not green false !P

When a statement is true, its Boolean value is equivalent to a non-zero integer such as 1.
Otherwise, if a statement produces a false result, it is given a 0 value. Therefore, our table
would be:

Boolean Integer
Color Statement
Value Value

© FunctionX, Inc. 49
C++ Fundamentals Chapter 9: Constructing Expressions

The light is green true 1

The light is not green false 0

Even though a program usually asks a straightforward question, the compiler would only
consider the expression that needs to be evaluated; that is, the expression included
between the parentheses of the if Condition. Suppose you are writing an ergonomic
program that would guide the user on when and how to exercise. One of the questions
your program would ask might be: "Are you sitting down?" There are three classic
variances to this issue: the user might be sitting down, standing up, or laying down. Your
program might look like this:

#include <iostream>
using namespace std;

int main()
{
int Position;

cout << "Specify your position:\n"


<< "1 - Sitting Down\n"
<< "2 - Standing Up\n"
<< "3 - Laying Down\n";
cin >> Position;

if( Position == 1 )
cout << "\nNow, position your back as vertically as you can.\n";

return 0;
}

That program allows the user to give one of three answers; and you might do something
depending on the user’s answer. Now, suppose you only want to know whether the user
is sitting down; in fact, the program might expect the user to be sitting down for the
subsequent assignment. Such a program could be:

#include <iostream>
using namespace std;

int main()
{
int SittingDown;

cout << "Are you sitting down (1=Yes/0=No)? ";


cin >> SittingDown;

if( SittingDown == 1 )
cout << "\nGood, now we will continue with the next exercise.";

return 0;
}

If the user is standing up, you would like her to sit down. If she is laying down, you still
would like her to sit down. Based on this requirement, you might want to check whether

© FunctionX, Inc. 50
C++ Fundamentals Chapter 9: Constructing Expressions

the user is sitting down and you would not be interested in another position. The question
could then be, “Aren't you sitting down?”. In Boolean algebra, the question would be
asked as, " Are you NOT sitting down?". A better C++ question would be, “Not “ “Are
you sitting down?”. In other words, the statement (in this case the question) would be the
negation of the regular question. If P represents the “Are you sitting down?” question, the
negativity of P is expressed as !P. The new version of our program would be more
concerned with the position the user has. Since the user is expected to type 1 for Yes, the
program would display a concern for any other answer; in short, it would check the
negativity of the Condition:

#include <iostream>
using namespace std;

int main()
{
int SittingDown;

cout << "Are you sitting down (1=Yes/0=No)? ";


cin >> SittingDown;

if( !(SittingDown == 1) )
cout << "\nCould you please sit down for the next exercise?";

cout << "\nWonderful!!!\n\n";

return 0;
}

Practical Learning: Using the Logical not Operator


1. Create a new console application named Not
2. Create a C++ source file named Exercise
3. To apply the logical not operator, change the contents of the file as follows:
#include <iostream>
using namespace std;

int main()
{
char Light;

cout << "What is the current light color(g=Green/y=Yellow/r=Red)? ";


cin >> Light;

if ( !(Light == 'g') )
{
cout << "\nThe light is not green";
cout << "\nPlease stop and wait.";
}
else
cout << "\nThe road is cleared. You can drive through";

return 0;
}
4. Test your program.

© FunctionX, Inc. 51
C++ Fundamentals Chapter 9: Constructing Expressions

1.2.2 Logical Conjunction: AND


The law of the traffic light states that if a driver drives through a red light, he or she has
broken the law. Three things happen here:

??The traffic light is red

??The driver is driving

??The law is broken

Let’s segment these expressions and give each a name. The first statement will be called
L. Therefore,

??L <=> The traffic light is red

The second statement will be called D. This means

??D <=> The driver is driving through the light

The last statement will be called B, which means

??B <=> The law is broken

Whenever the traffic light is red, the “The traffic light is red” statement is true. Whenever
a driver is driving, the “The driver is driving” statement is true, which means D is true.
Whenever the law is broken, the “The law is broken” statement is true. When a statement
is true, it receives a Boolean value of true:

L B D
true true true

These three statements are completely independent when each is stated in its own
sentence. The third bears any consideration only when the first two are combined.
Therefore, the third statement is a consequence or a result. The fact that a driver is
driving and/or a light is red or dis plays any color, does not make a law broken. The law is
broken only when or IF a driver drives through a red light. This means L and D have to
be combined to produce B.

A combination of the first two statements means you need Statement1 AND Statement2.
Co mbining Statement1 AND Statement2 means L AND D that produces

"The traffic light is red” AND “The driver is driving through the light"

In C++, the AND keyword is called an operator because it applies for one or more
variable. The AND operator is specifically called a binary operator because it is used on
two variables. The AND operator is used to concatenate or add two statements or
expressions. It is represented by &&. Therefore, a concatenation of L and D would be
written as L && D. Logically, what does the combination mean?

When the traffic light is red, L is true. If a driver is driving through the light, D is true. If
the driver is driving through the light that is red, this means L && D. Then the law is
broken:

© FunctionX, Inc. 52
C++ Fundamentals Chapter 9: Constructing Expressions

L D L && D B
true true true TRUE
When the traffic light is not red, regardless of the light’s color, L is false. If a driver
drives through it, no law is broken. Remember, not only should you drive through a green
light, but also you are allowed to drive through a yellow light. Therefore, B is false:

L D L && D B
false true false FALSE

If the traffic light is red, L is true. If no driver drives through it, D is false, and no law is
broken. When no law is broken, B, which is the result of L && D, is false:

L D L && D B
true false false FALSE

If the light is not red, L is false. If no driver drives through it, D is false. Consequently,
no law is broken. B, which is the result of L && D, is still false:

L D L && D B
false false false FALSE

From our tables, the law is broken only when the light is red AND a driver drives through
it. This produces:

L D L && D B
true true true TRUE
false true false FALSE
true false false FALSE
false false false FALSE

The logical conjunction operator && is used to check that the combination of two
statements results in a true condition. This is used when one condition cannot satisfy the
intended result. Consider a pizza application whose valid sizes are 1 for small, 2 for
medium, 3 for large, and 4 for jumbo. When a clerk uses this application, you would
usually want to make sure that only a valid size is selected to process an order. After the
clerk has selected a size, you can use a logical conjunction to validate the range of the
item’s size. Such a program could be written (or started) as follows:

#include <iostream>
using namespace std;

int main()
{
int PizzaSize;

cout << "Select your pizza size";


cout << "\n1=Small | 2=Medium";
cout << "\n3=Medium | 4=Jumbo";
cout << "\nYour Choice: ";
cin >> PizzaSize;

if(PizzaSize >= 0 && PizzaSize <= 4)

© FunctionX, Inc. 53
C++ Fundamentals Chapter 9: Constructing Expressions

cout << "\nGood Choice. Now we will proceed with the toppings";
else
cout << "\nInvalid Choice";

return 0;
}

When a program asks a question to the user who must answer by typing a letter, there is a
chance that the user would type the answer in uppercase or lowercase. Since we know
that C++ is case-sensitive, you can use a combined conditional statement to find out what
answer or letter the user would have typed.

We saw that the truthfulness of a statement depends on how the statement is structured.
In some and various cases, instead of checking that a statement is true, you can validate
only negative values. This can be done on single or combined statements. For example, if
a program is asking a question that requires a Yes or No answer, you can make sure the
program gets a valid answer before continuing. Once again, you can use a logical
conjunction to test the valild answers. Here is an example:

#include <iostream>
using namespace std;

int main()
{
char SittingDown;

do {
cout << "Are you sitting down now(y/n)? ";
cin >> SittingDown;

if( SittingDown != 'y' && SittingDown != 'Y' )


cout << "\nCould you please sit down for the next exercise?\n";
} while( SittingDown != 'y' && SittingDown != 'Y' );

cout << "\nWonderful!!!";

return 0;
}

1.2.3 Logical Disjunction: OR


Let’s assume that a driver has broken the law by driving through a red traffic light but
there was no accident (to make our discussion simpler). There are two ways he can get a
ticket: a police officer saw him, a special camera took a picture. This time again, we have
three statements to make:

??S <=> A police officer saw the driver

??H <=> A camera took a picture of the action

??T <=> The driver got a ticket

If a police officer saw the driver breaking the law, the “A police officer saw the driver”
statement is true. Consequently, S is true.
If a (specially installed) camera took the picture (of the scene), the “A camera took the
picture of the action” statement is true. This means H is true.

© FunctionX, Inc. 54
C++ Fundamentals Chapter 9: Constructing Expressions

If the driver gets a ticket, the “The driver gets a ticket” statement is true, which means T
is true:

S H T
true true true

Once again, the third statement has no bearing unless you consider the first two. Last
time, we saw that if the first two statements were combined, only then the result would
produce the third statement. Let’s consider in which case the driver would get a ticket.

If a police officer saw the driver, would he get a ticket? Yes, because on many traffic
lights there is no camera but a police officer has authority to hand an infraction. This
means if S is true, then T also is true. This produces:

S H T
true Don't Care true

Imagine a traffic light is equipped with a camera. If the driver breaks the law, the camera
would take a picture, which means the driver would get a ticket. Therefore, if a camera
takes a picture (H is true), the driver gets a ticket (T is true):

S H T
Don't Care true true

What if a police officer catches the action and a camera takes a picture. This means the
driver will still get a ticket, even if one of both the police officer and the camera does not
act but the other does. If both the police officer and the camera catch the action and act
accordingly, the driver would get only one ticket (even if the driver receives two tickets,
only one would be considered). Therefore, whether the first statement OR the second
statement is true, the resulting third statement T is still true:

S H T
true true true

The only time the driver would not get a ticket is when no police officer catches him and
no camera takes a picture. In other words, only when both of the first two statements are
false can the third statement be false.

Since T is the result of S and H combined, we have seen that T is true whenever either S
is true OR H is true. The OR logical disjunction is expressed in C++ with the || operator.
Here is the resulting table:

S H S || H T
true true true TRUE
false true true TRUE
true false true TRUE
false false false FALSE

Consider a program that asks a question and expects a yes or no answer in the form of y
or n. Besides y for yes, you can also allow the user to type Y as a valid yes. To do this,
you would let the compiler check that either y or Y was typed. In the same way, either n

© FunctionX, Inc. 55
C++ Fundamentals Chapter 9: Constructing Expressions

or N would be valid negations. Any of the other characters would fall outside the valid
characters. Our hot-tempered program can be restructured as follows:

#include <iostream>
using namespace std;

int main()
{
char Answer;

cout << "Do you consider yourself a hot -tempered individual(y=Yes/n=No)? ";
cin >> Answer;

if( Answer == 'y' || Answer == 'Y' ) // Unique Condition


{
cout << "\nThis job involves a high level of self-control.";
cout << "\nWe will get back to you.\n";
}
else if( Answer == 'n' || Answer == 'N' ) // Alternative
cout << "\nYou are hired!\n";
else
cout << "\nThat was not a valid answer!\n";

return 0;
}

Practical Learning: Combining Conditions


1. Create a new project named ComboConditions.
2. Create a new C++ source file named Exercise
3. Change the file with the following:
#include <iostream>
using namespace std;

int main()
{
char Light, L;
int Timer;

// Make sure the user enters a valid letter for a traffic light
do {
cout << "What is the current light "
<< "color(g=Green/y=Yellow/r=Red)? ";
cin >> Light;
} while( Light != 'r' && Light != 'R' &&
Light != 'y' && Light != 'Y' &&
Light != 'g' && Light != 'G' );

// Process a message depending on the current traffic light


if( Light == 'g' || Light == 'G' )
{
cout << "\nThe light is green";
cout << "\nYou can proceed and drive through.\n";
}
else if( Light == 'y' || Light == 'Y' )
{
Timer = 0;

© FunctionX, Inc. 56
C++ Fundamentals Chapter 9: Constructing Expressions

while(Timer < 5)
{
cout << Timer << ". Yellow Light - Be Careful!\n";
Timer++;
}

cout << "\nYellow light ended. Please Stop!!!\n";


}
else if( Light == 'r' || Light == 'R' )
{
cout << "\nShow respect for the red light";
cout << "\nPlease Stop!!!\n";

for( Timer = 1; Timer < 60; ++Timer)


{
if( Timer < 10 )
cout << " " << Timer << ".Red ";
else
cout << Timer << ".Red ";

if( Timer % 10 == 0 )
cout << endl;
}

cout << "\n - Red light ended -\n\n";


}
else
cout << endl << Light << " is not a valid color.\n";

return 0;
}
4. Test the program and return to your programming environment
5. To further refine your application, change the program as follows:
#include <iostream>
using namespace std;

enum TDrivingAnswer { daNo, daYes };

int main()
{
char Light;
int Timer;
int Answer;

do {
// Make sure the user enters a valid letter for a traffic light
do {
cout << "What is the current light "
<< "color(g=Green/y=Yellow/r=Red)? ";
cin >> Light;
// The user typed an invalid color for the traffic light
if( Light != 'r' && Light != 'R' &&
Light != 'y' && Light != 'Y' &&
Light != 'g' && Light != 'G' )
cout << "Invalid color\n";
} while( Light != 'r' && Light != 'R' &&

© FunctionX, Inc. 57
C++ Fundamentals Chapter 9: Constructing Expressions

Light != 'y' && Light != 'Y' &&


Light != 'g' && Light != 'G' );

// Process a message depending on the current traffic light


if( Light == 'g' || Light == 'G' )
{
cout << "\nThe light is green";
cout << "\nYou can proceed and drive through.\n";
}
else if( Light == 'y' || Light == 'Y' )
{
Timer = 0;
while(Timer < 5)
{
cout << Timer << ". Yellow Light - Be Careful!\n";
Timer++;
}
cout << "\nYellow light ended. Please Stop!!!\n";
}
else if( Light == 'r' || Light == 'R' )
{
cout << "\nShow respect for the red light";
cout << "\nPlease Stop!!!\n";

for( Timer = 1; Timer < 60; ++Timer)


{
if( Timer < 10 )
cout << " " << Timer << ".Red ";
else
cout << Timer << ".Red ";
if( Timer % 10 == 0 )
cout << endl;
}

cout << "\n - Red light ended -\n\n";


}
else
cout << endl << Light << " is not a valid color.\n";

cout << "\nAre you still on the road(0=No/1=Yes)? ";


cin >> Answer;
cout << endl;
} while( Answer == daYes );

cout << "\nNice serving you";

return 0;
}
6. Test the program and return to your development environment.
7. Save your program.

1.3 Conditional Statements and Functions

© FunctionX, Inc. 58
C++ Fundamentals Chapter 9: Constructing Expressions

1.3.1 Using Conditions in Functions


The use of functions in a program allows you to isolate assignments and confine them to
appropriate entities. While the functions take care of specific requests, you should
provide them with conditional statements to validate what these functions are supposed to
do. There are no set rules to the techniques involved; everything depends on the tasks at
hand. Once again, you will have to choose the right tools for the right job. To make
effective use of functions, you should be very familiar with different data types because
you will need to return the right value.

The ergonomic program we have been writing so far needs to check different things
including answers from the user in order to proceed. These various assignments can be
given to functions that would simply hand the results to the main() function that can, in
turn, send these results to other functions for further processing. Here is an example:

#include <iostream>
using namespace std;

#define Or ||
#define And &&

char GetPosition()
{
char Position;

do {
cout << "Are you sitting down now(y/n)? ";
cin >> Position;

if( Position != 'y' And Position != 'Y' And


Position != 'n' And Position != 'N' )
cout << "Invalid Answer\n";
} while( Position != 'y' And Position != 'Y' And
Position != 'n' And Position != 'N' );

return Position;
}

int main()
{
char Position;

Position = GetPosition();
if( Position == 'n' Or Position == 'N' )
cout << "\nCould you please sit down for the next exercise?\n";
else
cout << "\nWonderful!!!\n\n";

return 0;
}

Functions do not have to return a value in order to be involved with conditional


statements. In fact, both issues are fairly independent. This means, void and non-void
functions can manipulate values based on conditions internal to the functions. This is
illustrated in the following program that is an enhancement to an earlier ergonomic
program:

© FunctionX, Inc. 59
C++ Fundamentals Chapter 9: Constructing Expressions

#include <iostream>
using namespace std;

#define Or ||
#define And &&

char GetPosition()
{
char Position;

do {
cout << "Are you sitting down now(y/n)? ";
cin >> Position;

if( Position != 'y' And


Position != 'Y' And
Position != 'n' And
Position != 'N' )
cout << "Invalid Answer\n";
} while( Position != 'y' And
Position != 'Y' And
Position != 'n' And
Position != 'N' );

return Position;
}

void NextExercise()
{
char LayOnBack;

cout << "Good. For the next exercise, you should lay on your back";
cout << "\nAre you laying on your back(1=Yes/0=No)? ";
cin >> LayOnBack;

if(LayOnBack == '0')
{
char Ready;

do {
cout << "Please lay on your back";
cout << "\nAre you ready(1=Yes/0=No)? ";
cin >> Ready;
}while(Ready == '0');
}
else if(LayOnBack == '1')
cout << "\nGreat.\nNow we will start the next exercise.";
else
cout << "\nWell, it looks like you are getting tired...";
}

int main()
{
char Position, WantToContinue;

Position = GetPosition();

if( Position == 'n' Or Position == 'N' )


cout << "\nCould you please sit down for the next exercise?";

© FunctionX, Inc. 60
C++ Fundamentals Chapter 9: Constructing Expressions

else
{
cout << "\nWonderful!\nNow we will continue today's exercise...\n";
cout << "\n...\n\nEnd of exercise\n";
}

cout << "\nDo you want to continue(1=Yes/0=No)? ";


cin >> WantToContinue;

if( WantToContinue == '1' )


NextExercise();
else if( WantToContinue == '0' )
cout << "\nWell, it looks like you are getting tired...";
else
{
cout << "\nConsidering your invalid answer...";
cout << "\nWe had enough today";
}
cout << "\nWe will stop the session now \nThanks.\n";

return 0;
}

Practical Learning: Conditions in Functions


1. Create a new project named Conditioner
2. Create a C++ source file named Exercise
3. To use conditions in functions, change the program as follows:
#include <iostream>
using namespace std;

#define OR ||
#define AND &&

enum TDrivingAnswer { daNo, daYes };

char CurrentLight()
{
char Light;

// Make sure the user enters a valid letter for a t raffic light
do {
cout << "What is the current light "
<< "color(g=Green/y=Yellow/r=Red)? ";
cin >> Light;

// The user typed an invalid color for the traffic light


if( Light != 'r' AND Light != 'R' AND
Light != 'y' AND Light != 'Y' AND
Light != 'g' AND Light != 'G' )
cout << "Invalid color\n";
} while( Light != 'r' AND Light != 'R' AND
Light != 'y' AND Light != 'Y' AND
Light != 'g' AND Light != 'G' );

return Light;
}

© FunctionX, Inc. 61
C++ Fundamentals Chapter 9: Constructing Expressions

void GreenLight()
{
cout << "\nThe light is green";
cout << "\nYou can proceed and drive through.\n";
}

void YellowLight()
{
int Timer = 0;

while(Timer < 5)
{
cout << Timer << ". Yellow Light - Be Careful!\n";
Timer++;
}

cout << "\nYellow light ended. Please Stop!!!\n";


}

void RedLight()
{
int Timer;

cout << "\nShow respect for the red light";


cout << "\nPlease Stop!!!\n";

for( Timer = 1; Timer < 60; ++Timer)


{
if( Timer < 10 )
cout << " " << Timer << ".Red ";
else
cout << Timer << ".Red ";

if( Timer % 10 == 0 )
cout << endl;
}

cout << "\n - Red light ended -\n\n";


}

char AreYouStillOnTheRoad()
{
char Ans;

cout << "\nAre you still on the road(y=Yes/n=No)? ";


cin >> Ans;

return Ans;
}

int main()
{
char Light;
int Timer;
char Answer;

do {
Light = CurrentLight();

© FunctionX, Inc. 62
C++ Fundamentals Chapter 9: Constructing Expressions

// Process a message depending on the current traffic light


if( Light == 'g' OR Light == 'G' )
GreenLight();
else if( Light == 'y' OR Light == 'Y' )
YellowLight();
else if( Light == 'r' OR Light == 'R' )
RedLight();
else
cout << endl << Light << " is not a valid color.\n";

Answer = AreYouStillOnTheRoad();
cout << endl;
} while((Answer == '1') OR (Answer == 'y') OR (Answer == 'Y') );

cout << "\nNice serving you\n\n";

return 0;
}
4. Test the program and return to development environment
5. Save your project.

1.3.2 Conditional Returns


A function defined other than void must always return a value. Sometimes, a function
will perform some tasks whose results would lead to different consequences. A function
can return only one value (this is true for this context, but we know that there are ways to
pass arguments so that a function can return more than one value) but you can make it
render a result depending on a particular behavior. Image that a function is requesting an
answer from the user. Since the user can provide different answers, you can treat each
result differently.

In the previous section, we saw an example of returning a value from a function.


Following our employment application, here is an example of a program that performs a
conditional return:

#include <iostream>
using namespace std;

bool GetAnswer()
{
char Ans; string Response;

cout << "Do you consider yourself a hot -tempered individual(y=Yes/n=No)? ";
cin >> Ans;

if( Ans == 'y' )


return true;
else
return false;
}

int main()
{
bool Answer;

© FunctionX, Inc. 63
C++ Fundamentals Chapter 9: Constructing Expressions

Answer = GetAnswer();

if( Answer == true )


{
cout << "\nThis job involves a high level of self-control.";
cout << "\nWe will get back to you.\n";
}
else
cout << "\nYou are hired!\n";

return 0;
}

Imagine you write the following function:

#include <iostream>
using namespace std;

#define Or ||
#define And &&

string GetPosition()
{
char Position;

cout << "Are you sitting down now(y/n)? ";


cin >> Position;

if( Position == 'y' Or Position == 'Y' )


return "Yes";
else if( Position == 'n' Or Position == 'N' )
return "No";
}

int main()
{
string Answer;

Answer = GetPosition();
cout << "\nAnswer = " << Answer;

return 0;
}

On paper, the function looks fine. If the user answers with y or Y, the function returns the
string Yes. If the user answer with n or N, the function returns the string No.
Unfortunately, this function has a problem: what if there is an answer that does not fit
those we are expecting? In reality the values that we have returned in the function
conform only to the conditional statements and not to the function. Remember that in
if(Condidion)Statement;, the Statement executes only if the Condition is true. Here is
what will happen. If the user answers y or Y, the function returns Yes and stops; fine, it
has returned something, we are happy. If the user answers n or N, the function returns
No, which also is a valid value: wonderful. If the user enters another value (other than y,
Y, n, or N), the execution of the function will not execute any of the return statements
and will not exit. This means that the execution will reach the closing curly bracket
without encountering a return value. Therefore, the compiler will issue a warning.
Although the warning looks like not a big deal, you should take care of it: never neglect

© FunctionX, Inc. 64
C++ Fundamentals Chapter 9: Constructing Expressions

warnings. The solution is to provide a return value so that, if the execution reaches the
end of the function, it would still return something. Here is a solution to the problem:

string GetPosition()
{
char Position;

cout << "Are you sitting down now(y/n)? ";


cin >> Position;

if( Position == 'y' Or Position == 'Y' )


return "Yes";
else if( Position == 'n' Or Position == 'N' )
return "No";

// If you reach here, it means no valid answer was provided.


// Therefore
return "Invalid Answer";
}

Here is an example from running the program:

Are you sitting down now(y/n)? w

Answer = Invalid Answer

This is illustrated in the following program that has two functions with conditional
returns:

#include <iostream>
using namespace std;

#define Or ||
#define And &&

char GetPosition()
{
char Position;

do {
cout << "Are you sitting down now(y/n)? ";
cin >> Position;

if( Position != 'y' And


Position != 'Y' And
Position != 'n' And
Position != 'N' )
cout << "Invalid Answer\n";
} while(Position != 'y' And
Position != 'Y' And
Position != 'n' And
Position != 'N' );

if( Position == 'y' Or Position == 'Y' )


return 'y';
else if( Position == 'n' Or Position == 'N' )
return 'n';

© FunctionX, Inc. 65
C++ Fundamentals Chapter 9: Constructing Expressions

// If you reach this point, none of the answers was valid


return Position;
}

void NextExercise()
{
char LayOnBack;

cout << "Good. For the next exercise, you should lay on your back";
cout << "\nAre you laying on your back(1=Yes/0=No)? ";
cin >> LayOnBack;

if(LayOnBack == '0')
{
char Ready;

do {
cout << "Please lay on your back";
cout << "\nAre you ready(1=Yes/0=No)? ";
cin >> Ready;
} while(Ready == '0');
}
else if(LayOnBack == '1')
cout << "\nGreat.\nNow we will start the next exercise.";
else
cout << "\nWell, it looks like you are getting tired...";
}

bool ValidatePosition(char Pos)


{
if( Pos == 'y' Or Pos == 'Y' )
return true;
else if( Pos == 'n' Or Pos == 'N' )
return false;

// If you reached this point, something was not valid


return false;
}

int main()
{
char Position, WantToContinue;
bool SittingDown;

Position = GetPosition();
SittingDown = ValidatePosition(Position);

if( SittingDown == false )


cout << "\nCould you please sit down for the next exercise?";
else
{
cout << "\nWonderful!\nNow we will continue today's exercise...\n";
cout << "\n...\n\nEnd of exercise\n";
}

cout << "\nDo you want to continue(1=Yes/0=No)? ";


cin >> WantToContinue;

if( WantToContinue == '1' )

© FunctionX, Inc. 66
C++ Fundamentals Chapter 9: Constructing Expressions

NextExercise();
else if( WantToContinue == '0' )
cout << "\nWell, it looks like you are getting tired...";
else
{
cout << "\nConsidering your invalid answer...";
cout << "\nWe had enough today";
}

cout << "\nWe will stop the session now \nThanks.\n";

return 0;
}

Practical Learning: Functions and Conditional Returns


1. To implement a function that conditionally returns a value, modify the program as
follows:
#include <iostream>
using namespace std;

#define OR ||
#define AND &&

enum TDrivingAnswer { daNo, daYes };

char CurrentLight()
{
...
}

void GreenLight()
{
...
}

void YellowLight()
{
...
}

void RedLight()
{
...
}

bool AreYouStillOnTheRoad()
{
int Ans;

cout << "\nAre you still on the road(0=No/1=Yes)? ";


cin >> Ans;

if( Ans == 0 )
return false;
else if( Ans == 1 )
return true;

© FunctionX, Inc. 67
C++ Fundamentals Chapter 9: Constructing Expressions

// If you got so far, something went wrong, therefore, return false


return false;
}

int main()
{
char Light;
int Timer;
int Answer;

do {
Light = CurrentLight();

// Process a message depending on the current traffic light


if( Light == 'g' || Light == 'G' )
GreenLight();
else if( Light == 'y' || Light == 'Y' )
YellowLight();
else if( Light == 'r' || Light == 'R' )
RedLight();
else
cout << endl << Light << " is not a valid color.\n";

Answer = AreYouStillOnTheRoad();
cout << endl;
} while(Answer == 1);

cout << "\nNice serving you";


return 0;
}
2. Test the program and return to development environment
3. To conditionally return an enumerator from a function, change the program as
follows:
#include <iostream>
using namespace std;

#define OR ||
#define AND &&

enum TDrivingAnswer { daNo, daYes };


enum TTrafficColor { tcRed, tcYellow, tcGreen, tcNoColor };

TTrafficColor CurrentLight()
{
char Light;

cout << "What is the current light "


<< "color(g=Green/y=Yellow/r=Red)? ";
cin >> Light;

if( Light == 'r' || Light == 'R' )


return tcRed;
else if( Light == 'y' || Light == 'Y' )
return tcYellow;
else if( Light == 'g' || Light == 'G' )
return tcGreen;

© FunctionX, Inc. 68
C++ Fundamentals Chapter 9: Constructing Expressions

return tcNoColor;
}

void GreenLight()
{
...
}

void YellowLight()
{
...
}

void RedLight()
{
...
}

bool AreYouStillOnTheRoad()
{
...
}

int main()
{
TTrafficColor Light;
int Timer;
int Answer;

do {
Light = CurrentLight();

switch( Light )
{
case tcRed:
RedLight();
break;

case tcYellow:
YellowLight();
break;

case tcGreen:
GreenLight();
break;
}

Answer = AreYouStillOnTheRoad();
cout << endl;
} while(Answer == 1);

cout << "\nNice serving you\n\n";


return 0;
}
4. Test the program and return to development environment.
5. Save your project.

© FunctionX, Inc. 69
C++ Fundamentals Chapter 9: Constructing Expressions

Chapter 12:
Introduction to Classes

? Classes: An Introduction

? Classes and Methods

© FunctionX, Inc. 70
C++ Fundamentals Chapter 12: Introduction to Clases

12.1 Classes: An Introduction


The data types we have applied so far to our variables were used to identify individual
items. To create more advanced and complete objects, C++ allows you to group a series
of variables and/or functions and create a newly defined object.

12.1.1 Introduction to Classes


An object, such as a CD Player, a printer, a car, etc, is built from assembling various
parts. In the same way, C++ allows you to group various variables and create a new
object called a class.

Imagine a company that rent cars hires you to write a program that would help process
customers orders. A car is recognized by some characteristics such as the number of door,
the type of transmission, etc. The variables that characterize such an object could be:

long SerialNumber;
int NumberOfDoors;
int Year;
char Transmission;
bool AirCondit ion;
bool CDRom;

And the program that defines a shoe box object could be:

#include <iostream>
using namespace std;

int main ()
{
long SerialNumber = 284402;
char Make[] = "Ford";
char Model[] = "Focus";
int NumberOfDoors = 4;
int Year = 2002;
char Transmission[] = "Automatic";
bool AirCondition = true;
bool CDRom = true;
double Rate = 24.95;

cout << "Car Characteristics";


cout << "\nCar #: " << SerialNumber;
cout << "\nMake: " << Make;
cout << "\nModel: " << Model;
cout << "\nDoors: " << NumberOfDoors;
cout << "\nYear: " << Year;
cout << "\nTransmision: " << Transmission;
cout << "\nA/C: " << AirCondition;
cout << "\nCD-Rom: " << CDRom;
cout << "\nRate: $" << Rate;

cout << "\n\n";


return 0;
}

© FunctionX, Inc. 71
C++ Fundamentals Chapter 12: Introduction to Clases

The program would produce:

Car Characteristics
Car #: 284402
Make: Ford
Model: Focus
Doors: 4
Year: 2002
Transmision: Automatic
A/C: 1
CD-Rom: 1
Rate: $24.95

Unless dealing with one car, this program would be rudimentary to run for each object.
The solution is to create an object called car that groups everything that characterizes the
object.

Practical Learning: Introducing Objects


1. Create a new project named Employees and save the first file as Main. Save the
project as Employees
2. Change the contents of the file as follows:
#include <iostream>
#include <string>
using namespace std;

int main()
{
string FirstName = "Bertine";
string LastName = "Lamond";
double TotalHours = 36.50;
double HourlySalary = 8.52;
double WeeklySalary = TotalHours * HourlySalary;

cout << "Information about the employee";


cout << "\n\tEmployee Name: " << FirstName << " " << LastName;
cout << "\n\tWeekly Hours: " << TotalHours;
cout << "\n\tHourly Salary: $" << HourlySalary;
cout << "\n\tWeekly Salary: $" << WeeklySalary;

return 0;
}

3. Test the program. It would produce:

Information about the employee


Employee Name: Bertine Lamond
Weekly Hours: 36.5
Hourly Salary: $8.52
Weekly Salary: $310.98

4. Return to your programming environment


5. To request the values of the variables, change the program as follows:
#include <iostream>
#include <string>
using namespace std;

© FunctionX, Inc. 72
C++ Fundamentals Chapter 12: Introduction to Clases

int main()
{
string FirstName;
string LastName;
double TotalHours, HourlySalary, WeeklySalary;

cout << "Enter the following pieces of information about the employee\n";
cout << "First Name: ";
cin >> FirstName;
cout << "Last Name: ";
cin >> LastName;
cout << "Hours worked this week: ";
cin >> TotalHours;
cout << "Hourly Salary: $";
cin >> HourlySalary;

WeeklySalary = TotalHours * HourlySalary;

cout << "\nInformation about the employee";


cout << "\nEmployee Name: " << FirstName << " " << LastName;
cout << "\nWeekly Hours: " << TotalHours;
cout << "\nHourly Salary: $" << HourlySalary;
cout << "\nWeekly Salary: $" << WeeklySalary;

cout << "\n\n";


return 0;
}

6. Test the program:

Enter the following pieces of information about the employee


First Name: Alain
Last Name: Browns
Hours worked this week: 35.50
Hourly Salary: $12.20

Information about the employee


Employee Name: Alain Browns
Weekly Hours: 35.5
Hourly Salary: $12.2
Weekly Salary: $433.1

7. Return to your programming environment

12.1.2 Creating a Class


To create a class, use the class keyword followed by a name for the object. Like any
other declared variable, the class declaration ends with a semi -colon. The name of a class
follows the rules we have applied so far for variable and function names. To declare a
class called TCar, we would type the following:

class TCar;

As a name that represents a group of items, a class has a body that would be used to
define the items that compose it. The body of a class starts with an opening curly bracket
"{" and ends with a closing curly bracket "}". Therefore, another way to create a class is:

© FunctionX, Inc. 73
C++ Fundamentals Chapter 12: Introduction to Clases

class ClassName{};

This could also be created as:

class ClassName {
};

or

class ClassName
{
};

Either of these techniques produces the same effect.

Since a class is built from combining other objects, you will list each variable inside of
the body of the class. Each item that composes the class is represented as a complete
variable declared with a data type and a name. As a variable, each declaration must end
with a semi-colon.

Continuing with our TCar object, we could create it using the class as follows:

class TCar
{
public:
long SerialNumber;
char Make;
char Model;
int NumberOfDoors;
int Year;
char Transmission;
bool AirCondition;
bool CDRom;
double Rate;
};

The items that compose a class are called members of the class.

Practical Learning: Creating a Class


1. To add a class to our exercise, change the contents of the file as follows:

#include <iostream>
using namespace std;

class Employee
{
string FirstName;
string LastName;
double TotalHours;
double HourlySalary;
double WeeklySalary;
};

int main()
{
return 0;

© FunctionX, Inc. 74
C++ Fundamentals Chapter 12: Introduction to Clases

2. Test the program


3. As you can see, the program does not do much. Press any key to return to your
programming environment

12.1.3 Accessing a Class


A common object in real life is visibly made of two categories of parts: those you can see
or touch and those you do not have access to. The parts you can see or touch are
considered visible or accessible. In C++, such parts are referred to as public. Those you
cannot see or touch are considered hidden. In C++, such parts are referred to as private.
Like objects in real life, a class is made of sections that the other functions or other
objects cannot “see” and those the other objects can access. The other objects of of the
program are sometimes referred to as the clients of the object. The parts the client of an
object can touch in a class are considered public and the others are private.

When creating a class, you will define which items are public and which ones are private.
The items that are public are created in a section that starts with the public keyword
followed by a semi-colon. The others are in the private section. If you do not specify
these sections, all of the members of a class are considered private . For example, all of
the members of the previously defined TCar class are private.

Using the public and private sections, our TCar object can be created as:

class TCar
{
public:
long SerialNumber;
char Make;
char Model;
int NumberOfDoors;
int Year;
private:
char Transmission;
bool AirCondition;
bool CDRom;
double Rate;
};

The public and private keywords are referenced by their access level because they
control how much access a variable allows. You can create as many public sections or as
many private sections as you want. For example, the above class could be created as:

class TCar
{
public:
long SerialNumber;
char Make;
char Model;
public:
int NumberOfDoors;
int Year;
private:
char Transmission;
bool AirCondition;

© FunctionX, Inc. 75
C++ Fundamentals Chapter 12: Introduction to Clases

bool CDRom;
public:
double Rate;
};

When creating a class with different public and private sections, all of the declared
variables under an access level keyword abide by the rules of that access level. The fact
that you use different public sections does not by any means warrant different public
levels to the variables. A variable declared as public in one public section has the same
public level of access as any other variable that is declared in another public section.

A variable that is declared in a class is called a member of the class. Once the class has
been defined, you can use it as an individual variable.

Practical Learning: Accessing a Class


??To add access levels to our class, change the class definition as follows:

class TEmployee
{
public:
string FirstName;
string LastName;
double TotalHours;
double HourlySalary;
double WeeklySalary;
};

12.1.4 Declaring a Class


After defining a class, you can declare it as a variable using the same syntax we have
used for any other variable. A class is declared using its name followed by a name for the
defined variable and ending with a semi -colon. For example, our TCar class can be
declared as follows:

TCar Rental;

When an object has been declared, you can access any of its members using the member
access operator ".". First, type the name of the object variable, followed by a period,
followed by the name of the member you want to access. For example, to access the
member NumberOfDoors of the above class, you would write:

Car.NumberOfDoors;

Using this syntax, you can display the value of a class member:

cout << Car.NumberOfDoors;

or you can request its value from the user, using the cin extractor. Here is an example:

cin >> Car.NumberOfDoors;

Using the cout extractor to display the values of the object members, our program could
be as follows:

© FunctionX, Inc. 76
C++ Fundamentals Chapter 12: Introduction to Clases

#include <iostream>
using namespace std;

class TCar
{
public:
long SerialNumber;
char Make;
char Model;
int NumberOfDoors;
int Year;
char Transmission;
bool AirCondition;
bool CDRom;
double Rate;
};

int main ()
{
TCar Car;

Car.SerialNumber = 284402;
Car.Make = 'F';
Car.Model = 'F';
Car.NumberOfDoors = 4;
Car.Year = 2002;
Car.Transmission = 'A';
Car.AirCondition = true;
Car.CDRom = true;
Car.Rate = 24.95;

cout << "Car Characteristics";


cout << "\nCar #: " << Car.SerialNumber;
cout << "\nMake: " << Car.Make;
cout << "\nModel: " << Car.Model;
cout << "\nDoors: " << Car.NumberOfDoors;
cout << "\nYear: " << Car.Year;
cout << "\nTransmision: " << Car.Transmission;
cout << "\nA/C: " << Car.AirCondition;
cout << "\nCD-Rom: " << Car.CDRom;
cout << "\nRate: $" << Car.Rate;

cout << "\n\n";


return 0;
}

At this time, we have not learned how to use arrays in a class, we include simple char
variables. Because on this, we can transform the above program using the conditional
operator as follows:

#include <iostream>
using namespace std;

class TCar
{
public:
long SerialNumber;
char Make;

© FunctionX, Inc. 77
C++ Fundamentals Chapter 12: Introduction to Clases

char Model;
int NumberOfDoors;
int Year;
char Transmission;
bool AirCondition;
bool CDRom;
double Rate;
};

int main ()
{
TCar Car;

Car.SerialNumber = 284402;
Car.Make = 'F';
Car.Model = 'F';
Car.NumberOfDoors = 4;
Car.Year = 2002;
Car.Transmission = 'A';
Car.AirCondition = true;
Car.CDRom = true;
Car.Rate = 24.95;

cout << "Car Characteristics";


cout << "\nCar #: " << Car.SerialNumber;
cout << "\nMake: ";
Car.Make == 'F' ? cout << "Ford" : cout << "Unknown";
cout << "\nModel: ";
Car.Model == 'F' ? cout << "Focus" : cout << "Unknown";
cout << "\nDoors: " << Car.NumberOfDoors;
cout << "\nYear: " << Car.Year;
cout << "\nTransmision: ";
Car.Transmission == 'A' ? cout << "Automatic" : cout << "Manual";
cout << "\nA/C: ";
Car.AirCondition == true ? cout << "Yes" : cout << "No";
cout << "\nCD-Rom: ";
Car.CDRom == true ? cout << "Yes" : cout << "No";
cout << "\nRate: $" << Car.Rate;

cout << "\n\n";


return 0;
}

Practical Learning: Declaring a Class


1. Declare an employee object and initialize its members as follows:

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

class TEmployee
{
...
};

int main()

© FunctionX, Inc. 78
C++ Fundamentals Chapter 12: Introduction to Clases

{
TEmployee FullTime;

FullTime.FirstName = "Chester";
FullTime.LastName = "Stanley";
FullTime.TotalHours = 42.00;
FullTime.HourlySalary = 10.63;

FullTime.WeeklySalary = FullTime.TotalHours * FullTime.HourlySalary;

cout << "Information about the employee";


cout << "\nEmployee Name: " << FullTime.FirstName << " "
<< FullTime.LastName;
cout << "\nWeekly Hours: " << FullTime.TotalHours;
cout << "\nHourly Salary: $" << FullTime.HourlySalary;
cout << "\nWeekly Salary: $" << FullTime.WeeklySalary;

cout << "\n\n";


return 0;
}

2. Test the program:


Information about the employee
Full Name: Chester Stanley
Total Weekly Hours: 42.00
Hourly Salary: $10.63
Weekly Salary: $446.46

3. Return to your programming environment


4. To request the values of the members of a class, change the file as follows:

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

class TEmployee
{
public:
string FirstName;
string LastName;
double TotalHours;
double HourlySalary;
double WeeklySalary;
};

int main()
{
TEmployee FullTime;

cout << "Enter the following pieces of information about the employee\n";
cout << "First Name: ";
cin >> FullTime.FirstName;
cout << "Last Name: ";
cin >> FullTime.LastName;
cout << "Hours worked this week: ";
cin >> FullTime.TotalHours;
cout << "Hourly Salary: $";

© FunctionX, Inc. 79
C++ Fundamentals Chapter 12: Introduction to Clases

cin >> FullTime.HourlySalary;

FullTime.WeeklySalary = FullTime.TotalHours * FullTime.HourlySalary;

cout << "\nInformation about the employee";


cout << "\nEmployee Name: " << FullTime.FirstName << " "
<< FullTime.LastName;
cout << "\nWeekly Hours: " << FullTime.TotalHours;
cout << "\nHourly Salary: $" << FullTime.HourlySalary;
cout << "\nWeekly Salary: $" << FullTime.WeeklySalary;

cout << "\n\n";


return 0;
}
5. Test the program:
Enter the following pieces of information about the employee
First Name: Marlyse
Last Name: Dietch
Hours worked this week: 42.50
Hourly Salary: $10.85

Information about the employee


Employee Name: Marlyse Dietch
Weekly Hours: 42.5
Hourly Salary: $10.85
Weekly Salary: $461.125
6. Return to your programming environment
7. To calculate the value of a member using values from external variables, change the
file as follows:
#include <iostream>
#include <string>
using namespace std;

class TEmployee
{
public:
string FirstName;
string LastName;
double TotalHours;
double HourlySalary;
double WeeklySalary;
};

int main()
{
TEmployee Employee;
// Hours for each day
double Mon, Tue, Wed, Thu, Fri, Sat, Sun;

cout << "Enter the following pieces of information about this employee\n";
cout << "First Name: "; cin >> Employee.FirstName;
cout << "Last Name: "; cin >> Employee.LastName;
cout << "Hourly Salary: $"; cin >> Employee.HourlySalary;
cout << "Enter the number of hours for each day\n";
cout << "Monday: "; cin >> Mon;
cout << "Tuesday: "; cin >> Tue;

© FunctionX, Inc. 80
C++ Fundamentals Chapter 12: Introduction to Clases

cout << "Wednesday: "; cin >> W ed;


cout << "Thursday: "; cin >> Thu;
cout << "Friday: "; cin >> Fri;
cout << "Saturday: "; cin >> Sat;
cout << "Sunday: "; cin >> Sun;

Employee.TotalHours = Mon + Tue + Wed + Thu + Fri + Sat + Sun;;


Employee.WeeklySalary = Employee.TotalHours * Employee.HourlySalary;

cout << "\nInformation about the employee";


cout << "\nEmployee Name: " << Employee.FirstName << " "
<< Employee.LastName;
cout << "\nWeekly Hours: " << Employee.TotalHours;
cout << "\nHourly Salary: $" << Employee.HourlySalary;
cout << "\nWeekly Salary: $" << Employee.WeeklySalary;

cout << "\n\n";


return 0;
}

8. Test the program. Here is an example:

Enter the following pieces of information about this employee


First Name: Theodore
Last Name: Amis
Hourly Salary: $8.95
Enter the number of hours for each day
Monday: 8.00
Tuesday: 8.50
Wednesday: 9.00
Thursday: 8.00
Friday: 8.00
Saturday: 0
Sunday: 0

Information about the employee


Employee Name: Theodore Amis
Weekly Hours: 41.5
Hourly Salary: $8.95
Weekly Salary: $371.425
9. Return to your programming environment
10. When the user is typing the amount of hours for each day, you should make sure that
entries such –8.00 or 25 are not allowed because the user cannot work for negative
hours, and the user cannot work more than 24 hour in one day.
To take care of this situation, implementation a function that would use a conditional
statement to control what the user type. Consequently, you can change the
implementation of the main() function:

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

class TEmployee
{
public:
string FirstName;
string LastName;

© FunctionX, Inc. 81
C++ Fundamentals Chapter 12: Introduction to Clases

double TotalHours;
double HourlySalary;
double WeeklySalary;
};

double ObtainDailyHours(string s)
{
double h;

do {
cout << s << ": ";
cin >> h;
if(h < 0 || h > 24)
cout << "Please enter a number between 0.00 and 24.00\n";
}while(h < 0 || h > 24);

return h;
}

int main()
{
TEmployee Employee;
// Hours for each day
double Mon, Tue, Wed, Thu, Fri, Sat, Sun;

cout << "Enter the following pieces of information about this employee\n";
cout << "First Name: "; cin >> Employee.FirstName;
cout << "Last Name: "; cin >> Employee.LastName;
cout << "Hourly Salary: $"; cin >> Employee.HourlySalary;
cout << "Enter the number of hours for each day\n";
Mon = ObtainDailyHours("Monday");
Tue = ObtainDailyHours("Tuesday");
Wed = ObtainDailyHours("Wednesday");
Thu = ObtainDailyHours("Thursday");
Fri = ObtainDailyHours("Friday");
Sat = ObtainDailyHours("Saturday");
Sun = ObtainDailyHours("Sunday");

Employee.TotalHours = Mon + Tue + Wed + Thu + Fri + Sat + Sun;;

Employee.WeeklySalary = Employee.TotalHours * Employee.HourlySalary;

cout << "\nInformation about the employee";


cout << "\nEmployee Name: " << Employee.FirstName << " "
<< Employee.LastName;
cout << "\nWeekly Hours: " << Employee.TotalHours;
cout << "\nHourly Salary: $" << Employee.HourlySalary;
cout << "\nWeekly Salary: $" << Employee.WeeklySalary;

cout << "\n\n";


return 0;
}

11. Test the program to make sure it is working. Here is an example:

Enter the following pieces of information about this employee


First Name: Paul
Last Name: Kitts
Hourly Salary: $10.25

© FunctionX, Inc. 82
C++ Fundamentals Chapter 12: Introduction to Clases

Enter the number of hours for each day


Monday: 8.00
Tuesday: -5
Please enter a number between 0.00 and 24.00
Tuesday: 8.00
Wednesday: 9.50
Thursday: 8.00
Friday: 8.50
Saturday: 26
Please enter a number between 0.00 and 24.00
Saturday: 0
Sunday: 0

Information about the employee


Employee Name: Paul Kitts
Weekly Hours: 42
Hourly Salary: $10.25
Weekly Salary: $430.5
12. Return to your programming environment
13. Whenever doing a payroll, something you should always pay attention to is the
calculation of overtime if the employee has worked more than 40 hours in a week.
Add the following commented function to take care of calculating weekly gross pay
in factor of possible overtime:

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

class TEmployee
{
public:
string FirstName;
string LastName;
double TotalHours;
double HourlySalary;
double WeeklySalary;
};

double ObtainDailyHours(string s)
{
double h;

do {
cout << s << ": ";
cin >> h;
if(h < 0 || h > 24)
cout << "Please enter a number between 0.00 and 24.00\n";
}while(h < 0 || h > 24);

return h;
}

double CalcGrossPay(const double Hours, const double Salary)


{
// If there is no overtime, return a regular salary
if( Hours <= 40 )
return Hours * Salary;

© FunctionX, Inc. 83
C++ Fundamentals Chapter 12: Introduction to Clases

else // if( Hours > 40 )


{
// For an overtime period, regular hours = 40
const double RegularHours = 40.00;

double RegularSalary = RegularHours * Salary;

// Hourly overtime salary is calculated by adding half


// of the salary to the regular hourly salary
double OvertimeSalary = Salary + (Salary * 0.50);

// The overtime is anything above 40 hours


double OvertimeHours = Hours - RegularHours;

// To calculate the overtime salary, multiply the overtime


// hours by the overtime salary
double OvertimeGross = OvertimeHours * OvertimeSalary;

// Now we have the regular salary and the overtime wage


// Simply add them to get the gross weekly earnings
return RegularSalary + OvertimeGross;
}
}

int main()
{
TEmployee Employee;
// Hours for each day
double Mon, Tue, Wed, Thu, Fri, Sat, Sun, Total;
double Hourly;

cout << "Enter the following pieces of information about this employee\n";
cout << "First Name: "; cin >> Employee.FirstName;
cout << "Last Name: "; cin >> Employee.LastName;
cout << "Hourly Salary: $"; cin >> Employee.HourlySalary;
cout << "Enter the number of hours for each day\n";
Mon = ObtainDailyHours("Monday");
Tue = ObtainDailyHours("Tuesday");
Wed = ObtainDailyHours("Wednesday");
Thu = ObtainDailyHours("Thursday");
Fri = ObtainDailyHours("Friday");
Sat = ObtainDailyHours("Saturday");
Sun = ObtainDailyHours("Sunday");

Total = Mon + Tue + Wed + Thu + Fri + Sat + Sun;


Employee.TotalHours = Total;
Hourly = Employee.HourlySalary;
Employee.WeeklySalary = CalcGrossPay(Total, Hourly);

cout << "Information about the employee";


cout << "\nEmployee Name: " << Employee.FirstName << " "
<< Employee.LastName;
cout << "\nWeekly Hours: " << Employee.TotalHours;
cout << "\nHourly Salary: $" << Employee.HourlySalary;
cout << "\nWeekly Salary: $" << Employee.WeeklySalary;

cout << "\n\n";


return 0;
}

© FunctionX, Inc. 84
C++ Fundamentals Chapter 12: Introduction to Clases

14. Test the program twice to make sure it behaves appropriately. Test it once with less
than 40 hours; test it again with overtime.
15. Return to your programming environment

12.1.5 Techniques of Initializing a Class


There are various techniques used to initialize a class: initializing individual members or
initializing the class as a whole.

To initialize a member of a class, access it and assign it an appropriate value as we did


above:

#include <iostream>
using namespace std;

class TCar
{
public:
...
};

int main ()
{
TCar Car;

Car.SerialNumber = 284402;
Car.Make = 'F';
Car.Model = 'F';
Car.NumberOfDoors = 4;
Car.Year = 2002;
Car.Transmission = 'A';
Car.AirCondition = true;
Car.CDRom = true;
Car.Rate = 24.95;
...
return 0;
}

You can also initialize an object as a variable. This time, type the name of the variable
followed by the assignment operator, followed by the desired values of the variables
listed between an opening and a closing curly brackets; each value is separated with a
comma. The first rule you must follow is that the list of variables must follow the order of
the declared members of the class. The second rule you must observe is that none of the
members of the class must be another class:

#include <iostream>
using namespace std;

class TCar
{
public:
long SerialNumber;
char Make;
char Model;
int NumberOfDoors;
int Year;

© FunctionX, Inc. 85
C++ Fundamentals Chapter 12: Introduction to Clases

char Transmission;
bool AirCondition;
bool CDRom;
double Rate;
};

int main ()
{
TCar Car = { 62376, 'g', 'm', 2, 1998, 'm', false, false, 19.95 };

cout << "Car Characteristics";


cout << "\nCar #: " << Car.SerialNumber;
cout << "\nMake: ";
switch(Car.Make)
{
case 'f':
case 'F':
cout << "Ford";
break;
case 'g':
case 'G':
cout << "Geo";
break;
default:
cout << "Unknown";
}
cout << "\nModel: ";
switch(Car.Model)
{
case 'f':
case 'F':
cout << "Focus";
break;
case 'm':
case 'M':
cout << "Metro";
break;
default:
cout << "Unknown";
}
cout << "\nDoors: " << Car.NumberOfDoors;
cout << "\nYear: " << Car.Year;
cout << "\nTransmision: ";
Car.Transmission == 'A' ? cout << "Automatic" : cout << "Manual";
cout << "\nA/C: ";
Car.AirCondition == true ? cout << "Yes" : cout << "No";
cout << "\nCD-Rom: ";
Car.CDRom == true ? cout << "Yes" : cout << "No";
cout << "\nRate: $" << Car.Rate;

cout << "\n\n";


return 0;
}

When initializing a class that contains other classes, as we will learn when studying
composition, you cannot use the above square brackets, each class that is a member of
your object must be initialized separately.

© FunctionX, Inc. 86
C++ Fundamentals Chapter 12: Introduction to Clases

12.2 Classes and Methods


The primary motivation of using classes in a program is to create objects as complete as
possible. An object must be able to handle its own business so that the other objects of
the program or of another program would only need to know which object can take care
of a particular need they have.

A regular variable, as a member of an object, cannot handle assignments; this job is


handled by functions declared as members of a class.

A function that is a member of a class is also called a method. Therefore, in this book, the
word “method”, when associate with a class, refers to a function that is a member of that
class.

12.2.1 Declaring Methods


As a member of an object, a method is declared like any of the functions we
have used so far; it could or could not return a value.

Imagine you have a box, you know its dimensions and want to get its total
area and possibly its volume. From what we have learned so far, you can
create its class as follows:

class TBox
{
public:
double Length;
double Width;
double Height;
};

To calculate its area and volumne, you can include some member functions. Our object,
when including methods could be structured as follows:

class TBox
{
public:
double Length;
double Width;
double Height;
void TotalArea();
void Volume();
};

When using methods on a class, the variables are used to hold or store values, called data,
of the object, while methods are used to perform assignments related to the object. One
way you can control the data held by variables is to hide data from the "external world".
To achieve this, you should declare the member variables in the private section. After
doing this, use the methods in the public section to help the class interact with the other
objects or functions of the program. Based on this, our TBox object would look like this:

class TBox
{
private:
double Length;
double Width;

© FunctionX, Inc. 87
C++ Fundamentals Chapter 12: Introduction to Clases

double Height;
public:
void TotalArea();
void Volume();
};

There are at least two techniques you can use to implement a method member

Practical Learning: Adding Methods to an Object


??To add methods to our project, change the contents of the file as follows:

classTEmployee
{
public:
void IdentifyEmployee();
void GetHourlySalary();
void CalcTotalHours();
void CalcGrossPay();
void Display();
private:
string FirstName;
string LastName;
double TotalHours;
double HourlySalary;
double GrossPay;
};

12.2.2 Implementing Methods Locally


To implement a method in the class where it is declared, use the same techniques we used
to define regular functions. When a method is a class' member, it has access to the
member variables of the same class; this means you do not need to pass the variables as
arguments (there are cases when you will need to); you can just use any of them as if it
were supplied. Here is how you would define the Volume() method inside of the TBox
class:

class TBox
{
private:
double Length;
double Width;
double Height;
public:
double TotalArea();
double Volume()
{
return Length * Width * Height;
}
};

If your class has a lot of methods, this technique could be cumbersome. You should use it
only for small methods.

© FunctionX, Inc. 88
C++ Fundamentals Chapter 12: Introduction to Clases

Practical Learning: Implementing Methods Locally


1. To implement methods locally, change the contents of the class as follows:

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

double ObtainDailyHours(string s);

class TEmployee
{
public:
void Ident ifyEmployee()
{
cout << "Identify the Employee\n";
cout << "First Name: ";
cin >> FirstName;
cout << "Last Name: ";
cin >> LastName;
}
void GetHourlySalary()
{
cout << "Hourly Salary: $";
cin >> HourlySalary;
}
void CalcTotalHours()
{
// Hours for each day
double Mon, Tue, Wed, Thu, Fri, Sat, Sun;

cout << "Enter the number of hours for each day\n";


Mon = ObtainDailyHours("Monday");
Tue = ObtainDailyHours("Tuesday");
Wed = ObtainDailyHours("Wednesday");
Thu = ObtainDailyHours("Thursday");
Fri = ObtainDailyHours("Friday");
Sat = ObtainDailyHours("Saturday");
Sun = ObtainDailyHours("Sunday");

TotalHours = Mon + Tue + Wed + Thu + Fri + Sat + Sun;


}
void CalcGrossPay()
{
// If there is no overtime, return a regular salary
if( TotalHours <= 40 )
WeeklySalary = TotalHours * HourlySalary;
else // if( Hours > 40 )
{
// For an overtime period, regular hours = 40
const double RegularHours = 40.00;

double RegularSalary = RegularHours * HourlySalary;

// Hourly overtime salary is calculated by adding half


// of the salary to the regular hourly salary
double OvertimeSalary = HourlySalary + (HourlySalary *
0.50);

© FunctionX, Inc. 89
C++ Fundamentals Chapter 12: Introduction to Clases

// The overtime is anything above 40 hours


double OvertimeHours = TotalHours - RegularHours;

// To calculate the overtime salary, multiply the overtime


// hours by the overtime salary
double OvertimeGross = OvertimeHours * OvertimeSalary;

// Now we have the regular salary and the overtime wage


// Simply add them to get the gross weekly earnings
WeeklySalary = RegularSalary + OvertimeGross;
}
}
void Display()
{
cout << "Information about the employee";
cout << "\nEmployee Name: " << FirstName << " "
<< LastName;
cout << "\nWeekly Hours: " << TotalHours;
cout << "\nHourly Salary: $" << HourlySalary;
cout << "\nWeekly Salary: $" << WeeklySalary;
}
private:
string FirstName;
string LastName;
double TotalHours;
double HourlySalary;
double WeeklySalary;
};

double ObtainDailyHours(string s)
{
double h;

do {
cout << s << ": ";
cin >> h;
if(h < 0 || h > 24)
cout << "Please enter a number between 0.00 and 24.00\n";
}while(h < 0 || h > 24);

return h;
}

int main()
{
TEmployee Contractor;

Contractor.IdentifyEmployee();
Contractor.GetHourlySalary();
Contractor.CalcTotalHours();
Contractor.CalcGrossPay();
Contractor.Display();

cout << "\n\n";


return 0;
}
2. Test the program. Here is an example of running the program:
Enter the following pieces of information about this employee

© FunctionX, Inc. 90
C++ Fundamentals Chapter 12: Introduction to Clases

First Name: Jeanine


Last Name: Bliss
Hourly Salary: $14.55
Enter the number of hours for each day
Monday: 8
Tuesday: 9.50
Wednesday: 7.50
Thursday: 8.50
Friday: 8
Saturday: 0
Sunday: 0

Employee Payroll Information


Full Name: Jeanine Bliss
Total Weekly Hours: 41.5
Hourly Salary: $14.55
Weekly Salary: $614.74
3. Return to your programming environment

12.2.3 Implementing Methods Globally


When the methods execute long assignments, you should implement them outside of the
object by first accessing the desired function member of the class. To access a method of
a class when implementing it, instead of the member access operator “.”, you will use the
scope access operator represented as two colons ::

To implement a method outside of the class, provide the return type of the method,
followed by the class' name, followed by the scope access operator “::”, followed by the
method's name, followed by the arguments, if any, between parentheses, and finally
define what the function should do, in its body.

Another implementation of our Volume() method would be:

class TBox
{
private:
double Length;
double Width;
double Height;
public:
void TotalArea();
double Volume();
};

double TBox::Volume()
{
return Length * Width * Height;
}

Practical Learning: Implementing Methods Globally


1. To implement the methods globally, change the content of the file as follows:

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

© FunctionX, Inc. 91
C++ Fundamentals Chapter 12: Introduction to Clases

double ObtainDailyHours(string s);

class TEmployee
{
public:
void IdentifyEmployee();
void GetHourlySalary();
void CalcTotalHours();
void CalcGrossPay();
void Display();
private:
string FirstName;
string LastName;
double TotalHours;
double HourlySalary;
double WeeklySalary;
};

void TEmployee::IdentifyEmployee()
{
cout << "Identify the Employee\n";
cout << "First Name: ";
cin >> FirstName;
cout << "Last Name: ";
cin >> LastName;
}

void TEmployee::CalcTotalHours()
{
// Hours for each day
double Mon, Tue, Wed, Thu, Fri, Sat, Sun;

cout << "Enter the number of hours for each day\n";


Mon = ObtainDailyHours("Monday");
Tue = ObtainDailyHours("Tuesday");
Wed = ObtainDailyHours("Wednesday");
Thu = ObtainDailyHours("Thursday");
Fri = ObtainDailyHours("Friday");
Sat = ObtainDailyHours("Saturday");
Sun = ObtainDailyHours("Sunday");

TotalHours = Mon + Tue + Wed + Thu + Fri + Sat + Sun;


}

void TEmployee::GetHourlySalary()
{
cout << "Hourly Salary: $";
cin >> HourlySalary;
}

void TEmployee::CalcGrossPay()
{
// If there is no overtime, return a regular salary
if( TotalHours <= 40 )
WeeklySalary = TotalHours * HourlySalary;
else // if( Hours > 40 )
{
// For an overtime period, regular hours = 40
const double RegularHours = 40.00;

© FunctionX, Inc. 92
C++ Fundamentals Chapter 12: Introduction to Clases

double RegularSalary = RegularHours * HourlySalary;

// Hourly overtime salary is calculated by adding half


// of the salary to the regular hourly salary
double OvertimeSalary = HourlySalary + (HourlySalary * 0.50);

// The overtime is anything above 40 hours


double OvertimeHours = TotalHours - RegularHours;

// To calculate the overtime salary, multiply the overtime


// hours by the overtime salary
double OvertimeGross = OvertimeHours * OvertimeSalary;

// Now we have the regular salary and the overtime wage


// Simply add them to get the gross weekly earnings
WeeklySalary = RegularSalary + OvertimeGross;
}
}

void TEmployee::Display()
{
cout << "Information about the employee";
cout << "\nEmployee Name: " << FirstName << " "
<< LastName;
cout << "\nWeekly Hours: " << TotalHours;
cout << "\nHourly Salary: $" << HourlySalary;
cout << "\nWeekly Salary: $" << WeeklySalary;
}

double ObtainDailyHours(string s)
{
double h;

do {
cout << s << ": ";
cin >> h;
if(h < 0 || h > 24)
cout << "Please enter a number between 0.00 and 24.00\n";
}while(h < 0 || h > 24);

return h;
}

int main()
{
TEmployee Contractor;

Contractor.IdentifyEmployee();
Contractor.GetHourlySalary();
Contractor.CalcTotalHours();
Contractor.CalcGrossPay();
Contractor.Display();

cout << "\n\n";


return 0;
}

2. Test the program and return to your programming environment

© FunctionX, Inc. 93
C++ Fundamentals Chapter 12: Introduction to Clases

12.2.4 Inline Methods


When studying functions, we learned that an assignment can be carried where it is being
called. The same process can apply to a class’ member.

To declare a class’ method as inline, precede its name with the inline keyword when
declaring the method in the class:

class TBox
{
private:
double Length;
double W idth;
double Height;
public:
inline double TotalArea();
double Volume();
};

You can choose which methods would be inline and which ones would not. When
implementing the method, you can precede the method with the inline keyword. You can
also omit the inline keyword in the class but use it when defining the method.

If you decide to implement a method locally (in the class), you have the option of
implementing it as inline:

class TBox
{
private:
double Length;
double Width;
double Height;
public:
inline double TotalArea()
{
return (2 * (Length + Width))+
(2 * (Length + Height))+
(2 * (Width+Height));
}
double Volume();
};

On the other hand, if you omit the inline keyword, the compiler would take care of it.
Normally, any function implemented in the body of the class is considered inline.

Practical Learning: Using Inline Methods


1. To declare two new variables, in the private section of the class, type
double TaxAmount;
double NetPay;

2. To declare an inline method, in the public section of the class, type


bool inline IsMarried();
3. Implement the method as follows:

© FunctionX, Inc. 94
C++ Fundamentals Chapter 12: Introduction to Clases

bool inline Employee::IsMarried()


{
char Answer;

cout << "Are you married(y=Yes/n=No)? ";


cin >> Answer;

if( Answer == 'y' || Answer == 'Y' )


return true;
else
return false;
}

4. To create an implicit inline method, in the TEmployee class, implement the


following method:

class TEmployee
{
public:
...

void CalcTaxAmount()
{
if( IsMarried() == false )
TaxAmount = WeeklySalary * 30 / 100;
else
TaxAmount = WeeklySalary * 15 / 100;

NetPay = WeeklySalary - TaxAmount;


}

private:
...
};

5. Change the Display() method as follows:

void TEmployee::Display()
{
CalcTaxAmount();

cout << "Information about the employee";


cout << "\nEmployee Name: " << FirstName << " "
<< LastName;
cout << "\nWeekly Hours: " << TotalHours;
cout << "\nHourly Salary: $" << HourlySalary;
cout << "\nGross Salary: $" << WeeklySalary;
cout << "\nTax Amount: $" << TaxAmount;
cout << "\nNet Salary: $" << NetPay;
}

6. Test the program and return to your programming environment

© FunctionX, Inc. 95
C++ Fundamentals Chapter 12: Introduction to Clases

12.2.5 Class Members Interactions


Regardless of how the member methods of an object are implemented, any method can
call another without using an access operator. This allows an object’s methods to
exchange information among themselves easily. Furthermore, unlike regular functions
where a function must be declared prior to another function calling it, the method
members of a class do not abide by that rule: one method can call another method before
or after the other has been implemented, as long as it is defined somewhere.

Once an object is defined and behaves as complete as possible, the other functions or
objects of the program can make the appropriate calls trusting that the called object can
handle its assignments efficiently. This ability allows you to (tremendously) reduce the
work overload of the other components of a program.

The main() function can simply call the appropriate member of the TBox object now:

#include <iostream>
using namespace std;

class TBox
{
private:
double Length;
double Width;
double Height;
public:
void GetTheDimensions();
inline double TotalArea()
{
return (2 * (Length + W idth))+
(2 * (Length + Height))+
(2 * (Width+Height));
}
double Volume();
void BoxCharacteristics();
};

void TBox::GetTheDimensions()
{
cout << "Enter the dimensions of the box\n";
cout << "Length: "; cin >> Length;
cout << "Width: "; cin >> Width;
cout << "Height: "; cin >> Height;
}

double TBox::Volume()
{
return Length * Width * Height;
}

void TBox::BoxCharacteristics()
{
cout << "\nBox Characteristics";
cout << "\nLength: " << Length;
cout << "\nWidth: " << Width;
cout << "\nHeight: " << Height;
cout << "\nArea: " << TotalArea();
cout << "\nVolume: " << Volume();

© FunctionX, Inc. 96
C++ Fundamentals Chapter 12: Introduction to Clases

}
int main()
{
TBox Box;

Box.GetTheDimensions();
Box.BoxCharacteristics();

return 0;
}

Practical Learning: Interacting With Object Methods


1. To let a method call other member methods of the same object, change the Display()
method and the main() function as follows:

...
void TEmployee::Display()
{
IdentifyEmployee();
GetHourlySalary();
CalcTotalHours();
CalcGrossPay();
CalcTaxAmount();

cout << "\nEmployee Payroll";


cout << "\nEmployee Name: " << FirstName << " "
<< LastName;
cout << "\nWeekly Hours: " << TotalHours;
cout << "\nHourly Salary: $" << HourlySalary;
cout << "\nGross Salary: $" << WeeklySalary;
cout << "\nTax Amount: $" << TaxAmount;
cout << "\nNet Salary: $" << NetPay;
}

...

int main()
{
TEmployee Contractor;

Contractor.Display();

cout << "\n\n";


return 0;
}
2. Test the program.
3. After running the program, return to your programming environment.

© FunctionX, Inc. 97
C++ Fundamentals Chapter 19: Combinations of Objects

Chapter 18:
Objects and their
Environment

? Classes and Functions

? Objects and their Environment

© FunctionX, Inc. 98
C++ Fundamentals Chapter 19: Combinations of Objects

1.1 Classes and Functions


In order to perform the various assignments it receives, the computer manipulates objects
created in a program. In most significant applications, one object is not enough to
accomplish a whole purpose. As we have learned that the use of one variable in a
program is unrealistic, we can also combine various objects to create a more meaningful
and complete application.

There are various techniques used to mix objects in a program. To imitate the idea of
combining different variables in a program, we will start by passing an object as a
function argument, then we will be using various objects in the same program.

18.1.1 Introduction
C++ allows you to pass an object to a function or to return an object from a function. An
object you use in a program can come from any source: an object built-in the operating
system, an object shipped with your compiler, an object that is part of the C++ language,
or one that you create.

The first thing you should do is to create an object, unless you are using an existing one.
Here is an example:

Header File: Volumes.h

#if !defined VolumesH


#define VolumesH

namespace Volumes
{
class TBox
{
public:
TBox(double L = 0, double H = 0, double W = 0);
TBox(const TBox &Box);
~TBox();

void setLength(const double L) { Length = (L <= 0) ? 0 : L; }


double getLength() const { return (Length < 0) ? 0 : Length; }
void setHeight(const double H) { Height = (H <= 0) ? 0 : H; }
double getHeight() const { return (Height < 0) ? 0 : Height; }
void setWidth(const double W) { Width = (W <= 0) ? 0 : W; }
double getWidth() const { return (Width < 0) ? 0 : Width; }
void setDimensions(const double L, const double H, const double W);

double Area() const;


double Volume() const;

private:
double Length;
double Height;
double Width;
};
}

© FunctionX, Inc. 99
C++ Fundamentals Chapter 19: Combinations of Objects

#endif // VolumesH

The source file is used to initialize the object (its member variables) and to perform the
necessary calculations involved with the object.

Source File: Volumes.cpp

#include "Volumes.h"

namespace Volumes
{
TBox::TBox(double L, double H, double W)
: Length(L), Height(H), Width(W)
{
}

TBox::TBox(const TBox &Box)


: Length(Box.Length),
Height(Box.Height),
Width(Box.Width)
{
}

TBox::~TBox()
{
}

void TBox::setDimensions(const double L, const double H, const double W) const


{
setLength(L);
setHeight(H);
setWidth(W);
}

double TBox::Area() const


{
return 2 * ( (Length * Height) +
(Height * Width) +
(Length * Width) );
}

double TBox::Volume() const


{
return Length * Height * Width;
}
} // namespace Volumes

Once the object is built, you can call it from another function. As we have done with the
main() function, you can call an object “as is” using the default constructor, which itself
has the responsibility of using initializing the values for its members:

Source File: Main.cpp

#include <iostream>
#include "Volumes.h"

using namespace std;


using namespace Volumes;

© FunctionX, Inc. 100


C++ Fundamentals Chapter 19: Combinations of Objects

int main()
{
TBox RedBrick(6.25, 4.65, 3.85);

cout << "Box Properties";


cout << "\nLength = " << RedBrick.getLength();
cout << "\nHeight = " << RedBrick.getHeight();
cout << "\nWidth = " << RedBrick.getWidth();
cout << "\nArea = " << RedBrick.Area();
cout << "\nVolume = " << RedBrick.Volume() << "\n";

return 0;
}

The program produces:

Box Properties
Length = 6.25
Height = 4.65
Width = 3.85
Area = 142.055
Volume = 111.891

Practical Learning: The Starting Object


1. Create a Console Application in a new folder called ROSH1
2. If necessary, create a source file. Save the first source file as Main.cpp
3. Save the project as ROSH
4. Create a new header file and save it as Students.h in the ROSH1 folder
5. Change the Students.h file as follows:

#ifndef StudentsH
#define StudentsH

#include <string>
using namespace std;

namespace Students
{
namespace Registration
{
class Student
{
public:
Student();
Student(string fn, string ln,
int DOB, int MOB, int YOB);
~Student();

string getFirstName() { return FirstName; }


string getLastName() { return LastName; }
int getDayOfBirth() { return DayOfBirth; }
int getMonthOfBirth() { return MonthOfBirth; }
int getYearOfBirth() { return YearOfBirth; }

© FunctionX, Inc. 101


C++ Fundamentals Chapter 19: Combinations of Objects

private:
string FirstName;
string LastName;
int DayOfBirth;
int MonthOfBirth;
int YearOfBirth;
};

} // namespace Registration
} // namespace Students

#endif // StudentsH

6. Create a source file and save it as Students.cpp


7. Implement the object as follows:

#include "Students.h"

namespace Students
{
namespace Registration
{
Student::Student()
: FirstName("John"),
LastName("Doe"),
DayOfBirth(1),
MonthOfBirth(1),
YearOfBirth(1990)
{
}

Student::Student(string fn, string ln,


int DOB, int MOB, int YOB)
: FirstName(fn),
LastName(ln),
DayOfBirth(DOB),
MonthOfBirth(MOB),
YearOfBirth(YOB)
{
}

Student::~Student()
{
}

} // namespace Registration
} // namespace Students

8. To prepare a test of the project, change the Main.cpp file with the following:

#include <iostream>
#include "Students.h"

using namespace std;


using namespace Students::Registration;

int main()
{

© FunctionX, Inc. 102


C++ Fundamentals Chapter 19: Combinations of Objects

Student DefaulStudent;

// Display the characteristics of the student


cout << "Characteristics of this student";
cout << "\nFull Name: " << DefaulStudent.getFirstName()
<< " " << DefaulStudent.getLastName();
cout << "\nDate of Birth: " << DefaulStudent.getDayOfBirth()
<< "/" << DefaulStudent.getMonthOfBirth()
<< "/" << DefaulStudent.getYearOfBirth() << "\n";

Student Typical("William", "Tobolowski", 5, 15, 1985);


// Display the characteristics of the student
cout << "\nCharacteristics of this student";
cout << "\nFull Name: " << Typical.getFirstName()
<< " " << Typical.getLastName();
cout << "\nDate of Birth: " << Typical.getDayOfBirth()
<< "/" << Typical.getMonthOfBirth()
<< "/" << Typical.getYearOfBirth() << "\n";

return 0;
}

9. Test the program:

Characteristics of this student


Full Name: John Doe
Date of Birth: 1/1/1990

Characteristics of this student


Full Name: William Tobolowski
Date of Birth: 5/15/1985

10. Return to your programming environment.


11. To let the user provide the values of an object, you can request these values from the
user and fill out the object with those values. To see an example, change the
Main.cpp file as follows:

#include <iostream>
#include "Students.h"

using namespace std;


using namespace Students::Registration;

int main()
{
string FN, LN;
int Day, Month, Year;
cout << "Enter the student's information\n";
cout << "First Name: ";
cin >> FN;
cout << "Last Name: ";
cin >> LN;
cout << "Day of Birth: ";
cin >> Day;
cout << "Month of Birth: ";
cin >> Month;
cout << "Year of Birth: ";
cin >> Year;

© FunctionX, Inc. 103


C++ Fundamentals Chapter 19: Combinations of Objects

Student Typical(FN, LN, Day, Month, Year);

// Display the characteristics of the student


cout << "\nStudent Information";
cout << "\nFull Name: " << Typical.getFirstName()
<< " " << Typical.getLastName();
cout << "\nDate of Birth: " << Typical.getDayOfBirth()
<< "/" << Typical.getMonthOfBirth()
<< "/" << Typical.getYearOfBirth() << "\n";

return 0;
}

12. Test the program. Here is an example:

Enter the student's information


First Name: Gregory
Last Name: Ballack
Day of Birth: 22
Month of Birth: 6
Year of Birth: 1988

Student Information
Full Name: Gregory Ballack
Date of Birth: 22/6/1988

13. Return to your programming environment

14. Writing values to an object allows the user to control the object. That’s why set
methods are very valuable. To provide set methods, change the header file of the
Student object as follows:

#ifndef StudentsH
#define StudentsH

#include <string>
using namespace std;

namespace Students
{
namespace Registration
{
class Student
{
public:
Student();
Student(string fn, string ln,
int DOB, int MOB, int YOB);
~Student();

void setFirstName(const string f) { FirstName = f; }


string getFirstName() const { return FirstName; }
void setLastName(const string L) { LastName = L; }
string getLastName() const { return LastName; }
void setDayOfBirth(const int d) { DayOfBirth = d; }
int getDayOfBirth() const { return DayOfBirth; }
void setMonthOfBirth(int m) { MonthOfBirth = m; }
int getMonthOfBirth() const { return MonthOfBirth; }

© FunctionX, Inc. 104


C++ Fundamentals Chapter 19: Combinations of Objects

void setYearOfBirth(const int y) { YearOfBirth = y; }


int getYearOfBirth() const { return YearOfBirth; }

private:
string FirstName;
string LastName;
int DayOfBirth;
int MonthOfBirth;
int YearOfBirth;
};

} // namespace Registration
} // namespace Students

#endif

15. To request values of the Student object, change the Main.cpp file as follows:

#include <iostream>
#include "Students.h"

using namespace std;


using namespace Students::Registration;

int main()
{
string FN, LN;
int Day, Month, Year;
cout << "Enter the student's information\n";
cout << "First Name: ";
cin >> FN;
cout << "Last Name: ";
cin >> LN;
cout << "Day of Birth: ";
cin >> Day;
cout << "Month of Birth: ";
cin >> Month;
cout << "Year of Birth: ";
cin >> Year;

Student Typical;
Typical.setFirstName(FN);
Typical.setLastName(LN);
Typical.setDayOfBirth(Day);
Typical.setMonthOfBirth(Month);
Typical.setYearOfBirth(Year);

// Display the characteristics of the student


cout << "\nStudent Information";
cout << "\nFull Name: " << Typical.getFirstName()
<< " " << Typical.getLastName();
cout << "\nDate of Birth: " << Typical.getDayOfBirth()
<< "/" << Typical.getMonthOfBirth()
<< "/" << Typical.getYearOfBirth() << "\n";

return 0;
}

16. Test the program. Here is an example:

© FunctionX, Inc. 105


C++ Fundamentals Chapter 19: Combinations of Objects

Enter the student's information


First Name: Juan
Last Name: Gomez
Day of Birth: 2
Month of Birth: 2
Year of Birth: 1991

Student Information
Full Name: Juan Gomez
Date of Birth: 2/2/1991

17. Return to your programming environment

18.1.2 Passing an Object as an Argument


After creating an object, it becomes a data type, sometimes referred to as a programmer
defined data type. As a data type, you can declare an object inside of a function and use
it. That is what we have done so far when using objects inside of the main() function.

There are two techniques used to involve an object with a function. You can pass a
member of an object as argument to a function, or you can pass the whole object as an
argument. When passing an object as a parameter, you should be familiar with the
construction of the object, know its members and which ones you need to use.

Instead of displaying the characteristics of the box in the main() function, we can use an
external function to perform that assignment.

Source File: Main.cpp

#include <iostream>
#include "Box.h"

using namespace std;


using namespace Volumes;

void ShowProperties(TBox Box)


{
cout << "Box Properties";
cout << "\nLength = " << Box.getLength();
cout << "\nHeight = " << Box.getHeight();
cout << "\nWidth = " << Box.getWidth();
cout << "\nArea = " << Box.Area();
cout << "\nVolume = " << Box.Volume() << "\n";
}

int main()
{
TBox Brick(5.14, 3.28, 2.86);

ShowProperties(Brick);

return 0;
}

© FunctionX, Inc. 106


C++ Fundamentals Chapter 19: Combinations of Objects

Even if you let the user provide the values of the class, after constructing such an object,
you can pass it to a function that would manipulate it, including displaying its
characteristics.

Practical Learning: Using an Object as an Argument


1. To use an object as argument, change the Main.cpp file as follows:

#include <iostream>
#include "Students.h"

using namespace std;


using namespace Students::Registration;

int main()
{
void ShowStudent(Student Std);
string FN, LN;
int Day, Month, Year;

cout << "Enter the student's information\n";


cout << "First Name: "; cin >> FN;
cout << "Last Name: "; cin >> LN;
cout << "Day of Birth: "; cin >> Day;
cout << "Month of Birth: "; cin >> Month;
cout << "Year of Birth: "; cin >> Year;

Student Typical;
Typical.setFirstName(FN);
Typical.setLastName(LN);
Typical.setDayOfBirth(Day);
Typical.setMonthOfBirth(Month);
Typical.setYearOfBirth(Year);

ShowStudent(Typical);

return 0;
}

void ShowStudent(Student Stud)


{
// Display the characteristics of the student
cout << "\nStudent Information";
cout << "\nFull Name: " << Stud.getFirstName()
<< " " << Stud.getLastName();
cout << "\nDate of Birth: " << Stud.getDayOfBirth()
<< "/" << Stud.getMonthOfBirth()
<< "/" << Stud.getYearOfBirth() << "\n";
}

2. Test the program. Here is an example:


Enter the student's information
First Name: Joan
Last Name: Lucent
Day of Birth: 18
Month of Birth: 4
Year of Birth: 1986

© FunctionX, Inc. 107


C++ Fundamentals Chapter 19: Combinations of Objects

Student Registration
Full Name: Joan Lucent
Date of Birth: 18/4/1986

3. Return to your programming environment

18.1.3 Returning an Object


As a data type, you can use an object as a returning value of a function. The issue this
time is a little different. When returning an object, you should be familiar with the
construction of the object, especially its constructor. Since you will mostly return an
object as complete as possible, the returned variable is a constructor. Therefore, when
building the object inside of the function, make sure that the object can be used as a
variable. Ask yourself whether the object you are returning can be passed an argument to
another function. Can it be used to display the complete properties of the object?

As opposed to requesting the dimensions of the box from the main() function, we will
use an external function to take care of that so that when the object is returned, the other
functions or objects would trust that it can be used by another part of the program.

Source File: Main.cpp

#include <iostream>
#include "Box.h"

using namespace std;


using namespace Volumes;

TBox GetDimensions()
{
double L, H, W;

cout << "Specify the dimensions of the box\n";


cout << "Length: "; cin >> L;
cout << "Height: "; cin >> H;
cout << "Width: "; cin >> W;

return TBox::TBox(L, H, W); // Returning the constructor


}

void ShowProperties(TBox Box)


{
cout << "\nBox Properties";
cout << "\nLength = " << Box.getLength();
cout << "\nHeight = " << Box.getHeight();
cout << "\nWidth = " << Box.getWidth();
cout << "\nArea = " << Box.Area();
cout << "\nVolume = " << Box.Volume() << "\n";
}

int main()
{
TBox Boom;

© FunctionX, Inc. 108


C++ Fundamentals Chapter 19: Combinations of Objects

Boom = GetDimensions();
ShowProperties(Boom);

return 0;
}

An example of running the program would produce:

Specify the dimensions of the box


Length: 40.12
Height: 36.06
Width: 28.82

Box Properties
Length = 40.12
Height = 36.06
Width = 28.82
Area = 7284.47
Volume = 41694.7
Press any key to continue

Another version of the GetDimensions() function would consist of assigning the values of
the member variables of the object to the right access methods:

Source File: Main.cpp

TBox GetDimensions()
{
TBox B;
double L, H, W;

cout << "Specify the dimensions of the box\n";


cout << "Length: "; cin >> L;
cout << "Height: "; cin >> H;
cout << "Width: "; cin >> W;

B.setLength(L);
B.setHeight(H);
B.setWidth(W);
return B;
}

As another technique, you can first build the object by assembling the necessary member
variables. Once the variables are gathered, you build an object based on those and return
such an object from the function. Here is an example:

Source File: Main.cpp

TBox GetDimensions()
{
double L, H, W;

cout << "Specify the dimensions of the box\n";


cout << "Length: "; cin >> L;
cout << "Height: "; cin >> H;
cout << "Width: "; cin >> W;

© FunctionX, Inc. 109


C++ Fundamentals Chapter 19: Combinations of Objects

TBox Doss(L, H, W);


return Doss;
}

Any of these techniques should allow you to return the desired object from a function and
be able to use that object somewhere else, including displaying its properties using
another function

Practical Learning: Returning an Object From a Function


1. To apply an example of returning an object, change the Main.cpp file as follows:

#include <iostream>
#include "Students.h"

using namespace std;


using namespace Students::Registration;

Student Registration()
{
string FN, LN;
int Day, Month, Year;
Student s;

cout << "Enter the student's information\n";


cout << "First Name: "; cin >> FN;
cout << "Last Name: "; cin >> LN;
cout << "Day of Birth: "; cin >> Day;
cout << "Month of Birth: "; cin >> Month;
cout << "Year of Birth: "; cin >> Year;

s.setFirstName(FN);
s.setLastName(LN);
s.setDayOfBirth(Day);
s.setMonthOfBirth(Month);
s.setYearOfBirth(Year);

return s;
}

int main()
{
void ShowStudent(Student Std);
Student Typical;

Typical = Registration();
ShowStudent(Typical);

return 0;
}

void ShowStudent(Student Stud)


{
...
}

2. Test the program. Here is an example:

Enter the student's information

© FunctionX, Inc. 110


C++ Fundamentals Chapter 19: Combinations of Objects

First Name: Jarrel


Last Name: Jeremies
Day of Birth: 2
Month of Birth: 4
Year of Birth: 1991

Student Registration
Full Name: Jarrel Jeremies
Date of Birth: 2/4/1991

3. Return to your programming environment

18.1.4 Passing an Object by Reference


Since an object is a data type, it enjoys the features of the other, regular, variables. For
example, instead of returning an object from a function, when this is not possible because
of some circumstances, you can pass an object by reference. Like another variable, when
an object is passed by reference, any alteration made on the object will be kept when the
function exists. This feature allows you to declare a function as void but return a
completely built object.

To pass an object by reference, use the ampersand operator “&” between its name and the
name of the argument inside of the function’s parentheses:

Source File: Main.cpp

#include <iostream>
#include "Box.h"

using namespace std;


using namespace Volumes;

void GetDimensions(TBox& Box)


{
double L, H, W;

cout << "Specify the dimensions of the box\n";


cout << "Length: "; cin >> L;
cout << "Height: "; cin >> H;
cout << "Width: "; cin >> W;

Box.setLength(L);
Box.setHeight(H);
Box.setWidth(W);
}

void ShowProperties(TBox Box)


{
cout << "\nBox Properties";
cout << "\nLength = " << Box.getLength();
cout << "\nHeight = " << Box.getHeight();
cout << "\nWidth = " << Box.getWidth();
cout << "\nArea = " << Box.Area();
cout << "\nVolume = " << Box.Volume() << "\n";
}

© FunctionX, Inc. 111


C++ Fundamentals Chapter 19: Combinations of Objects

int main()
{
TBox Boom;

GetDimensions(Boom);
ShowProperties(Boom);

return 0;
}

Here is examp le of running the program:

Specify the dimensions of the box


Length: 12.44
Height: 14.66
Width: 16.88

Box Properties
Length = 12.44
Height = 14.66
Width = 16.88
Area = 1279.64
Volume = 3078.41

Practical Learning: Passing an Object by Reference


1. To pass an object as reference, change the Main.cpp file as follows:

#include <iostream>
#include "Students.h"

using namespace std;


using namespace Students::Registration;

void Registration(Student &Stud)


{
string FN, LN;
int Day, Month, Year;

cout << "Enter the student's information\n";


cout << "First Name: "; cin >> FN;
cout << "Last Name: "; cin >> LN;
cout << "Day of Birth: "; cin >> Day;
cout << "Month of Birth: "; cin >> Month;
cout << "Year of Birth: "; cin >> Year;

Stud.setFirstName(FN);
Stud.setLastName(LN);
Stud.setDayOfBirth(Day);
Stud.setMonthOfBirth(Month);
Stud.setYearOfBirth(Year);
}

int main()
{
void ShowStudent(Student Std);
Student Typical;

© FunctionX, Inc. 112


C++ Fundamentals Chapter 19: Combinations of Objects

Registration(Typical);
ShowStudent(Typical);

return 0;
}

void ShowStudent(Student Stud)


{
// Display the characteristics of the student
cout << "\nStudent Information";
cout << "\nFull Name: " << Stud.getFirstName()
<< " " << Stud.getLastName();
cout << "\nDate of Birth: " << Stud.getDayOfBirth()
<< "/" << Stud.getMonthOfBirth()
<< "/" << Stud.getYearOfBirth() << "\n";
}
2. Test the program and return to your programming environment

18.1.5 Passing a Constant Object


We learned that, when a function is passed an argument that the function does not
modify, the argument should be passed as a constant. This is also valid for a class passed
to a function.

The functions we have used so far to display the properties of our object do not modify
their arguments. For this reason, it would be safe and advantageous to pass such an object
as a constant. To pass an object as constant, type the const keyword on its left. Here is an
example:

void ShowProperties(const TBox Box)


{
cout << "\nBox Properties";
cout << "\nLength = " << Box.getLength();
cout << "\nHeight = " << Box.getHeight();
cout << "\nWidth = " << Box.getWidth();
cout << "\nArea = " << Box.Area();
cout << "\nVolume = " << Box.Volume() << "\n";
}

We also learned that, passing an argument by reference accelerates compilation because


the argument itself, and not just its value as a copy is accessed by the compiler. And if a
function does not modify an argument it receives, the argument can be passed as a
constant reference. Here is an example from the above function:

void ShowProperties(const TBox &Box)


{
cout << "\nBox Properties";
cout << "\nLength = " << Box.getLength();
cout << "\nHeight = " << Box.getHeight();
cout << "\nWidth = " << Box.getWidth();
cout << "\nArea = " << Box.Area();
cout << "\nVolume = " << Box.Volume() << "\n";
}

© FunctionX, Inc. 113


C++ Fundamentals Chapter 19: Combinations of Objects

Practical Learning: Passing an Object as a Constant Reference


1. When displaying information about a student, to pass the Student argument as a
constant reference, change the main() function as follows:

int main()
{
void ShowStudent(const Student& Std);
Student Typical;

Registration(Typical);
ShowStudent(Typical);

return 0;
}

2. Change the ShowStudent() function as follows:

void ShowStudent(const Student& Stud)


{
// Display the characteristics of the student
cout << "\nStudent Information";
cout << "\nFull Name: " << Stud.getFirstName()
<< " " << Stud.getLastName();
cout << "\nDate of Birth: " << Stud.getDayOfBirth()
<< "/" << Stud.getMonthOfBirth()
<< "/" << Stud.getYearOfBirth() << "\n";
}

3. Test the program and return to your programming environment.

1.2 Classes and Pointers


Like a regular data type, an object can be declared as a pointer, it can be passed to a
function as a reference or as a pointer and you can dynamically create an instance of an
object.

1.2.1 An Object Pointer as an Argument


Using the same techniques of passing regular variables as pointers, you can pass an
object as a pointer to a function. To pass a pointer object to a function, when declaring
the function, between the parentheses, type the * operator on the right side of the object
name and type a name for the object. Here is an example:

void GetDimensions(TBox *Box);

When defining the function, use the pointer access operator (->) to access the desired
members of the object:

void GetDimensions(TBox *Box)


{
double L, H, W;

cout << "Specify the dimensions of the box\n";


cout << "Length: "; cin >> L;
cout << "Height: "; cin >> H;

© FunctionX, Inc. 114


C++ Fundamentals Chapter 19: Combinations of Objects

cout << "Width: "; cin >> W;

Box->setDimensions(L, H, W);
}

When calling a function whose argument was passed a a pointer to an object, it depends
on how the object was declared in the function that is making the call. For example,
imagine that you declared a TBox instance regularly as we did previously:

TBox Box;

In order to pass such an object to the GetDimensions() function, call the argument as a
reference. Here is an example:

#include <iostream>
#include "Volumes.h"

using namespace std;


using namespace Volumes;

void GetDimensions(TBox *Box)


{
double L, H, W;

cout << "Specify the dimensions of the box\n";


cout << "Length: "; cin >> L;
cout << "Height: "; cin >> H;
cout << "Width: "; cin >> W;

Box->setLength(L);
Box->setHeight(H);
Box->setWidth(W);
}

void ShowProperties(const TBox &Box)


{
...
}

int main()
{
TBox Box;

GetDimensions(&Box);
ShowProperties(Box);

return 0;
}

This feature of pointers (passing an argument as a pointer) allows a function declared as


void to return values, which, as we learned with references, is one of the primary reasons
for using pointers:

Specify the dimensions of the box


Length: 2.25
Height: 4.15
Width: 1.85

© FunctionX, Inc. 115


C++ Fundamentals Chapter 19: Combinations of Objects

Box Properties
Length = 2.25
Height = 4.15
Width = 1.85
Area = 42.355
Volume = 17.2744

In the same way, if you pass an argument to a function that does not modify its argument,
because an argument passed as a pointer gives direct access to the address (or memory
location) of the argument, you can pass the argument as a constant pointer. Here is an
examp le:

#include <iostream>
#include "Volumes.h"

using namespace std;


using namespace Volumes;

void GetDimensions(TBox *Box)


{
...
}

void ShowProperties(const TBox *Box)


{
cout << "\nBox Properties";
cout << "\nLength = " << Box->getLength();
cout << "\nHeight = " << Box->getHeight();
cout << "\nWidth = " << Box->getWidth();
cout << "\nArea = " << Box->Area();
cout << "\nVolume = " << Box->Volume() << "\n";
}

int main()
{
TBox Box;

GetDimensions(&Box);
ShowProperties(&Box);

return 0;
}

Practical Learning: Passing an Argument as a Pointer


1. To pass an argument as a pointer, change the Registration() function as follows:
#include <iostream>
#include "Students.h"

using namespace std;


using namespace Students::Registration;

void Registration(Student *s)


{
string FN, LN;
int Day, Month, Year;

© FunctionX, Inc. 116


C++ Fundamentals Chapter 19: Combinations of Objects

cout << "Enter the student's information\n";


cout << "First Name: "; cin >> FN;
cout << "Last Name: "; cin >> LN;
cout << "Day of Birth: "; cin >> Day;
cout << "Month of Birth: "; cin >> Month;
cout << "Year of Birth: "; cin >> Year;

s->setFirstName(FN);
s->setLastName(LN);
s->setDayOfBirth(Day);
s->setMonthOfBirth(Month);
s->setYearOfBirth(Year);
}

int main()
{
void ShowStudent(const Student &Std);
Student Typical;

Registration(&Typical);
ShowStudent(Typical);

return 0;
}
...
2. Test the application and return to your programming environment.
3. To pass an argument as a constant pointer, change the ShowStudent() function as
follows:
#include <iostream>
#include "Students.h"

using namespace std;


using namespace Students::Registration;

void Registration(Student *s)


{
...
}

int main()
{
void ShowStudent(const Student *Std);
Student Typical;

Registration(&Typical);
ShowStudent(&Typical);

return 0;
}

void ShowStudent(const Student *Stud)


{
// Display the characteristics of the student
cout << "\nStudent Information";
cout << "\nFull Name: " << Stud->getFirstName()
<< " " << Stud->getLastName();
cout << "\nDate of Birth: " << Stud->getDayOfBirth()

© FunctionX, Inc. 117


C++ Fundamentals Chapter 19: Combinations of Objects

<< "/" << Stud->getMonthOfBirth()


<< "/" << Stud->getYearOfBirth() << "\n";
}
4. Test the application and return to your programming environment

1.2.2 Declaring an Object as a Pointer


In the example we saw above, our abjects were still declared regularly. An object can
also be declared as a pointer variable using the same * operator as we did for the regular
variable. The syntax of declaring a pointer to an object is:

ObjectName * InstanceName ;

The ObjectName is one already created. It could be in the program or one that shipped
with the compiler. Once again, the asterisk * lets the compiler know that the object is
declared as a pointer. The InstanceName follows the same rules we have applied to other
variables so far. For example, you can declare our TBox as a pointer as follows:

TBox *Box;

Just like when initializing a regular variable, you can assign an instance of a regular
object to an object’s pointer. Here is an example:

TBox Brick;
TBox *Box = &Brick;

When an object has been declared as a pointer, use the pointer access operator “->” to
access any of its available members. For example, to access the getLength() method of
the TBox object using the Box pointer, you can type:

Box->getLength();

Here is an example program that declares a pointer to a TEllipse object and uses the ->
operator to access its members:

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

struct TEllipse
{
double Radius;
double radius;
};

double GetTheRadius(const string s);


double Area(const double R, const double r);

int main()
{
TEllipse Els;
TEllipse* Elisp = &Els;

cout << "Enter the dimensions of the ellipse\n";

© FunctionX, Inc. 118


C++ Fundamentals Chapter 19: Combinations of Objects

Elisp->Radius = GetTheRadius("Long Radius: ");


Elisp->radius = GetTheRadius("Short Radius: ");

cout << "\nCharacteristics of the ellipse";


cout << setiosflags(ios::fixed) << setprecision(2);
cout << "\nLong Radius: " << Elisp->Radius;
cout << "\nShort Radius: " << Elisp->radius;
cout << "\nArea: " << Area(Elisp->Radius, Elisp->radius);

return 0;
}

double GetTheRadius(const string s)


{
double r;

cout << s;
cin >> r;
return r;
}

double Area(const double R, const double r)


{
const double PI = 3.14159;
return R * r * PI;
}

Earlier, we saw that, when calling a function that has received an argument as a pointer, it
depends on how the object was declared. If the object was declared as a pointer and
rightly initialized, since it is a pointer already, when passing it to a function, simply
provide its name. Here is an example:

#include <iostream>
#include "Volumes.h"

using namespace std;


using namespace Volumes;

void GetDimensions(TBox *Box)


{
...
}

void ShowProperties(const TBox *Box)


{
...
}

int main()
{
TBox Brick;
TBox *Box = &Brick;

GetDimensions(Box);
ShowProperties(Box);

return 0;
}

© FunctionX, Inc. 119


C++ Fundamentals Chapter 19: Combinations of Objects

The object we have just declared needed a second object to be initialized. C++ allows
you to dynamically create an object and initialize it to its class using the new operator.
This can be done as follows:

int main()
{
TBox *Box = new TBox;

GetDimensions(Box);
ShowProperties(Box);

return 0;
}

With such a TBox instance so declared and initialized, you can access any of its available
members.

Once you have finished using a dynamically created object, you should get rid of it and
reclaim the memory space it was using. To delete a dynamic object, use the delete
operator. The syntax is:

delete ObjectInstance;

The delete keyword is required. The ObjectInstance is the name used when declaring the
pointer, the same name used when using the new operator. Here is an example:

int main()
{
TBox *Box = new TBox;

GetDimensions(Box);
ShowProperties(Box);

delete Box;

return 0;
}

To avoid the possibility of a memory leak, you can assign the NULL constant to the
memory space left by the deleted instance of your object:

int main()
{
TBox *Bo x = new TBox;

GetDimensions(Box);
ShowProperties(Box);

delete Box;
Box = NULL;

return 0;
}

© FunctionX, Inc. 120


C++ Fundamentals Chapter 19: Combinations of Objects

Practical Learning: Declaring an Object as a Pointer


1. To declare the Student object as a pointer and call the functions that use it as
arguments, change the main() function as follows:
#include <iostream>
#include "Students.h"

using namespace std;


using namespace Students::Registration;

void Registration(Student *s)


{
...
}

int main()
{
void ShowStudent(const Student *Std);
Student *Typical = new Student;

Registration(Typical);
ShowStudent(Typical);

return 0;
}

void ShowStudent(const Student *Stud)


{
...
}

2. Test the program to make sure it wors fine.


3. Delete the object instance after it has been used as follows:

int main()
{
void ShowStudent(const Student *Std);
Student *Typical = new Student;

Registration(Typical);
ShowStudent(Typical);

delete Typical;
Typical = NULL;

return 0;
}

4. Test the program and return to your programming environment

1.2.3 The Size of an Object


As a regular variable, an object such as TBox declared occupies a set amount of space.
As we learned with variables, this assignment of memory space is referred to as static
allocation. Using the sizeof operator, you can find out how much space an object is
occupying. Here is how we could get the size of the TBox object:

© FunctionX, Inc. 121


C++ Fundamentals Chapter 19: Combinations of Objects

cout << "\nThe size of the TBox is " << sizeof(TBox);

In the same way you can find out the amount of space occupied by an instance of an
object:

int main()
{
TBox Box;

cout << "Size of TBox class: " << sizeof(TBox) << " bytes\n";
cout << "Size of Box instance: " << sizeof(Box) << " bytes\n";

return 0;
}

When testing the program, I got (I am using Microsoft Windows XP-HE):

Size of TBox class: 24 bytes


Size of Box instance: 24 bytes

If the object is declared as a pointer, to get the size of a pointer to an object, use the sizeof
operator. If you use just the name of the pointer, you will get the current size of the
declared object. If you append the * operator, you will get the actual size of the object:

int main()
{
TBox *Box = new TBox;

cout << "Size of TBox class: " << sizeof(TBox) << " bytes\n";
cout << "Size of *Box instance: " << sizeof(*Box) << " bytes\n";
cout << "Size of Box instance: " << sizeof(Box) << " bytes\n";

delete Box;
Box = NULL;

return 0;
}

This would produce:

Size of TBox class: 24 bytes


Size of *Box instance: 24 bytes
Size of Box instance: 4 bytes

1.3 Object and Self-Management

1.3.1 Self Returning an Object


The constructors are not the only member functions that can be declared with the name of
the class. C++ allows you to manipulate the members of class without using an external
function. This technique uses a memb er function that can return the parent class. To have

© FunctionX, Inc. 122


C++ Fundamentals Chapter 19: Combinations of Objects

a function that can refer to the object itself, in the body of the class, declare a function
that holds the same name as the class, followed by a valid name of a function and the
parentheses. Here is an example:

#if !defined VolumesH


#define VolumesH

namespace Volumes
{
class TBox
{
public:
TBox(double L = 0, double H = 0, double W = 0);
TBox(const TBox &Box);
~TBox();

void setLength(const double L) { Length = (L <= 0) ? 0 : L; }


double getLength() const { return (Length < 0) ? 0 : Length; }
void setHeight(const double H) { Height = (H <= 0) ? 0 : H; }
double getHeight() const { return (Height < 0) ? 0 : Height; }
void setWidth(const double W) { Width = (W <= 0) ? 0 : W; }
double getWidth() const { return (Width < 0) ? 0 : Width; }
void setDimensions(const double L, const double H, const double W);

double Area() const;


double Volume() const;

TBox Add();

private:
double Length;
double Height;
double Width;
};
}

#endif // VolumesH

An example of using such a function would consist of changing the value of each
member of the class. Since the function is declared as returning the value of the same
variable, you can implement it as follows:

TBox TBox::Add()
{
TBox Box;

// The constant double values used here were randomly chosen


Box.Length = Length + 12.52;
Box.Height = Height + 8.95;
Box.Width = Width + 5.75;

return Box;
}

Calling this self-returning function is equivalent to changing the values of the member
variables, as illustrated in the followng main() function:

#include <iostream>

© FunctionX, Inc. 123


C++ Fundamentals Chapter 19: Combinations of Objects

#include <iomanip>
#include "Volumes.h"

using namespace std;


using namespace Volumes;

void GetDimensions(TBox *Box)


{
...
}

void ShowProperties(const TBox *Box)


{
...
}

int main()
{
TBox Box;

// GetDimensions(Box);
cout << "A TBox with default dimensions";
ShowProperties(&Box);

TBox Brick = Box.Add();


ShowProperties(&Brick);

return 0;
}

This would produce:

A TBox with default dimensions


Box Properties
Length = 0.00
Height = 0.00
Width = 0.00
Area = 0.00
Volume = 0.00

Box Properties
Length = 12.52
Height = 8.95
Width = 5.75
Area = 471.01
Volume = 644.31

You can use this self-returning ability to define almost any type of method that returns
the same class. A particular function can be used to modify the default values of the
member variables. For example, you can write a method that would be passed a constant
value and ask the method to add this value to each member variable before returning the
same object that made the call. Such a method can be declared as follows:

TBox Add(const double Value);

To add the provided value to each member variable, you can define the method as
follows:

© FunctionX, Inc. 124


C++ Fundamentals Chapter 19: Combinations of Objects

TBox TBox::Add(const double Value)


{
TBox Box;

Box.Length = Length + Value;


Box.Height = Height + Value;
Box.Width = Width + Value;

return Box;
}

The method can be tested with the following implementation of the main() function:

int main()
{
TBox Box(6.42, 2.84, 4.56);
TBox Brick = Box.Add(8.92);
ShowProperties(&Brick);

return 0;
}

Of course, as done with the addition, you can also declare a method that performs a subtr
action, or a multiplication, or a division, etc. Such a method can be passed a constant
double as done for the addition:

TBox Mul(const double Value);

One way you can implement such a method is to multiply the passed constant to each
member to the calling object and return it:

TBox TBox::Mul(const double d)


{
TBox Box;

Box.Length = Length * d;
Box.Height = Height * d;
Box.Width = Width * d;

return Box;
}

Another type of self-returning method you can create would consit of adding the values
of another instance of the class to the one that makes the call before returning it with new
values. Such a method would take one argument like a copy constructor: a constant
reference of the class. The method can be declared as follows:

TBox Add(const TBox& B);

One way you can use this method is to add each one of its values to the corresponding
member variable of the object that made the call:

TBox TBox::Add(const TBox& Box)


{
TBox NewBox;

NewBox.Length = NewBox.Length + Box.Length;

© FunctionX, Inc. 125


C++ Fundamentals Chapter 19: Combinations of Objects

NewBox.Height = NewBox.Height + Box.Height;


NewBox.Width = NewBox.Width + Box.Width;

return NewBox;
}

You can test this method with the following:

int main()
{
TBox Box(6.42, 2.84, 4.56);

cout << "Box examples\n";

TBox Brick; // This object is empty


ShowProperties(&Brick);

cout << "\nA similar object added to this one";


Brick = Brick.Add(Box);

ShowProperties(&Brick);

return 0;
}

Here is the current Box.h header file:

#if !defined VolumesH


#define VolumesH

namespace Volumes
{
class TBox
{
public:
TBox(double L = 0, double H = 0, double W = 0);
TBox(const TBox &Box);
~TBox();

void setLength(const double L) { Length = (L <= 0) ? 0 : L; }


double getLength() const { return (Length < 0) ? 0 : Length; }
void setHeight(const double H) { Height = (H <= 0) ? 0 : H; }
double getHeight() const { return (Height < 0) ? 0 : Height; }
void setWidth(const double W) { Width = (W <= 0) ? 0 : W; }
double getWidth() const { return (Width < 0) ? 0 : Width; }
void setDimensions(const double L, const double H, const double W);

double Area() const;


double Volume() const;

TBox Add(const double Value);


TBox Sub(const double Value);
TBox Mul(const double Value);
TBox Div(const double Value);
TBox Add(const TBox& B);

private:
double Length;

© FunctionX, Inc. 126


C++ Fundamentals Chapter 19: Combinations of Objects

double Height;
double Width;
};
}

#endif // VolumesH

Here is the current Box.cpp source file:

#include "Volumes.h"

namespace Volumes
{
TBox::TBox(double L, double H, double W)
: Length(L), Height(H), Width(W)
{
}

TBox::TBox(const TBox &Box)


: Length(Box.Length),
Height(Box.Height),
Width(Box.Width)
{
}

TBox::~TBox()
{
}

void TBox::setDimensions(const double L, const double H, const double W)


{
setLength(L);
setHeight(H);
setWidth(W);
}

double TBox::Area() const


{
return 2 * ( ( getLength() * getHeight()) +
( getHeight() * getWidth() ) +
( getLength() * getWidth() ) );
}

double TBox::Volume() const


{
return getLength() * getHeight() * getWidth();
}

TBox T Box::Add(const double d)


{
TBox Box;

Box.Length = Length + d;
Box.Height = Height + d;
Box.Width = Width + d;

return Box;
}

© FunctionX, Inc. 127


C++ Fundamentals Chapter 19: Combinations of Objects

TBox TBox::Sub(const double d)


{
TBox Box;

Box.Length = Length - d;
Box.Height = Height - d;
Box.Width = Width - d;

return Box;
}

TBox TBox::Mul(const double d)


{
TBox Box;

Box.Length = Length * d;
Box.Height = Height * d;
Box.Width = Width * d;

return Box;
}

TBox TBox::Div(const double d)


{
if( d == 0 )
return TBox(0.00, 0.00, 0.00);
else
{
TBox Box;

Box.Length = Length / d;
Box.Height = Height / d;
Box.Width = Width / d;

return Box;
}
}

TBox TBox::Add(const TBox& Box)


{
TBox NewBox;

NewBox.Length = NewBox.Length + Box.Length;


NewBox.Height = NewBox.Height + Box.Height;
NewBox.Width = NewBox.Width + Box.Width;

return NewBox;
}

} // namespace Volumes

1.3.2 The this Pointer


As you can see from the pseudo-operation methods we implemented above, the idea is to
let an object return itself. That is, we want an object that can point to itself. Unfornately,
the only solution we could use was to declare an object in the method we are implement,

© FunctionX, Inc. 128


C++ Fundamentals Chapter 19: Combinations of Objects

change the value of that object and return it. C++ proposes an alternative to returning an
object from one of its member functions. Instead of explicitly declaring a variable when
implementing a function that returns the same object, the compiler simply needs to know
what object you want to return: the object that called the function or a newly declared
one. If you want to return the same object, you can use a special pointer called this.

As its name implies, the this pointer is a self referencing object, which means it allows
you to designate the object that is making the call as the same object you are referring to.
Using the this pointer is a technique that allows you to perform any necessary operation
on an object without the help of an external function and return the same object.

Suppose you have a method called Add() and you want to pass it a constant value that
would be added to an object (or to the members of the object) and change the value of the
object. We saw that such a method can be declared as follows:

TBox Add(const double Value);

The problem we have with this method is that it will return a value or a copied value of
the object that calls it: the real value of the object would not be touched and cannot be
returned. This means that our goal would not be met. The solution is to return a reference
to the object that makes the call. As we saw with variables, giving access to the caller
means the caller would get the object itself, from its location or address, instead of
sending a copy of its value. Therefore, this Add() method should return a reference (or
even a pointer). Therefore, the method should be declarded as follows:

TBox &Add(const double Value);

In the way, you can declare the other methods we had earlier:

#if !defined VolumesH


#define VolumesH

namespace Volumes
{
class TBox
{
public:
...

TBox &Add(const double Value);


TBox &Sub(const double Value);
TBox &Mul(const double Value);
TBox &Div(const double Value);
TBox &Add(const TBox& B);

private:
double Length;
double Height;
double Width;
};
}

#endif // VolumesH

When implementing such a method, because the method should return the same object,
you do need to declare a local variable to hold the changed variable. Since the member

© FunctionX, Inc. 129


C++ Fundamentals Chapter 19: Combinations of Objects

variables of the object will be modified, the member function cannot be declared as a
constant. A priori, the method would be implemented as follows:

TBox &TBox::Add(const double d)


{
Length = Length + d;
Height = Height + d;
Width = Width + d;

return TBox(); // What are we returning?


}

When implementing this function, the values of the variables will certainly be modified
to implement whatever behavior you want. To return the same object, the this object
must be called as a pointer, with *this. Here is the new implementation of the function:

TBox &TBox::Add(const double d)


{
Length = Length + d;
Height = Height + d;
Width = Width + d;

return *this;
}

Using the same logic, you can use the this pointer to return the object from any of its
member methods that needs to reference the same object:

#include "Volumes.h"

namespace Volumes
{
...

TBox &TBox::Add(const double d)


{
Length = Length + d;
Height = Height + d;
Width = Width + d;

return *this;
}

TBox &TBox::Sub(const double d)


{
Length = Length - d;
Height = Height - d;
Width = Width - d;

return *this;
}

TBox &TBox::Mul(const double d)


{
Length = Length * d;
Height = Height * d;
Width = Width * d;

© FunctionX, Inc. 130


C++ Fundamentals Chapter 19: Combinations of Objects

return *this;
}

TBox &TBox::Div(const double d)


{
if( d == 0 )
{
Length = 0;
Height = 0;
Width = 0;
}
else
{
Length = Length / d;
Height = Height / d;
Width = Width / d;
}

return *this;
}

TBox &TBox::Add(const TBox& Box)


{
TBox NewBox;

NewBox.Length = NewBox.Length + Box.Length;


NewBox.Height = NewBox.Height + Box.Height;
NewBox.Width = NewBox.Width + Box.Width;

return *this;
}

} // namespace Volumes

© FunctionX, Inc. 131


C++ Fundamentals Chapter 21: Exception Handling

Appendix

? Appendix A: Clearing the Screen

? Appendix B: Operator Precedence

? Appendix C: Relationships on Numeric Systems

© FunctionX, Inc. 132


C++ Fundamentals Chapter 21: Exception Handling

Appendix C: Relationships on the Numeric Systems

Converting A Byte From Binary to Decimal

Since the bits are numbered from right to left , you can calculate the decimal value of a
byte using the base 2. Consider a binary number intensely mixed with 0s and 1s such as
11010111. The 11010111 binary number can be calculated as:

1 1 0 1 0 1 1 1
= 1* 27 + 1* 26 + 0* 25 + 1* 24 + 0*23 + 1*22 + 1*21 + 1*20
= 1*128 + 1* 64 + 0* 32 + 1*16 + 0* 8 + 1*4 + 1*2 + 1*1
128 + 64 + 0 + 16 + 0 + 4 + 2 + 1
= 215

An alternative to calculating such a number is by using the following table:

128 64 32 16 8 4 2 1

Binary to Decimal Conversion Table

When you are presented with a binary number, you can just write the corresponding bit
value under the ranking decimal number. Consider that you want to calculate the decimal
equivalent of the 01110110 binary number. Using the Binary to Decimal Conversion
Table, you can perform the operation like this:

128 64 32 16 8 4 2 1
0 1 1 1 0 1 1 0

This produces:

0 64 32 16 0 4 2 0

= 64 + 32 + 16 + 4 + 2

= 118

Converting Any Number From Binary To Decimal

Once you are presented with a binary number, you can produce or use a table inspired
from the binary to decimal conversion table:

Etc 214 213 212 211 210 29 28 27 26 25 24 23 22 21 20


Etc 16384 8192 4096 2048 1024 512 256 128 64 32 16 8 4 2 1

Imagine you would like to convert the 10011110011101101 binary number to a decimal
value.

© FunctionX, Inc. 133


C++ Fundamentals Chapter 21: Exception Handling

1 0 0 1 1 1 1 0 0 1 1 1 0 1 1 0 1
65536 32768 16384 8192 4096 2048 1024 512 256 128 64 32 16 8 4 2 1

= 65536+0 + 0 + 8192 + 4096 + 2048 + 1024 + 0 + 0 + 128 + 64 + 32 + 0 + 8 + 4 + 0 + 1

= 65536 + 8192 + 4096 + 2048 + 1024 + 128 + 64 + 32 + 8 + 4 + 1

= 81133

Converting A Byte From Binary to Hexadecimal

When all bits are 0, the byte also has a value of 0. When combining and mixing 0 and 1
bits, you can get binary values as varied as possible: 0101 0010 or 1101 1110 or 0111
1100. We only need to know what each combination would represent. If you divide bits
by groups of four, you can use the table of numeric conversions to find out what each
group represents. Consider a binary number such as 10101101. Dividing it in groups of 4-
bits, we get 1010 1101. Referring to our conversion table, the low order nibble has a
hexadecimal value of 8. The high order nibble has a hexadecimal value of C.

1010 1101
A D

Therefore, the binary number 10101101 has a hexadecimal representation of 0XAD.

Of course, the binary number 10101101 is equivalent to 128 + 0 + 32 + 0 + 8 + 4 + 0 + 1


= 173 in the decimal system

Converting Any Number From Binary to Hexadecimal

To convert a binary number to hexadecimal, use the table of numeric conversions. First,
convert the number in groups of 4 bits. If the most left group has less than 4 bits,
complete the other bits with 0 each.

Imagine you would like to convert the 100011111111011011100 binary to its


hexadecimal equivalent. First create groups of 4 bits. The number becomes:

11 0001 1111 1110 1101 1100

Since the most left group has only 2 bits, you can add two 0 bits to its left to make it a
group of 4. The number becomes:

0011 0001 1111 1110 1101 1100

Using the table of numeric conversions, you get:

0011 0001 1111 1110 1101 1100


3 1 F E D C
= 0x 31FEDC

© FunctionX, Inc. 134


C++ Fundamentals Chapter 21: Exception Handling

Converting A Byte From Decimal to Binary

Remember that the maximum decimal number you can store in a byte is 255. Once you
have a decimal number, you can use the remainder operation to fill out the bits. Let's
convert the number 206.
Considering 206, find out the range of the number. Since this is greater than 128, fill out
bit 7 with 1. This produces:

128 64 32 16 8 4 2 1
1

Next, find the remainder of 206 by 128. This is 206 / 128 = Remainder(78). In C++, this
operation would be 206 % 128 = 78. The result, 78, is greater than 64. Therefore, fill out
the corresponding bit of 64, which is bit 6, with 1:

128 64 32 16 8 4 2 1
1 1

Next, find the remainder of 78 by 64. 78 / 64 = Remainder(14). This is equivalent in C++


to 78 % 64 = 14. 14 is less than 32. Therefore, the bit corresponding to decimal 32, which
is bit 5, has a binary value of 0. 14 is less than 16. Therefore, bit 4 is 0. 14 is greater than
8. Therefore, fill out bit 3 with 1:

128 64 32 16 8 4 2 1
1 1 0 0 1

Now, find the remainder of 14 by 8. 14 % 8 = 6. 6 is greater than 4. Therefore, bit 2 has a


binary value of 1.

128 64 32 16 8 4 2 1
1 1 0 0 1 1

Find the remainder of 6 by 4: 6 % 4 = 2. According to this, bit 1 will have a binary value
of 1. The remaining decimal value is 0. Therefore, bit 0 has a value of 0. The decimal
number 206 produces the following table:

128 64 32 16 8 4 2 1
1 1 0 0 1 1 1 0

= 1 1 0 0 1 1 1 0

= 11001110

= 1100 1110

Converting Any Number From Decimal to Binary

Converting a decimal number to binary takes longer because of the various comparisons
you would perform. There are, as always, various techniques available. Once again, find
the range of the number using numbers such as those:

2n-1 230 229 228 227 226 225 224

© FunctionX, Inc. 135


C++ Fundamentals Chapter 21: Exception Handling

1,073,741, 536,870,9 268,435,4 134,217 67,108, 33,554, 16,777,


etc
824 12 56 ,728 864 432 216

223 222 221 220 219 218 217 216


8,388,608 4,194,304 2,097,152 1,048,576 524,288 262,144 131,072 65,536

215 214 213 212 211 210 29 28


32,768 16,384 8,192 4,096 2,048 1,024 512 256

27 26 25 24 23 22 21 20
128 64 32 16 8 4 2 1

Consider you would like to convert the following decimal number 408340623 =
408,340,623 to binary.

408,340,623 is less than 536,870,912 but is greater than 268,435,456. Therefore , we will
start the counting at 268,435,456. Write 1 under 268,435,456.

536,870,912 268,435,456 134,217,728 67,108,864 33,554,432 16,777,216


1

At this time, we have the number as 1

Next, find the remainder of 408,340,623 by 268,435,456, which is 139,905,167.


139,905,167 is greater than 134,217,728. Therefore, write 1 under 134,217,728

536,870,912 268,435,456 134,217,728 67,108,864 33,554,432 16,777,216


1 1

The current number is 11000 0r 1 1000

Now, find the remainder of 139,905,167 by 134,217,728. This is 5,687,439. This number
is between 8,388,608 and 4,194,304. Therefore, fill each bit to 0 down to 4,194,304:

536,870,912 268,435,456 134,217,728 67,108,864 33,554,432 16,777,216


1 1 0 0 0

Since 4,194,304 is immediately less than 5, 687,439 fill it with 1.

8,388,608 4,194,304 2,097,152 1,048,576 524,288 262,144 131,072 65,536


0 1

The number becomes 1100001 or 110 0001

Then find the remainder of 5, 687,439 by 4,194,304. This produces 1,493,135. This
number is greater than 1,048,576. Therefore, write 0 under 2,097,152 and 1 under
1,048,576.

© FunctionX, Inc. 136


C++ Fundamentals Chapter 21: Exception Handling

8,388,608 4,194,304 2,097,152 1,048,576 524,288 262,144 131,072 65,536


0 1 0 1

Now the number is 110000101 or 1 1000 0101

Find the remainder of 1,493,135 by 1,048,576. The result is 444,559. The next number
greater than 444,559 is 262,144. Therefore, fill it with 1 and fill out the524,288 number
with 0:

8,388,608 4,194,304 2,097,152 1,048,576 524,288 262,144 131,072 65,536


0 1 0 1 0 1

The number has become 11000010101 or 110 0001 0101

Find the remainder of 444,559 by 262,144. This is 182415. This number is greater than
131,072. Therefore, fill out the corresponding bit with 1.

8,388,608 4,194,304 2,097,152 1,048,576 524,288 262,144 131,072 65,536


0 1 0 1 0 1 1

The current number is 110000101011 or 1100 0010 1011

The remainder of 182,415 by 131,072 is 51343 which is less than 65,536 but greater than
32,768. For this reason, the equivalent but of 65,536 is 0 and that of 32,768 is 1:

8,388,608 4,194,304 2,097,152 1,048,576 524,288 262,144 131,072 65,536


0 1 0 1 0 1 1 0

32,768 16,384 8,192 4,096 2,048 1,024 512 256


1

The current number is 11000010101101 or 11 0000 1010 1101

The remainder of 51,343 by 32,768 is 18,575. This number is between 32,768 to 16,384.
This results in:

32,768 16,384 8,192 4,096 2,048 1,024 512 256


1 1

The number becomes 110000101011011 or 110 0001 0101 1011

The remainder of 18,575 by 16,384 is 2191. This number is greater that 2048. Therefore,
the binary equivalents of both the 8,192 and 4,096 bits is 0. The bit equivalent of 2,048 is
1:

32,768 16,384 8,192 4,096 2,048 1,024 512 256


1 1 0 0 1

The number becomes 110000101011011001 or 11 0000 1010 1101 1001

The remainder of 2,191 by 2,048 is 143. The next number lower than 143 is 128. The
resulting tables are:

32,768 16,384 8,192 4,096 2,048 1,024 512 256

© FunctionX, Inc. 137


C++ Fundamentals Chapter 21: Exception Handling

1 1 0 0 1 0 0 0

128 64 32 16 8 4 2 1
1

The current number is 1100001010110110010001 or 11 0000 1010 1101 1001 0001

Find the remainder of 143 by 128. This produces 15; a number that is greater than 8 but
less than 16. The bits of 64, 32, and 16 will receive a bit value of 0. Bit 8 will have a
value of 1:

128 64 32 16 8 4 2 1
1 0 0 0 1

The current number is:


11000010101101100100010001 or 11 0000 1010 1101 1001 0001 0001

The remainder of 15 by 8 is 7, which is greater than 4. Fill out bit 2 with 1.

128 64 32 16 8 4 2 1
1 0 0 0 1 1

The current number is:


110000101011011001000100011 or 110 0001 0101 1011 0010 0010 0011

The remainder of 7 by 4 is 3, which is greater than 2. This produces:

128 64 32 16 8 4 2 1
1 0 0 0 1 1 1

The current number is:


1100001010110110010001000111 or 1100 0010 1011 0110 0100 0100 0111

The remainder of 3 by 2 is 1. This means, you will fill out bit 0 with 1:

128 64 32 16 8 4 2 1
1 0 0 0 1 1 1 1

The final number is:


11000010101101100100010001111 or 1 1000 0101 0110 1100 1000 1000 1111

The equivalent decimal number of 408340623 is binary is


11000010101101100100010001111 or 1 1000 0101 0110 1100 1000 1000 1111

This number can easily be converted from binary to hexadecimal using the table of
numeric conversions:

0001 1000 0101 0110 1100 1000 1000 1111


1 8 5 6 C 8 8 F
= 0x1856C88F

© FunctionX, Inc. 138


C++ Fundamentals Chapter 21: Exception Handling

Converting A Byte From Decimal to Hexadecimal

To convert a decimal value of a byte to its hexadecimal equivalent, again keep in mind
that the maximum number you are dealing with is 255 (this is because the operation will
be a little different later on). Find the remainder of the decimal number by 16. This
remainder will constitute the low nibble. The result will constitute the high nibble.
Therefore, use the table of numeric conversions to find the equivalent hexadecimal
number for each nibble.

Let's convert decimal 225 to hexadecimal. The remainder of 225 by 16 is 225 % 16 = 1


and the natural result is 14. Using the table of numeric conversions, decimal 14 =
hexadecimal E. Decimal 1 = hexadecimal 1. Therefore, the decimal number 225 has a
hexadecimal value of 0xE1.

As another example, Let's convert the decimal 203 to the hexadecimal system. 203 % 16
= 11 and the natural result is 12. Using the table of numeric conversions, decimal 12 =
hexadecimal C; decimal 11 = hexadecimal B. Therefore, decimal 203 = hexadecimal
0xCB

Converting Any Number From Decimal to Hexadecimal


To convert any number from decimal to hexadecimal, find the remainder of the number
by 16. This remainder would be the LO nibble. Use the quotient to find the remainder by
16; this remainder would be the second nibble. Continue until the decimal is less than 16.

Consider a decimal number such as 1325 to convert to hexadecimal. The remainder of


1325 by 16 is 1325 % 16 = 13 and the quotient is 82.
Therefore the left number will be 13.
82 % 16 = 2 and the quotient is 5. Therefore, the second number from left is 2; this would
produce 2 and 13.
Since the quotient, 5, is less that 16, it will be put to the left of the existing numbers. We
get 5 | 2 | 13. According to the table of numeric conversions, decimal 13 = hexadecimal
D. Therefore, decimal 1325 = hexadecimal 0x52D

Let’s convert decimal 462834 to hexadecimal.

462834 % 16 = 2 and the quotient is 28927


28927 % 16 = 15 and the quotient is 1807
1807 % 16 = 15 and the quotient is 112
112 % 16 = 0 and the quotient is 7

The different nibbles of this number are 7 | 0 | 15 | 15 | 2. According to the table of


numeric conversions, decimal 15 = hexadecimal F. The number is 7 | 0 | F | F | 2.
Therefore, the hexadecimal equivalent of the decimal number 462834 is 0x70FF2

Converting a Byte From Hexadecimal to Binary

The conversion of a hexadecimal number to its binary equivalent is extremely easy; the
only thing you need is the table of numeric conversions. A byte is represented with two
hexadecimal symbols. The right symbol represents the low nibble (the first 4 bits). The
other symbol is the high nibble.

© FunctionX, Inc. 139


C++ Fundamentals Chapter 21: Exception Handling

Consider a hexadecimal number such as 0x26. Referring to our table of numeric


conversions, 2 has a binary representation of 0010; hexadecimal 6 is represented in
binary as 0110. Therefore, the hexadecimal number 0x26 can be represented in binary as
00100110 which is easily read as 0010 0110. Remember that when a number has leading
0s (the 0s on the left side of the number), the computer ignores those 0(s). As a result, the
computer would display 00100110 as 100110

Let's convert the hexadecimal 0xD5 to binary. The binary representation of D is 1101.
The binary representation of 5 is 0101. Therefore, hexadecimal 0xD5 is represented in
binary as 11010101 or 1101 0101

Converting Any Number From Hexadecimal to Binary


To convert any hexadecimal number to binary, once again, you use the table of numeric
conversion. Each hexadecimal digit will be converted to its binary equivalent.

Consider you would like to convert the 0x72FA to binary. Using the table of numeric
conversions:

7 = 0111
2 = 0010
F = 1111
A = 1010

Therefore, hexadecimal 0x72FA is represented in binary as 011100101111010. This can


be read as 0111 0010 1111 1010. The computer would display it as 11100101111010

Converting a Byte From Hexadecimal to Decimal


A byte is made of 8 bits. This means, the highest hexadecimal value you can represent
with a byte is 0xFF and the highest decimal value is 255. To convert a hexadecimal
number to decimal, multiply each hexadecimal digit to its 16 base value. Starting on the
left side, which is the low order bit, use the following table:

161 160

Consider a hexadecimal byte represented with 0x24, to convert it to decimal, you would
use:

2 * 161 + 4 * 160 = (2 * 16) + (4 * 1) = 32 + 4 = 36

Therefore, the decimal equivalent of the 0x24 is 36

Consider another hexadecimal number as 0x5D. To convert it to decimal, you would


write:

5 * 161 + D * 160 . If you look at the table of numeric conversions,

Table of Numeric Conversion


Decimal Hexadecimal Binary
0 0 0000
1 1 0001
2 2 0010

© FunctionX, Inc. 140


C++ Fundamentals Chapter 21: Exception Handling

3 3 0011
4 4 0100
5 5 0101
6 6 0110
7 7 0111
8 8 1000
9 9 1001
10 A 1010
11 B 1011
12 C 1100
13 D 1101
14 E 1110
15 F 1111

you would see that the decimal value of hexadecimal D is 13. Therefore, the conversion
would be performed as follows:

5 * 161 + D * 160 = 5 * 161 + 13 * 160 = (5 * 16) + (13 * 1) = 80 + 13 = 93. Therefore,


hexadecimal 0x5D = decimal 93.

Converting Any Number From Hexadecimal to Decimal


To convert a hexadecimal number to decimal, multiply each digit of the hexadecimal
number to its 16-base equivalent. Starting from the

etc 166 165 164 163 162 161 160

Consider a hexadecimal number such as 0x80329. To convert it to decimal, you would


write:

8 * 164 + 0 * 163 + 3 * 162 + 2 * 161 + 9 * 160 =


= (8 * 65536) + (0 * 4096) + (3 * 256) + (2 * 16) + (9 * 1)
= 524288+ 0 + 768+ 32 + 9 = 525097

Therefore, hexadecimal 0x80329 = decimal 525097

Consider another hexadecimal number such as 0xBE45A6. To convert it to decimal,


using the base 16, you would write an equation as:

B * 165 + E * 164 + 4 * 163 + 5 * 162 + A * 161 + 6 * 160

Refering to the table of numeric conversions, you would find out that the decimal
equivalent of hexadecimal B is 11, that of E is 14, and that of A is 10. Therefore, you
would rewrite the equation as:

11*165 + 14*164 + 4*163 + 5*162 + 10*161 + 6*160

= (11 * 1048576 ) + (14 * 65536) + (4 * 4096) + (5 * 256) + (10 * 16) + (6 * 1)

= 11534336 + 917504 + 16384 + 1280 + 160 + 6

= 12469670 = 12,469,670

© FunctionX, Inc. 141


C++ Fundamentals Chapter 21: Exception Handling

Therefore, hexadecimal 0xBE45A6 = decimal 12469670 or 12,469,670

© FunctionX, Inc. 142


C++ Fundamentals Chapter 21: Exception Handling

Index
_exit().....................................................................361 Backspace ................................................................ 49
Base 10 .................................................................... 41
beam.......................................................................141
++.............................................................................. 87 Bell ............................................................................ 49
+=............................................................................109 binary .....................................................................183
binary combinations.............................................. 44
< binary digit .............................................................. 43
Binary Operator....................................................667
< 184
Binary System ........................................................ 40
<<............................................................................672
bit .............................................................................. 43
<=............................................................................185
Bitwise &...............................................................110
= Bitwise AND.........................................................681
Bitwise NOT................................................110, 681
= 648 Bitwise OR...................................................111, 681
==............................................................................180 Bitwise Shift Left................................................681
> Bitwise Shift Right.............................................681
Bitwise XOR .........................................................681
> 186 Bitwise-exclusive OR..........................................112
>=...................................................................187, 667 bool ....................................................................38, 50
A Boolean.................................................................... 50
Borland ..................................................................176
Abnormal Termination........................................362 break........................................................................ 38
abort().....................................................................362 Built-in Classes
abs...........................................................................177 cin .......................................................................355
Access Level.........................................................317 Built-in Functions................................................175
acos.........................................................................176 _exit() ................................................................361
addition.................................................................... 93 abort() ................................................................362
Additive Assignment .........................................681 clrscr() ...............................................................679
Address .................................................................681 exit()...................................................................360
algebra....................................................................175 gets() ..................................................................356
Algebraic Operators ............................................103 resetiosflags()...................................................351
alphabetic Chanracters .......................................... 40 scanf()................................................................356
ampersand ............................................................... 88 setiosflags().......................................................350
AND Assignment ................................................681 system() .............................................................679
Apostrophe............................................................... 49 terminate().........................................................363
applications............................................................. 39 tolower()............................................................359
array........................................................................104 toupper()............................................................358
asin..........................................................................176 width() ...............................................................350
asm........................................................................... 38 Byte .......................................................................... 45
assignment.............................................................118
C
Assignment..........................................................681
associative............................................................... 98 C 353
atan .........................................................................176 C++ Names ............................................................. 37
atan2.......................................................................176 C++ Standard........................................................175
auto .......................................................................... 38 Calling a Function................................................119
axis ..........................................................................141 camera ....................................................................189
Carriage Return ...................................................... 49
B case.......................................................................... 38
backslash................................................................. 49 case-sensitive.......................................................... 38

© FunctionX, Inc. 143


C++ Fundamentals Chapter 21: Exception Handling

cassert.....................................................................176 Decimal System ..................................................... 41


catch ........................................................................ 38 decrement ....................................................... 87, 107
ceil ..........................................................................176 default..................................................................... 38
cfloat......................................................................... 68 Default Constructor....................................460, 485
char .......................................................................... 38 define........................................................................ 66
character................................................................341 Definitions
characters................................................................. 46 Addition............................................................... 93
cin ..............................................................38, 39, 355 Bit ......................................................................... 43
Circle ......................................................................142 Boolean................................................................ 50
class ......................................................................... 38 Byte...................................................................... 45
classes ....................................................................104 Class...................................................................313
Classes Computer............................................................. 13
cout.....................................................................341 Constant............................................................... 66
ostream..............................................................672 Constant Reference .........................................152
clients .....................................................................317 Copy Constructor.............................................485
climit ........................................................................ 68 Curly Brackets..................................................104
Closing Curly Bracket.........................................119 Default Constructor.........................................460
clrscr()....................................................................679 Division.............................................................101
cmath......................................................................176 do...while ...........................................................203
combination ............................................................ 38 Escape Sequence................................................ 49
Comma..................................................................681 Exception ..........................................................366
comparison............................................................180 for.......................................................................204
compiler.................................................................120 Function.............................................................118
Computer................................................................. 13 if 190
Condition Expression ........................................681 if...else...............................................................195
Conditional Operator...........................................196 inline ..................................................................157
conditional statements.........................................104 Method...............................................................329
consecutive.............................................................. 43 Multiplication..................................................... 98
Console Applications..........................................341 Namespace.......................................................... 68
const ................................................38, 67, 148, 395 NULL .................................................................. 68
constant..................................................................650 Precedence........................................................116
Constant Methods ................................................397 Reference ............................................................ 88
Constant Reference.....................................152, 580 Remainder.........................................................102
Constructor............................................................460 return..................................................................121
sizeof.................................................................... 90
continue .................................................................. 38
convert ...................................................................110 static...................................................................161
Copy Constructor.................................................485 string.................................................................... 81
cos...........................................................................176 switch.................................................................198
cosh.........................................................................176 Unary ................................................................... 86
counter...................................................................189 using..................................................................... 71
Word .................................................................... 51
cout ........................................................ 38, 290, 341
cstdlib .....................................................................176 delete ....................................................................... 38
ctype.h....................................................................358 Destructor..............................................................487
Curly brackets.......................................................104 Dev-C++................................................................166
Dialog Boxes
Curly Brackets............68, 171, 192, 198, 315, 366
cursor........................................................................ 39 C++ Builder's New Items ...............................165
KDevelop New Items ......................................165
D Microsoft Visual C++' New...........................167
digit.................................................................. 40, 359
data ........................................................................... 42 digits......................................................................... 38
Data Output...........................................................341 dimension.....................................................104, 251
data type .................................................................. 39 diminish.................................................................109
Data Types direction.................................................................116
bool ...................................................................... 50 div ...........................................................................177
datum........................................................................ 42 division ..................................................................101
decimal..........................................................348, 353 Division..................................................................681

© FunctionX, Inc. 144


C++ Fundamentals Chapter 21: Exception Handling

Divisional Assignment......................................681 Daily() ...............................................................157


do.............................................................................. 38 Earnings()..........................................................134
do...while ...............................................................203 FahrenheitToCelsius() ....................................130
double...................................................................... 38 GetBase() ..........................................................166
Double Quote .......................................................... 49 GetCelsius()......................................................130
double-precision number....................................341 GetFahrenheit ...................................................123
driver......................................................................188 GetHeight().......................................................166
dynamic_cast........................................................ 38 GetHours() ........................................................127
getline() ...................................................... 82, 292
E GetName() ........................................................127
GetNumberOfPages ........................................123
else........................................................................... 38
GetOriginalPrice() ...........................................152
endl........................................................................... 33
GetRadius().......................................................166
enum........................................................................ 38 Introduction......................................................125
Equal ......................................................................681 MomentOfInertia() ........................ 141, 149, 166
equality ..................................................................180 Monthly()..........................................................157
Escape Sequence.................................................... 49 Perimeter()........................................................148
Exception Handling....................................363, 366 printf() ...............................................................344
exceptions..............................................................104 PurchasePrice ...................................................129
exit().......................................................................360 puts()..................................................................343
exp ..........................................................................176 Receipt()............................................................152
explicit..................................................................... 38 RequestSalary()................................................157
exponent ..............................................................354 setprecision() ....................................................351
extern ...................................................................... 38 setw() .................................................................346
ShowSchoolName ...........................................123
F SquareArea .......................................................125
fabs .........................................................................176 Starter()..............................................................160
false...........................................................38, 40, 180 strcat()................................................................302
fill().........................................................................347 strchr() ...............................................................308
finance....................................................................175 strcmp() .............................................................306
Flags strcpy()...............................................................303
ios strdup() ..............................................................305
left .............................................................350 stricmp()............................................................307
fixed ..........................................................351 strlen() ...............................................................302
scientific ...................................................352 strlwr() ...............................................................309
float.......................................................................... 38 strncat()..............................................................303
floating number....................................................341 strncmp() ...........................................................307
floor........................................................................176 strncpy() ............................................................304
flow.........................................................................366 strnicmp()..........................................................307
fmod .......................................................................176 strrchr()..............................................................308
for .................................................................... 38, 204 strupr()...............................................................309
Form Feed ................................................................ 49 Weekly()............................................................157
frexp .......................................................................176 Yearly() .............................................................157
friend ..................................................... 38, 577, 652 G
function........................................................... 68, 118
Function Overloading..........................................140 geometry ................................................................175
functions................................................................104 getline().................................................................... 82
Functions gets().......................................................................356
Area().................................................................140 goto .......................................................................... 38
assert() ...............................................................176 Greater Than.......................................................681
BiWeekly() .......................................................157 Greater Than or Equal .....................................681
BoxArea() .........................................................139
CalcInterest()....................................................171 H
CalcMaturityValue().......................................171 Header File ............................................................408
CalculateNetPrice()....................... 136, 137, 152 Header Files
cputs()................................................................344

© FunctionX, Inc. 145


C++ Fundamentals Chapter 21: Exception Handling

ctype.h ...............................................................358 L
hex ..........................................................................348
hexadecimal .................................................348, 353 labs..........................................................................177
Hexadecimal System............................................. 41 Latin ......................................................................... 41
HI bit ........................................................................ 43 law ..........................................................................188
High Order bit ........................................................ 43 ldexp .......................................................................176
Horizontal Tab ......................................................... 49 ldiv ..........................................................................177
human.....................................................................189 Left Shift Assignment .......................................681
Left Shift Operator << ........................................113
I Length of a string.................................................342
Less Than .............................................................681
if 38, 190
if...else....................................................................194 Less Than or Equal ...........................................681
Line Feed................................................................. 49
include....................................................................410
increase.................................................................... 87 LO bit ....................................................................... 43
increment................................................................. 87 log...........................................................................176
log10.......................................................................176
index.......................................................................104
Initializer...............................................................457 Logical AND .........................................................681
Initializing a Class...............................................327 Logical NOT .........................................................681
inline ...................................................... 38, 157, 336 Logical NOT Operator........................................182
Input Operator......................................................674 Logical Operations ..............................................192
int.............................................................................. 38 Logical Operators ................................................187
integer....................................................................341 Logical OR ............................................................681
Intel........................................................................... 43 long .......................................................................... 38
interrupt.................................................................. 38 Low Order............................................................... 43
iomanip ..................................................................346 lowercase.......................................38, 307, 309, 358
ios::scientific .........................................................352 M
iostream.h ..............................................................673
isalnum()................................................................360 main ......................................................................... 38
isalpha() .................................................................359 main().....................................................................360
isascii()...................................................................360 Member Access Operator...................................318
isdigit()...................................................................359 memory .................................................................... 37
isgraph().................................................................360 method ...................................................................329
islower().................................................................359 Methods
isprint() ..................................................................360 fill() ....................................................................347
ispunct().................................................................360 put()....................................................................341
isspace().................................................................360 width() ...............................................................345
istream....................................................................674 write() ................................................................342
isupper().................................................................359 Microsoft Visual C++ .Net.................................166
isxdigit() ................................................................359 modf .......................................................................176
Modulating Assignment...................................681
K Modulus ................................................................681
Keywords ..............................................................367 Moment of Inertia ................................................141
catch...................................................................366 monitor..................................................................... 39
char.....................................................................289 Most Significant..................................................... 43
const............................................................ 67, 395 multiplication.......................................................... 98
for.......................................................................204 Multiplication .......................................................681
friend..................................................................577 Multiplicative Assignment ...............................681
namespace.........................................................429 mutable................................................................... 38
operator..............................................................647
protected............................................................602 N
public .................................................................317 namepsace.............................................................170
static...................................................................161 namespace..............................................38, 68, 344
try .......................................................................366 namespaces ...........................................................104
Negation ...............................................................681
negative.................................................................... 42

© FunctionX, Inc. 146


C++ Fundamentals Chapter 21: Exception Handling

Nesting a namespace............................................. 77 Pre-increment .....................................................681


new........................................................................... 38 printf()....................................................................344
New Line .................................................................. 49 private ...........................................38, 317, 572, 652
nibble........................................................................ 43 Programming .......................................................... 13
normal....................................................................366 programming syntax.............................................. 98
Not Equal..............................................................681 Programs
Null ............................................................................ 49 Conditions1.......................................................189
NULL....................................................................... 68 Conversions1....................................................114
nullify .....................................................................182 Function1..........................................................123
numeric symbols .................................................... 40 GCS1 ................................................................... 95
GCS2 ................................................................... 99
O Multiply1............................................................. 98
Opening Curly Bracket .......................................119 Remainder1.......................................................102
operand .................................................................... 86 Subtraction1........................................................ 96
operator ............................................................38, 86 Projects
operator+() ............................................................653 Functions1.........................................................123
operator<<() ..........................................................672 protected .............................................. 38, 602, 652
operator>>() ..........................................................674 public .............................................................. 38, 317
Operators
Q
! 182
!= 183 Question Mark ......................................................... 49
% 353
~ 488 R
< 184 Radius ....................................................................142
<< .......................................................................672 rand.........................................................................177
<= .......................................................................185 Random Access Memory (RAM) ....................... 37
== .......................................................................180 Rectangle ...............................................................141
> 186 Rectangular Parallelepiped.................................602
>= .......................................................................187 reference ................................................ 88, 133, 681
Bitwise AND ....................................................111 register.................................................................... 38
Bitwise NOT ....................................................110 regulations.............................................................188
Bitwise OR .......................................................111 reinterpret_cast.................................................... 38
Bitwise-exclusive XOR..................................112 remainder...............................................................102
Curly Brackets..................................................119
Reserved words...................................................... 38
hex......................................................................348 resetiosflags() .......................................................351
Left Shift Operator <<....................................113
return.............................................................. 38, 121
Right Shift Operator >>..................................114
Right Shift Assignment ....................................681
sizeof.........................................................251, 342
Right Shift Operator >> ......................................114
OR Assignment...................................................681
ostream...................................................................672 S
Output Operator...................................................671
scanf() ....................................................................356
P scope.......................................................................104
Scope Access Operator......................................... 69
parentheses ............................................................103
Semi -circle ............................................................142
Parentheses.........................................................681 semi -colon.............................................................317
people.....................................................................188 sentence.......................................................... 83, 341
picture ....................................................................189
sequence.................................................................. 40
Plus Sign ...............................................................681 setiosflags()...........................................................350
positive..................................................................... 42 setprecision() ........................................................351
Post-decrement ..................................................681 setw()......................................................................346
Post-increment ...................................................681 short................................................................ 38, 191
pow.........................................................................176 short integer..........................................................341
precedence.............................................................116 SHRT_MAX........................................................... 67
precision ................................................................354 SHRT_MIN ............................................................ 67
Pre-decrement....................................................681 signed .......................................................38, 42, 353

© FunctionX, Inc. 147


C++ Fundamentals Chapter 21: Exception Handling

sin ...........................................................................176 V
single-quotes ........................................................... 49
sinh .........................................................................176 Vertical Tab.............................................................. 49
Size of data ..........................................................681 virtual....................................................................... 38
sizeof.......................................38, 90, 251, 342, 681 void........................................................................... 38
sound........................................................................ 49 volatile..................................................................... 38
sprintf() ..................................................................310 W
sqrt..........................................................................176
Square brackets ....................................................104 wchar........................................................................ 38
Square Brackets....................................................289 while......................................................................... 38
srand.......................................................................177 width()....................................................................350
statement................................................................190 word.......................................................................... 51
static ............................................................... 38, 161
static_cast.............................................................. 38 X
std..............................................................38, 80, 344 XOR Assignment................................................681
stdio........................................................................344
Stream Operators .................................................671
string........................................................................ 38
struct........................................................................ 38
structures ...............................................................104
Subtraction ..........................................................681
Subtractive Assignment...................................681
switch ............................................................. 38, 198
system() .................................................................679
T
tag ...........................................................................354
tan ...........................................................................176
tanh.........................................................................176
terminate() .............................................................363
this ..........................................................................521
throw ....................................................................... 38
tilde................................................................110, 488
timer .......................................................................189
tolower()................................................................359
toupper() ................................................................358
Traffic Light..........................................................188
Trailing zeros ......................................................354
Triangle ..................................................................143
trigonometry .........................................................175
true............................................................38, 40, 180
try ............................................................................. 38
Typecast ...............................................................681
typedef ..............................................................38, 65
typeid....................................................................... 38
typename ............................................................... 38
U
unary......................................................................... 86
underscore ............................................................... 38
union........................................................................ 38
unsigned ..................................................38, 42, 353
uppercase.......................................38, 307, 309, 350
using ..................................................................38, 71

© FunctionX, Inc. 148


C++ Fundamentals Chapter 21: Exception Handling

© FunctionX, Inc. 149

Vous aimerez peut-être aussi