Chapt 8. Basic object-oriented programming

8.13 Friend functions and classes: (Learn C++)

friend function: function that can access private member of the class

friend class: if class A is friend of B, then B can access private member object A’s

∗ ‘friend’ must be declared inside of class, but in can be private or public section

∗ friend functions is not, rigorously, member of the class

∗ friend relationship is asymmetric, not symmetric


Chapt 9. Operator Overloading

9.1. Introduction to Operator Overloading (Learn C++)

A. Constraints

1. cannot overload

a. ‘? :’ – Conditional operator

b. ‘sizeof’ – sizeof operator

c. ‘::’ – scope resolution

d. ‘.’ – member selector

e. ‘.*’ – member pointer selector

2. cannot create new operator

3. cannot rename existing operator

4. at least one of operand should be user-defined type

5. cannot change number of operands

6. cannot change default ‘precedence’ and ‘associativity’

9.2. Overloading the arithmetic operators (+, -, *, /) (Learn C++)

By using keyword ‘friend’, you can overload arithmetic operator

Source Code

9.3. Overloading the I/O operators (>>, <<) (Learn C++)

Input Operator(‘<<‘)   : std::cin is type of ‘isream’

Output Operator(‘>>’): std::cout is type of ‘ostream’

Source Code

9.4. Overloading using member functions (Learn C++)

KEY: left operand is fixed – becomes implicit ‘*this’ object

Not every operator can be overloaded as member functions

i.e. ‘>>’, ‘<<‘

Not every operators can be overloaded as friend functions

i.e. ‘[]’, ‘=’, ‘->’

Source Code

9.5. Overloading unary operator (+, -, !) (Learn C++)

implement as member function, because it operator on itself

9.6. Overloading the comparison operator (<,>,==) (Learn C++)

Source Code

9.8. Overloading the subscript operator ‘[]’ (Learn C++)

A. operator[] returns a ‘l-value’ (reference)

int& operator[] (const int index) { return array[index]; }

9.10. Overloading Typecasts (Learn C++)

• No return type syntax included

Source Code

9.11. & 14. Copy constructor and Overloading assignment operator

both do same function, but called in difference cases

A. Copy Constructor (Learn C++)

parameter must passed by reference, not by value

When called

1. instantiating and initializing a new object from already existing object

2. passing an object by value

3. object is returned from a function by value

B. Assignment Operator (Learn C++)

default memberwise assignment operator provided by C++ compiler

should be member function to ease accessing private field

should check to avoid self-assignment

return ‘*this‘ so can chain the assignment operator

9.12 Shallow vs Deep copying (Learn C++)

A. Shallow Copy(=Memberwise Copying)

C++ provide default shallow copy constructor and assignment operator

B. Deep Copy

Must implement your won copy constructor and assignment overloading in case class has dynamically allocated variables

C. Prevent Copy

Place into private field, if you don’t want your class object to be copied

Chapt 11. Inheritance

11.1. Introduction to Inheritance (Learn C++)

‘Inheritance’ is one of two ways to build complex class (the other is ‘composition’)

reusability‘ is fundamental idea of inheritance

base (or parent): the object being inherited from i.e. fruit

derived (or child): the object doing inheriting i.e. apple

by default, children inherit all of properties from parent

children can redefine, hide inherited properties and add new properties

11.2. Basic inheritance in C++ (Learn C++)

derived class inherit all of member variables and functions of base class

inheritance hierarchy: must be from ‘general’ to ‘specific’

11.3. Order of construction of derived class (Learn C++)

execute constructors from base(top) to derived(leaf) following inheritance tree

∗ Order of destruction: from derived(leaf) to base(top)

Source Code

11.4. Constructors and initialization of derived class (Learn C++)

C++ allows to set specific base constructor to call before derived constructor

 Source Code

11.5. Access Specifiers (Learn C++)

A. Member Access Specifiers

1. Public: derived and outside can directly access it

3. Private: derived and outside can’t directly access it

3. Protected: only derived can access it

Source Code

B. Inheritance Access Specifiers

1. Public(mostly used): all members inherited maintain member access specifiers

2. Private(rarely used): all members inherited become private

3. Protected(not used): public members inherited become protected

Note! : It only affect outside access, not in immediate derived class

Source Code

11.6. Add, Redefine, Insert and Hide (Learn C++)

A. Add new functionality

can define new functions in derived

Source Code

B. Redefine inherited functionality : Polymorphism

can override inherited functions in derived what makes ‘polymorphism

 ∗ redefined function does not inherit the access specifier

Source Code

C. Insert inherited functionality

can insert inherited function in another function → reusability

* recommend use scope resolution operator(::) to make explicit

Source Code

D. Hide inherited functionality

can change access specifier of inherited functions directly accessible in derived

* ‘private’ can’t change to public or protected, because it is invisible in derived

Source Code

11. 7. Multiple Inheritance (Learn C++)

Conclusion: It turns out that most of problems can be handled by ‘Single Inheritance’

 Therefore, think once again before using multiple inheritance

 because, it can lead to complex, naming conflict and diamond problem

11. 8. Virtual base classes (Learn C++)

‘virtual’ keyword means base class will be created later and shared on inheritance

therefore, it is responsible for most derived to construct virtual base class

can handle the diamond problem one of issue in multiple inheritance

Chapt 13. Input and Output (I/O)

13.1. Input and Output (I/O) streams: (Learn C++)

I. Introduction

Basically, I/O in C++ is implemented with streams

Abstractly, stream is just a sequence of characters can be accessed directly

II. Abstraction

A. input stream

used to hold input from a data producer i.e. keyboard, network, file

B. output stream

used to hold output for a data consumer i.e. printer, monitor, file

∗ dont need to know how streams intract with actual devices, left up to OS

III. I/O Classes

‘ios’ is base class of both input and output streams, and inherited from ‘ios_base’

A. ‘istream'(>>)

primary class used for input stream. the extraction operator(>>) is used to remove value from the stream

B. ‘ostream'(<<)

primary class used for output stream. the insertion operator(<<) is used to insert value into the stream

∗ ‘_withassign’, stream classes wont be handled directly

I/O Class Hierarchy (Learn C++)

IV. standard streams

pre-created and connected stream object for a program by its environment

A. ‘cin’: object of istream_withassign class for standard input

B. ‘cout’: object of ostream_withassign class for standard output

C. ‘cerr’: object of ostream_withassign class for standard error, unbuffered

D. ‘clog’: object of ostream_withassgn class for standard error, buffered

∗ unbuffered: processed directly ↔ buffered: temporary stored and processed

13.2. Input with stream: (Learn C++)

∗ all of the I/O objects and functionality prefixed with ‘std’ namespace

I. manipulator:setw()

limit # of bytes read in from the stream for each call

II. extraction operator: ‘>>’

• C++ has predefined extraction operator for all of built-in data types

• Discard white-space(i.e. blank, tab, newline) when read

III. useful member functions:

• ‘get()‘: extract one character from the stream

• ‘getline()’

· istream::getline() – extract characters until delimiter or specific size

· std::getline() – extract characters from stream into string

• ‘ignore()‘: extract and discard characters from the input stream

• ‘peek()‘: return next character without extracting from the input stream

• ‘unget()‘: return last character back into stream, can be read again

• ‘putback(char c)‘: put character back into the stream, can be read by next call

13.3. Output with ‘ostream’ and ‘ios’: (Learn C++)

ostream is derived from ios, so formatting can be controlled by ios’s options

A. formatter: there are two ways to change formatting options:

1. flag: group of bool variables can be turned on/off

setf(): turn formatting option on i.e. cout.setf(ios::showpos)

unsetf(): turn formatting option off i.e. cout.unsetf(ios::showpos)

2. manipulator: objects placed in the stream affecting the way of output

i.e. cout << hex << 27 << endl → 1B

B. useful formatter:

• ‘boolalpha‘: print boolean “true” or “false”, instead of 0 or 1

• ‘showpos‘: if set, positive number prefixed with ‘+’

• ‘uppercase‘: use upper or lower case letter ↔ ‘nouppercase’

• ‘dec‘, ‘hex‘, ‘oct‘: print value in decimal, hexadecimal and cotal

C. Precision, Notation, Decimal point:

• ‘fixed’: decimal notation for floating-point value

• ‘scientific’: scientific notation for floating-point value

• ‘setprecision(int)’: set # of decimal places or significant digits displayed

• ‘showpoint’: show decimal point and trailing zero(0)s

D. Width, Fill and Aligned:

• ‘setw(int)’: set field-width for input and output operation

• ‘setfill(char)’: set character to fill the blank, default is blank

• ‘left’: left-aligned sign and value

• ‘right’: right-aligned sign and value

• ‘internal’: left-aligned sign and right-aligned value

13.4. Stream class for strings: (Learn C++)

object of this class use string buffer to hold data for processing later i.e. parsing

there are 6 string stream classes, but you may use the stringstream class mainly

because stringstream is derived from iostream it support common operation and

functions i.e. ‘<<‘, ‘>>’, ‘getline()’, ‘ignore()’, ‘clear()’, ‘fill()’

Code Example

13.5. Stream states and input validation: (Learn C++)

I. stream state

is the signal for indicating certain condition occurred in using the stream

four bits consisting of  bitmask to represent stream error state flag, iostate

• goodbit: no error occurred

• badbit: fatal error occurred

• failbit: error(but not fatal) occurred

• eofbit: reached end of file

if any bits are set except a goodbit, then further stream operations are ignored

ios provide functions check whether the state flag set i.e. good(), bad(), fail(), eof()

* see state flag functions part is ios

II. Input Validation

to check whether the input data meet the criterion: mainly string and numeric

C++ not provide high-level one to check validation, but useful primitive functions

so you can build your own validator by composing the primitive blocks

A. String Validation

best way to validate string is checking each characters meet the criterion

cctype provide useful function for character validation i.e. isalpha(), isdigit()

Code Example

B. Numeric Validation

1. via stream operation and stream state flag: Code Example

• if first character in the input stream is not digit, fail flag set occurred

2. via string conversion and exception handeling: Code Example

• see the string conversion function part, in string

13.6. Basic file I/O: (Learn C++)

All of file I/O classes are derived from normal I/O classes, just few things added

There are three basic file I/O classes

• ‘ifstream‘: derived from istream – input

• ‘ofstream‘: derived from ostream – output

• ‘fstream‘: derived from iostream – input/output

can simply instantiate file I/O object with just file name path as a paramter

13.7. Random file I/O: (Learn C++)

I. File Pointer

every file stream class have their own file pointers used to keep track of position in file for read / write operation from / to the file

II. Random File Access

if the file only can be accessed sequentially, it would become very inefficient

A. File pointer:

file pointer make random file access possible

istream::seekg(): set file pointer at the position of next character extracted

ostream::seekp(): set file pointer at the position of next character inserted

istream::tellg(): return absolute position of file pointer on input stream

ostream::tellp(): return absolute position of file pointer on output stream

∗ ‘g’:get – input , ‘p’: put – output

B. std::fstream: read / write

because ftsream is derived from iostream, and iostream is derived from both istream and ostream, it support both read / write operation on file.

however you must call seekg() or seekp() before, if you want switch context from read to write or from write to read. Otherwise something weird will occur

Chapt 14. Template

14.1 Function Template (Learn C++)

Write one function, Work with different parameter types


14.2 Function Template Instance: (Learn C++)

function template with actual parameter type is compiled at run time.

14.3 Template Classes: (Learn C++)

template class is useful for containers dealing with various data types

template class is compiled at run time. so if you don’t use it, never compiled