## Friday, 13 April 2012

### Exam Reference Book (my notes) Part2

int a =5 declaration and definition extend details: 1-2-3-4 separate method

Each byte has a unique address e.g. above 2ff2b8c4 (4 bytes later) 2ff2b8c8
Int x; address is 1st byte: Int type consists of 4 bytes =32 bits à sizeof (int/variable) rn 4 à 2nd variable…&x+1
Char y; address is 5th byte correspond variable y: Char type consist of 1 byte=8bits
Address 2ff2b8c4-7 (4 bytes-32bits) can store (000…11) = can store data (3/true/’c’…depend on type)
e.g. unsigned Char y – 01101110= store data ’n’ or ‘1’; char=int+letters
e.g. unsigned int x-01101111= store data 111 %X,%d; int=int only
e.g. signed(default) int x- 10000001=store data –1st i.e. –128- 0th so –127 (if 16bit, -ve is leftmost)
p.s. 234à-234=inverse bit+1

 char:           1 bytesshort:          2 bytesint:            4 byteslong:           4 bytes Signed int - -128 to 127 (data) - defaultUnsigned char – 0-255Overflow if use more than assigned bits127+1=-128 (111…+1=1000000=000000) Moreover: operators Arithmetic operators For int, return intp.s. x+y return x, x=y return x; bool:           1 bytes true false keyword data (use 1 bit) Relational operatorsFor int, return boolLogical operatorsFor bool, return boolShort circuit evaluation makes skip statement wchar_t:        2 bytesint*: 4 bytes on 32 bit float:          4 bytesdouble:         8 byteslong double:    8 bytes Becareful round off values as not accurate Int into Bit binary Conversion between binary and decimal 5=00000101-5=00000101 flip 11111010+1(add 1 for negative 0 and positive 0) Bit operatorFor int, return int(x and y are int variable and convert to bits and use operator, and convert to int and return)x<< >> y – shift y bits~xx & | ^ y – each bit in x y^ - or but TT=F<< >> & | ^ =

Print bits logic:
 void prnBits(unsigned int val){  for(int i = sizeof(int)*8-1;i>=0;i--){ //32bits, i=31    printf("%d", (int)isOn(val, i));//argument evaluate to 110 and 31  }}//pass the variable to be printed to prnBits to print all bits after function//determine number of bits and start print bit by bit with the 31st bit (leftmost) and pass it to isOn bool isOn(unsigned int val, int bitNo){//110,31 110=01101110  unsigned int m = 1 << bitNo; //1000 0000 0000 0000 0000 0000 0000 0000  if((val & m) != 0)// ==0 so return false (int) false=0    return true;  else    return false;}//pass the variable and the bit to be printed e.g.31st bit//shift 1 the bit position (bitNo) and use it to & variable :// 1&1 !=0 will return true (1) which is the bit ; 1&0 ==0 will return false(0) which is the bit; print the bit//repeat for remaining bits

Variable type value conversion –

each data of this type can convert to another data of that type by binary number

 Promotion of variable value in exp (arithmetic conversion) – by compilerchar and short is implicitly promoted to int in exp (1byte to 4byte, watch out the bits!)unsigned Char y – 01101110= store data ’n’ or ‘1’; int a=00110001= store data 49; p.s. char=int+letterschar 00110001 ‘1’ will convert to 0x31/49 in integer valuechar 00110001 ‘n’ will convert to 110/0x6e in integer valueStandard conversion of variable value in exp (arithmetic conversion) – by compiler2+5.0- integer value (lowest of promotion) widen to higher double value, etc (e.g. pter to void pter) in an exp Type casting of variable value exp – by programmerint a/double b – double value return but I need int value so that (int) (int a/double b)(int) exp = int (exp) // c-function like syntax // = `static_cast(nValue / 2.5);``may narrowing` Implicit type conversion = (assignment conversion) – by programmer (same as type casting + store in variable)type var = exp/value/variable ; exp value variable convert to value which determined by typemay narrowingstudent josee=1234; single argument constructor is used if convert to a class - process will be using the single argument constructor (since there is only one value 1234) to construct a temporary object and then copy to josee by assignment and delete temp object by destructor example: all keep the value of variable stored but changed at that momentint ch = 'A' / cword;                               //ch is assigned 65 and cword is still ‘A’printf("%d, %c\n", ch, ch);                 //65 Aeach data of this type can convert to another data of that type e.g.true false keyword data convert to 1 0 integer data >0 0 integer data convert to true false bool data `Inheritance and Pointer, Reference – Implicit type conversion (3)``Derived cDerived(5); ``Base &rBase = cDerived;  ``(Derived &rDerived = cDerived; - should store Derived type variable)``Base *pBase = &cDerived;``  ``(Derived *pDerived = &cDerived; - should store address- store Derived type data)``à`` Reason is cDerived, Derived (apple) type, is actually Base (fruit) type``à`` Result: cast into Base type value (only members of Base from cDerived is extracted), assign to rBase and pBase ``à``Problem: ``rBase.GetName(), pBase->GetName()use Base class and cannot use any Derive class methods ``à`` Virtual Function to use Derive class method (Look LOWER)` Above 2,3 are old C cast we should use 4 new C++ cast because old C cast is dangerous as can convert any typ

Variable Address Value Type- Variable correspond address (declare), store changing data (define), which determined by type. Must initialize (define l-value=r-value), otherwise who knows value

Int
int chris –
Chris correspond address, store integer ( 1/’c’ (value) / num(variables/exp with int value) ), which determined by int ;
Student
Student chris –
Chris (fields) correspond address, store data by Constructor (as usually private fields and cannot use = ), which determined by Student ( field types) ;
Char/
Char []

char c[4] –
c[0] correspond address (constant address c/c[]), stores character ( ‘a’ (value) / variables/exp with char value or {1,2,3,4,5,6,7,8,9,0} for c[1] to c[10] ), which determined by type char ;
p.s. [constant] when declare; omit if define (initialize) at the same time as compiler will cal the size
p.s. c[0][0] same as above…[0][1] has address c+1

Int*
int* ivan –
repeat-address stores integer (1, ‘c’ (value)…), which determined by int*’s int, variable=*address(ivan)
Student*
student* ivan –
repeat-address stores student type data = integer+char (1, ‘c’ (value)…), which determined by student*’s student= field types (see pic), variable=*address(ivan)
Void*
Int* ivan= &num ; *ivan valid
Void* ivan= &num/&char/&double… ; *ivan is not valid (also ivan+1) unless
Int* chris= (int*) ivan; *chris
Char* []
Char* c[4] –
repeat-address stores character ( ‘a’ (value) / variables/exp with char value or {1,2,3,4,5,6,7,8,9,0} for c[1] to c[10] ), which determined by type char ;
Student* ivan;
ivan= new Student ; à ivan=new (&a); Student (*ivan); (Student a;)  //5,2 reverse normal order, do at same tim
ivan= new Student[size] ; à ivan=new[size] (arrayconstantaddress); Student (*ivan)[size]; //5,3 reverse
ivan= new Student ( parameter ) ; à student=new; Student (*ivan) ( parameter );
int* integer= new int;
int* integer= new int[nSize]              //4,1 reverse normal order, do at same time (no constructor is needed, still define 0)
Student ivan ;                                       //call constructor to create an object/instance ivan of type Student
Student ivans[] ;                                                   //no parameter can create array of objects
ivan= number;                                                      //assignment conversion occurs - call below to create object temp
Student temp ( number ) ;                                   //single argument constructor – assignment to copy temp to chris

# Static Memory

Student chris; Student chris[5]; //2,3
Student* ivan= NULL; //5
ivan=&chris; (new) //5
For both Static Memory and dynamic:

//Why we need different approach if they are both 2/3+5? Dynamic allocation can make a pointer point to //variable size array – array[0] (array) – array[size]

//once u allocate dynamic memory u have to free it inside, within the scope and b4 change value or new to avoid
//memory leak – eat up memory (if outside scope cannot access ptr anymore, change add cannot access)
//e.g. destructor – prevent pointer goes out of score e.g. assignment operator  - prevents change address
Before out of scope, change pointer value, change pointer value (new)
delete []ivan; delete ivan;         // delete the memory itself only
student= 0;                                 // pointer still store the address so that set to 0 NULL (!=undefined)
Change value now:
new ;                                           //create the memory itself; set the pointer to store address
Pointer (general for variable with type type*) declared (1 address) and must be defined one value and corr value
Array (general for variable with type type[]) declared (1 address + elements address) same
Int* ()
int (*ivan) () –
ivan correspond address, store address (&num, NULL, new, function_name with same return type and parameter which is a constant address (value) ), which determined by * ;
repeat-address stores int () type data, which determined by int* ()’s int (), variable=*address (ivan)
int () type data = program instructions for a function that receives a double and returns an int (value) p.s.2 to call function: ivan(value)==foo(value) or (*ivan)(value) //goes into instruction
Int* [] ()
int (*c[3])(int, int) = {add, mul, prnch}; // array store 3 functions –
c correpond address, store constant address of 1st element c[0], which determined by type [];
repeat-address stores address (&num, function_name with same return type and parameter which is a constant address (value) ), which determined by type int* (int, int)’s *; variable=*c=c[0]
repeat-address stores int () type data, which determined by int* ()’s int (), variable=**c=*(c[0])
Int&
int& ref – ref correspond address, store int variable ( num (value), another ref (variable) with variable value ), which determined by type int&
1.        e.g. int& ref= num; int a=5; cout << a –5; now output a variable; 5’s type is int and variable’s type is int&
2.        since it is a variable, usually variable(evaluate to variable) = something instead of variable = num(evaluate to value) ; if variable=num (evaluate to variable, then value)
1.        ref = something.value.value so that become not messy
2.        Example:
a.        Int& foo (int& x);
b.        Int& z= foo (y); //int& x(alias)=y; int x=y wont change y value
c.        return x; // int& z= x (return value: evaluate to argument y); i.e. return actual y, not destoryed as y is outside like z ; but if return local variable (e.g. int x in parameter instead) in function, then out scope
3.        Int z= foo(y) ; //advantage to return a reference: declare z only cost 4 bytes as reference
Enum Color
Color eColor = COLOR_WHITE;
eColor correspond address, store defined values ( COLOR_WHITE (value) / aColor(variables/exp with defined values) ), which determined by Color ;
p.s. before declare and define variable (allocate memory), need to define the type by enum Color { defined value0; 1;….or BLUE=-5 } (no allocate memory)
p.s. class easy version as the defined value are actually integer from 0 to… (integer != defined value) but with easier names (good description for array index) and the variable is actually an integer variable

Const and built-in type and class

`#define YEN_PER_DOLLAR 122                       //global scope- common problem is naming conflict`
`int` `nYen = nDollars * YEN_PER_DOLLAR;`
YEN_PER_DOLLAR=123;                                   //compiler error! Not a L-value, invalid assignment
`const` `int` `nYenPerDollar = 122;                          //can be applied to local scope only, outside block can name same`
`int` `nYen = nDollars * YEN_PER_DOLLAR;`
`nYenPerDollar = 123;                                          // compiler error! Valid assignment but just prevent to do it`
 `Const Something cSomething; //initialize by constructor already``cSomething.m_nValue = 5; // violates const, change field value ``cSomething.ResetValue(); // violates const ``cSomething.SetValue(5); // violates const `

à same purpose, little difference for compiler error if change value, big difference for scope

Const and Pointer

 `int` `*const` `pnPtr = &nValue;                              //value must be 123 (&nvalue)``*pnPtr = 6;                                                             // allowed, since pnPtr points to a non-const int` `NEW (even same as const int nYenPerDollar)``const` `int` `*pnPtr = &nValue;``nValue = 6;                                            // ok! nValue is non-const``*pnPtr = 6;                                             // not allowed! Before is constant address, now is address’s constant value``pnPtr = &nValue2;                               // okay` `const` `int` `nValue; ``const` `int` `*const` `pnPtr = &nValue;    //cannot change the address and data stored in the address`

Const method – for get methods – force no field value can be changed

 `int` `GetValue() const` `{ return` `m_nValue; }` it will not change any class variables (so that should not be used on constructor as constructor should change class variables) or call any non-const member functions.`void` `ResetValue() const` `{ m_nValue = 0; }  //fail!``Void GetValue() const { ResetValue() }       //fail! Change field value by ResetValue()` const class objects can only call const member functions     //theirfield value cannot be changed, non-const changclass objects can call non-const or const member functions //their field value can be changed

Const and Reference

 num=5;const int& ref = num; (can also treat as argument into parameter and below is inside the function)ref=6ànum=6 illegal! Const won’t let u change reference’s value (variable)’s value (maybe integer) and good to use in function and object

#define extend details:

(include directives explained in preprocessor process – copy and expand in preprocess)

Macro directives – expand in preprocessor process

`#define SYMBOLIC_NAME    Replacement text\                 //spaces between NAME and Re very important`
`continuous Replacement text                   (until \n)                //PI à PI à 3.14 à PI`
`#define SYMBOLIC_NAME (vars) Replacement text          //Area(2,5) à Area(r,b) à PI * r * b à Area(2,5)`
`//function: evaluate       `
`//define: simple text sub except string, comment, #in <filestring> but #in PI <filestring> without consider type`
`#undef SYMBOLIC_NAME                                                     //for redefine p.s. same text e.g. 2 header files, no nee`
`NAME= _FILE_, _TIME, _DATE_                                            //pre-define and cannot undef`
`                                                                                                      //_FILE_ à _FILE à current file string à _FILE`
` `

Conditional directives –  logical directive - expand in preprocessor process for choosing #include #define

#define CASE_A   0                                              //0 represent NAME in #if and purpose is for operator ==

#define CASE_B   1

#define CASE_C   2

#define CASE CASE_C                                       //CASE à 2

#if   CASE == CASE_A                                        //if 2 == 0

#include "case_a.h"

#elif CASE == CASE_B

#include "case_b.h"

#elif CASE == CASE_C

#include "case_c.h"

#else (without condition)

#endif

//we need to know which case_?.h has to be inserted before compile stage. (same for #define – has to be before)

//if ( 2==1) { #include…} let us choose which case but will be included in compile stage

//#if (2==1) {#include "case_c.h"} let us choose which case and is the only statement before compile stage!

Conditional directives – Definition directi - expand in preprocessor process for preventing duplicate header file, moreover, can #define DEBUG, #ifdef DEBUG {debug statements}, to debug

if dun want to debug, comment out #define, DEBUG is not defined and debug statements is not carry out

#ifndef _SHAPE_H_

#define _SHAPE_H_

// A Shape

// Shape.h

class Shape {

public:

virtual double volume() const;

};

#endif

//separate the code + #ifndef to form every header file and then on other files…

#include Shape.h

#include Picture.h è

[ #ifndef _SHAPE_H_                                          //#if !(defined(_SHAPE_H))…#endif

#define _SHAPE_H_

// A Shape

// Shape.h

class Shape {

public:

virtual double volume() const;

};

#endif ]

//1st define so that ok and then another picture.h which include shape.h (#include picture.h à #include Shape.h

[ #ifndef _SHAPE_H_

#define _SHAPE_H_

// A Shape

// Shape.h

class Shape {

public:

virtual double volume() const;

};

#endif ]

//2nd define fail. As a result, only 1st #include Shape.h is processed

//#pragma once

#include student.h in a file=

if another file use student.h, redefine

if another file use grade.h, also redefine

à so that no more redifinition if already defined, so that defined if not yet defined

Function Basic:

 parameter=argument evaluated value, use parameter; returntype=evaluated returnvalue, use returntype returntype is the only change outside function. If use reference or address as parameters (more than one), then parameters are changes outside function (if do not want to change the parameters, see const reference) return reference purpose: in main: function()=5;return address purpose: in main: int* array= function(); inline keyword add to function à change all function call to function definition when compile à faster exe as no need to call function (save current exe address, etc) à code larger à compare total time spent for different case (call and execute; just execute) and consider

Special Parameter - … eclipse (think as pointer)

 #include                                                        // needed to use ellipsesdouble FindAverage(etc, int nCount, ...)                    //nCount is the pass parameter to notify how many elememtsva_list list;                                                                     //declare a list to store elementsva_start(list, nCount);                                                 //put in the declared list and num of elements to definefor (int nArg=0; nArg < nCount; nArg++){              //access the elements from list and gives it type, moves to nextlSum += va_arg(list, int); }va_end(list);                                                                  //clean up the list cout << FindAverage(6, 1.0, 2, 3, 4, 5, 6) << endl;    //int 1.0 à NO CASTING! Gabage value in gabage out!

3,[{(2+1)+1}+1]

Argument extend details: -

 Default parameters – declare in .h file`void` `PrintValues (int` `nValue1, int` `nValue2=20, int` `nValue3=30 )                                //set default parameters in PROtype``PrintValues ( 1, 2, 3 ) ;                                                                                         //`Values: 1 2 3`PrintValues ( 1, 2 ) ;                                                                                             //`Values: 1 2 30`PrintValues ( 1 ) ;                                                                                                                 //`Values: 1 20 30`PrintValues ( ) ;`                                                                                                    //Values: 10 20 30PrintValues (  ,  , 3 ) ;                                                                                           //not support so that `void` `PrintValues (int` `nValue1=10, int` `nValue2=20, int` `nValue3 )                                //not support` Function overloading (same name different definition) by parameters – different declaration`int` `Add(int` `nX, int` `nY); { …a… }                                                                       //integer version ``double` `Add(double` `dX, double` `dY); { …b… }                                                    //differ type of parameters``int` `Add(int` `nX, int` `nY, int` `nZ)                                                                            //differ no of parameters`double `Add(int` `nX, int` `nY); { …a… }                                                                //can’t be differ by return type``//function call ( argument ) decide which function is called by matching exactly parameters``//if no matching exact parameter, promotion e.g. int nX= char para``//if no promotion, then use standard conversion ``à`` 1 match, no match or >1 match because int convert to unsigned int is equal to convert to double, >1 result can be produced ``//if result >1 / 0 matching functions,  compile error, use type casting (double) para``//>1 argument, then find the best function which means at least one better (search faster) argument, others equal` Default parameters and function overloading`void` `Print ( char` `*strString ) ; { …a…}                                                             // 1 parameter``void` `Print ( char` `ch = ' ' ) ; { …b…}                                                                    // 0 parameter``Print ( a ) ; Print ( ) ;                                                                                            // function call``void` `PrintValues ( int` `nValue ) ;                                                                        // 1 parameter``void` `PrintValues ( int` `nValue1, int` `nValue2=20 ) ;                                         // 1 parameter``PrintValues ( 10 )                                                                                                 // compiler confused` `Function overloading by Const – different declaration``const` `int& GetValue() const` `{ return` `m_nValue; }         //1st const is used to make m_nValue cannot be changed``int& GetValue() { return` `m_nValue; }                             //differ by GetValue() const and thus overloaded``Something cSomething; ``cSomething.GetValue();                                                     // calls non-const GetValue(); ``const` `Something cSomething2; ``cSomething2.GetValue();                                                   // calls const GetValue();`

`Function (same name same para = same declare, different definition) + Variable `

`Declaration: Same name cannot be declared in same block but different block `
`Separated by Namespace –`
`Like class1 class2 `
 `inherited method1() in class2 (which also has same method1 declare (+ return type same) different definition) – in different block`
`Access global function: function() – which one? Namespace :: function() or using… – ok – Namespace details`
`Access class  method: object1.method() and object2.method() – ok`
`inherited makes object2 can use 2 method1() i.e. it is like 2 method1() same declare in class2! `
`inherited: object2.method1()- use its own version; if not existed, use inherited (UPPER) version;`
`If both existed, and do not want to use its own version, object2.(class1::method1() )  (UPPER) `
`shadowing – (`but not a good programming style as baseclass name is exposed, so it’s better to call the baseclass method (shadowed method) inside the newly created method of derived class

`Works for multiple inheritation to choose which inherited (UPPER) version should be used`
`To use (LOWER) version: (continue with type casting by pointer and reference) – Virtual Function`
`Set virtual return method1 () in class2``à`` object2.method1() ignore this method``à`` Look (LOWEST until pointe) class3 method1() p.s. it knows there is class3 because pointer and reference assignments`
`Delete object1; //object1= &object3 ;`
`Reason: should call destructor of derived class (class3) as later destructor will call base destructor`
`Result: use virtual function (destructor) `
`Reason: no need to define in class2 but class3 as never used`
`Result: use (pure/abstract) virtual function - Set virtual return method1 () in class2 = 0 ; Define in all classes with method1()`
`Side-effect: Class2 becomes abstract base class and cannot create object – object2.method1() compile error Object3.method1() compile error will remind us class3 must define method1()`
 `Interface class – no fields, all methods are pure virtual functions!`

Definition has the name only; virtual default parameters in declaration

`Reason: function and method `
class student{
declaration of method1,2}
declaration of function (name as method1)
in .cpp file
method2{//student method2 so that student called and inside u dun need object.method1 but method1
//at the same time, call the function is also just function (imagine same name as method1
//as a result, we use method1() to say it is method1 and (namespace)::method1() to say it is global
`Adds Local variable vs Global variable vs Field `
`Local can be accessed inside the block (function) it declared only, so field1 in method must be object.field1`
`Reason: access – refer to Inner hider outer declaration and definition but I want to refer outer one`
`So: ::variable to clarify we need to use outer`

2-1-1
Template – a function/ class for All type parameter – sub in the type and compile

template <typename Type, typename Type2> // this is the template parameter declaration – function template
template <typename T, int nSize> //this is the template class - nSize is the expression parameter
Type max(Type tX, Type tY) // {
return (tX > tY) ? tX : tY; //take care the variables with the Type for additional adjustments (e.g. overload) }

Function call : max ( 5, 6 ) to sub argument’s int to create the template and then value to execute
Class call : Array<int, 5> to sub int and value into the template to create the template, Array<T> to sub T, then continue to execute
 class name will become class when call :`template` `  - function template``int` `Array::GetLength() { return` `m_nLength; } ``// instead of int Array :: GetLength() coz Array class is also a template and in function we access/call Array    `

Template specialization – suppose same function implementation for every type
void Print() { std::cout << m_tValue << std::endl;; } //inside template class
void Storage<double>::Print() { std::cout << std::scientific << m_tValue << std::endl; } //no subbing
//add above code outside of class - create a specialized version of the Print() function for doubles

nValue.Print(); à template class version function implementation //normal subbing like 1
dValue.Print(); à specialized version function implementation `// no subbing is needed`
Class Template specialization – suppose same class implementation for every type
`template` `<typename` `T> class` `Storage8 { … } `
`template` `<> //the following is a template class with no templated parameters `
`class` `Storage8<bool> { … } `
`//add above code outside of class – create a specialized class version for bool`

`Storage8<int> cIntStorage; ``à`` template class version class implementation //normal subbing like 1`
`Storage8<bool> cBoolStorage; ``à`` specialized version class implementation ``// no subbing is needed`

4-4

<iostream> extend details p.s. <iostream> is a header file even no .h coz of traditional writing, it includes istream and ostream because of inheritance

input object (keyboardà Stream (sequence of chars in buffer) >> datamemory >> Stream àoutput object(display, print)
Function << >> with operands cout and cin (standard object, see below)
 ivan + chris ; call operator to do a task - .method name () replaced by OperatorSymbol r.o cout << “hello” class x object cout .method name () replaced by method << “hello” – task is to print val to scr cout << << endl Cascading – go to cout width fflush(stdin); Cin >> input, data stores in cin, >> for next cin; Cout << output, data stores in cout, << for next cout; to clear up the buffer: (flushing)Close program and destructor is called and flushing is called (how about crash!?)Manually flush() after cout << to ensure it is cleared cin >> input … >> input – variable input declared, wait cin to be defined instead of using assignment1.        if cin is empty-wait input, store input in cin after user pressed enter(\n)2.        store input corresponding to type, remaining remain in cin until next cin- repeat p.s. int input for number, char input[255] for string (see string constant of char[]), char input for a char (if abcde enter, then store only a, and remaining remain for next cin) p.s. NO CASTING! [ See Variable extend details. Int=00110001=49; char a=00110001=’1’/0x31/49; promotion so that (int)a—return 49 ] If no casting, integer must be 0-9 and no letters (chars can be 0-9 and letters) Cin >> setw(10) >>input (string version) Set store input from cin only 9 chars (1 for \0) or up to \n, remaining (include \n) remain in cin until next cin – repeat Cin and whitespace (space, newline >> skip, discard space! >> char: I am ivan à iamivan //take a char, discard space>> char*: ivan am i à Ivan\0space\0? No! ivan\0am\0i\0 //take a string (determine by whitespace), discard space, add \0int: 96 à 96space //take a number (determine by whitespace), discard space, add space scanf("%d%c", &num, &a); 123sss enter, 123 store in num, s store in a, ss no storeusing scanf instead of cin can store data into number of variables

 Examples of standard output input object of o/istream (buffer) type: Examples of r.o: cout (standard output device) Value, Variable/exp cerr (standard error output device with unbuffered chars) end1 which is a newline character \n makes the cursor on the newline clog (same but buffered) cin (standard input device)

Above is function operator with operands cout cin, here is cout/cin method
 cout.width(10) ; ch13.3 sets width of Next output field cout.fill(‘*’) ; defines the padding character which is the char inserted into Stream if text occupies less than width, space is default cout.precision(2) ; generalàdigits, scientific and fixedàdigits after decimal pt – go to cin >> input cin.get(input) ; = cin >> input, but keep the space ( >> skips!) `cin.get(strBuf, 11);` `char` `strBuf[11]; cin.get(strBuf, 11); cin.get(strBuf,10)``//string version, same as setw() above` `cin.getline(strBuf, 11);` //above try to read 10 more chars, but it stop immediately because the 1st char is \ngetline is same as get string version but reads \n, not up top.s. cin.gcount() to count number of chars for last getlinep.s. `getline(cin, strBuf); from class` cin.ignore() or cin.ignore(2000,’\n’) ; Discard first 1/2000 chars in cin or until \n is pressed peek()unget()putback(char ch) allows you to read a character from the stream without removing it from the stream. returns the last character read back into the stream so it can be read again by the next call. allows you to put a character of your choice back into the stream to be read by the next call.

 State of stream after above op Ios::goodbit/badbit/eofbit/failbit is set //ios is the base so that inheritance to iostrea Cin.good() //also ios method but inheritance Returns true if the goodbit is set (the stream is ok)- goodbit must be true to continue perform operations Bad() Returns true if the badbit is set (a fatal error occurred – read past eof) Eof() Returns true if the eofbit is set (the stream is at the end of a file) Fail() Returns true if the failbit is set (a non-fatal error occurred– enter letters when expecting integer – NO CASTING! [ See Variable extend details. Int=00110001=49; char a=00110001=’1’/0x31/49; promotion so that (int)a—return 49 ] If no casting, integer must be 0-9 and no letters (chars can be 0-9 and letters) Clear() Clears all flags and restores the stream to the goodbit state Clear(state) Clears all flags and sets the state flag passed in Rdstate() Returns the currently set flags Setstate(state) Sets the state flag passed in

basic file I/O classes in C++:

<ifstream> (derived from istream), <ofstream> (derived from ostream), and <fstream> (derived from iostream)

<fstream> is a header file even no .h coz of traditional writing, it includes ifstream and ofstream boz inheritance

`Cout cin: `
`#include <fstream> ``à`` <iostream>`
`ofstream outf("Sample.dat"); ``à`` cout i.e. write to file`
`ifstream inf("Sample.dat"); ``à`` cin i.e. read from file`
`//Oops, we forgot something, cannot redeclare so that… `
`outf.open("Sample.dat", ios::app); `
`//When outf goes out of scope, ofstream destructor will close the file `
`// If we couldn't open the output file stream for writing/reading`
`if` `(!outf) ; / if(!inf)`
`<< >>`
`outf << "This is line 1"` `<< endl; //write to file`
`inf >> strInput; //read from file, return 0 if reach EOF`
`Methods: Getline same as above… `
`To open file in a specific location:`
`ofstream outf("Sample.dat", ios::app); //constructor with another para`
`App`
###### Opens the file in append mode
`Ate`
Seeks to the end of the file before reading/writing
`Binary`
Opens the file in binary mode (instead of text mode)
`In`
Opens the file in read mode (default for ifstream)
`Out`
Opens the file in write mode (default for ofstream)
`Nocreate`
Opens the file only if it already exists
`Noreplace`
Opens the file only if it does not already exist
`trunc`
Erases the file if it already exists
`  To open file in a specific location instead of beginning, end; + plus to read/write ~ignore()`
 `inf.seekg(-18, ios::cur); // move backwards 18 bytes  //cur/beg/end //+ towards end, - towards beginning` `outf.seekp(-18, ios::cur); // for writing` `inf.seekg(0, ios::end); // move to end of file ``cout << inf.tellg();` //returns absolute position `Inf.remove() //delete a file`

`Fstream: (derive of base i/fstream)`
`Above we use #include <fstream> for objects ifstream and ofstream, we can use fstream objs to represent in/out`
`Fstream obj; //to change between read and write, we perform seekg, write, seekg, read…`

1-4-1

Inheritance and Constructor extend details:

Only looks up!

Inheritance=

class deriveclass : accessModifier BaseClass, accessModifier BaseClass2 {
} // accessModifier= determine derived class member access
Then the derived class (specific, apple) already has baseclass (general, fruit, is relationship) fields (different derived member access specifiers determined by accessModifier see p.s and also different access to base members determined by base members private, public protected) and methods and can add their own like how base class add the fields and methods, except constructor destructor copy constructor and assignment operator is not inherited! (to save time, reuse) //always only look up one level and then one level…until found the field/function
p.s.
 Below accessModifierRight is base class member access (Private) Protected Public Public Private Protected Public Private Private Private Private (Private) Private Protected Proteced
Change inherited member from protected to public –  (not private to public because cannot access)
add Base :: member (no () ) into Derived Class’s Public
Change inherited member from public to private/protected–
add Base :: member (no () ) into Derived Class’s Private

Constructor definition and access

 Student ivan ( Field : Person x ): Declare all (allocate memory) e.g. int x, Person’s int y, int z Choose constructor Student() and Define after : e.g. default- x(), not Person x(); or x(3,4) – initial list for ObjChoose constructor Person() and Define after : e.g. y(1), z(2) – initial list for VarInitialize values and define values in bodyBack to student constructor and Define after : x(), Initialize values and define values in body *default constructor (); if no constructor is provided, compiler provided (); if there is constructor provided, compiler wont provide (); if there is no constructor - default (), if called (), compiler gives error Derived object (x); Derived object (x,y);            //constructor call, process below:Create [ object/instance (i.e. fields) ] – [ variable ], corresponding address – data part belowCall particular Derive Constructor: Base( c ) or defaultCall particular Base Constructor: gabage value and logic body define OR define and logic body Back: , a(b) gabage value and logic body define OR define and logic body //according to process’s definition syntax`class` `Derived: public` `Base { ``public: ``double` `a; ``Derived(double` `b=0) : a(b) { ` `} //without give input to base class, call default immediate base constructor``Derived(double` `b=0, int` `c=0) : Base(c), a(b) { } //give input to base class as well, only immediate base class` Destructor=call destructor of derived class for last object and then based classcall destructor of derived class for 2nd last object and then based classCalled b4 scope ends according where constructor called to delete objects; so additionally deallocate all dynamically allocated memory of object fields to prevent memory leak when pointer goes out of scope(deallocate dynamically allocated memory != delete address (set to NULL) Copy Constructor= (constructor concept)Student::Student(const Student& source) : Person(source) {……}Person::Person (const Student& source2) {…} or just shallow copy (default) Assignment Operator=Student& operator=(const Student& src);Student& Student::operator=(const Student& src) {     if (this != &src) {         // base class assignment operation – two/3 methods          // 1 - symbolic form - cast to base class ( see type casting )         (Person&)(*this) = src;  //type cast this as Person& from Student so that *this REFERENC object (var) srcà(base&, derived using reference which is below)Person& x= src;  (base&, derived student);  Person& y= *this; (base&, derived student);Y=x; done! //y will use Person’s assignment operator=, not Student         //or 2 - functional form - unavailable on Borland         *this Person::operator=(src); //can use base method//3- derived class shallow assignment         no = src.no;         // derived class deep assignment         if (grade != NULL) delete [] grade; if (src.grade != NULL) { grade = new char[strlen(src.grade) + 1];             strcpy(grade, src.grade); } else grade = NULL; }     return *this; } Default:1.        Constructor- empty argument constructor2.        Destructor- empty argument constructor3.        Copy Constructor- shallow copy4.        Assignment Operator- shallow copy

Multiple Inheritance and Virtual, Constructor definition and access

 Copier copy ;   //constructor call, process below:Create [ object/instance (i.e. fields) ] – [ variable ], corresponding address – data part belowCall particular Derive Constructor: Base( c ) or defaultCall particular Base Constructor: gabage value and logic body define OR define and logic body Back: , a(b) gabage value and logic body define OR define and logic bodyà call copier constructor; call scanner constructor, powered device constructor; call printer constructor, powered device constructor Copier copy ;   //constructor call, process below:à call copier constructor; call poweredDevice constructor; call Scanner constructor without call powered device constructor; call printer constructor without call powered device constructorp.s. if create scanner object, poweredDevice will be calledp.s. copier is responsible to create poweredDevice, not the class below copier //according to process’s definition syntax`class` `Copier: public` `Scanner, public` `Printer ``{ ``public: ``Copier(int` `nScanner, int` `nPrinter, int` `nPower) ``: Scanner(nScanner, nPower), a(b), Printer(nPrinter, nPower), a(b) ` //according to process’s definition syntaxclass Copier: public Scanner, public Printer { public: Copier(int nScanner, int nPrinter, int nPower) : Scanner(nScanner, nPower), Printer(nPrinter, nPower), PoweredDevice(nPower)class Printer: virtual public PoweredDeviceclass Scanner: virtual public PoweredDevicep.s. All same as left except add bold

Command Line argument extend details:

 C:\\>WordCountC:\\>WordCount Myfile.txt Myotherfile.txtMicrosoft Visual Studio 2005 solution explorerà propertiesàConfiguration PropertiesàDebuggingàCommand Arguments”. `int` `main(int` `argc, char` `*argv[]) ``//argument count >=1 (program name must exist) ``//`array of C-style strings` argv[0]= program name and argv[1]=user input`