Friday 13 April 2012

Exam Reference Book (my notes)



OOP244

Complexity= Problems are detailed and the most important features are activities and objects

By identifying the objects and activities, we can have:

Object-oriented programming= Solution which offer its systematic approach to complex problems

SYS366 System analysis and design= To identify the objects and activities (features of problems) after learning C++ - variables, functions, classes (object) include fields (properties) with methods (action)













Language Differences=

Major Language in world= http://www.levenez.com/lang/

Popular by software engineers= http://www.tiobe.com/tpci.htm 

Java

C
C++

Object-oriented= exclude all non object-oriented features; break problem into objects only * all about object and class

Procedural= exclude any object-oriented features; break problem into activities only
e.g. main function
Hyprid= include object-oriented features and non object-oriented features; break problem domain into objects and activities
Import class;
copy class into the file by pre-processor;

class{
field;
method{…}
}end class

class{
field;
method{…}
}end class

use local data scope (including class, variables) and instance data scope

#Include <file.h>/“file.h”
<>== standard library path-system
“”==same directory as source file
even the file is .h, compiler links the same name.c along the path for the definition;
copy file into the file;

struct{field};
function{…}

struct{field};
function{…}

use local data scope (including struct, methods) and instance data scope (only public)
#Include file (imagine .h link withc)
Copy file into the file;

struct{
field
method{…} //implementation outside, not the below, which is can be main()
}; end struct
function{…}

struct{
field
method{…}
}; end struct
function{…}

use local data scope (including struct and methods) and instance data scope
Inheritance
X Inheritance

Objectname.method()
X Objectname.method()
Use method(variablename)
printf("Welcome to Object-Oriented\n");
cout << "Welcome to Object-Oriented" << endl;


























Create Module – why declare define? Why declaration has to put in header files? Where declare define?

1.        Write all necessary code, which contains #include other header file if that file has to be used, is the module

Function – function declaration + function definition –
Situation: A function has to be defined before B function if B definition calls A ; B function has to be defined before A function if A definition calls B
using function declaration (forward declaration) so that compiler will not complain if B definition calls A or A definition calls B
Class definition – class definition-method definition + method definition –
easy to manage if the class is long and complicated, especially who care how it works

2.        Separate #define (keep #include in cpp file), (struct definition-method definition) and function declarator (prototype) and variable declaration as header file and the definition as implementation cpp/c file à

function declaration (prototype) – have to declare 10 functions before the 10 functions are used; 10 x 2 functions if another file also use those 10 functions
group 10 function prototype into the header file – have to declare only 1 time before the 10 functions are used; 1 x 2 times if another file also use those 10 functions; moreover, change 1 time in header file instead of changing 1 function x 5 files
class definition-method definition – have to declare 10 class definitions before the 10 classes are used; 10 x 2 classes if another file also use those 10 classes
group 10 class definition into the 10 header files – have to declare 10 header file sentenses before 10 classes are used; 10 x 2 header file sentences if another file also use those 10 classes

3.        #Include back its own header file in cpp file à always need to group together for performing

4.         

5.       

6.        procedure: bcc32 main.cpp order.cpp

Start preprocessor to copy the code (function prototype; or struct class{…}-method definition; or #define) from file in (<>== standard library path-system “”==current directory) to replace #include <file>/”file” and form the pre-processed source file
(bcc32=copy ALL code from #include to main.cpp & order.cpp)
Start compiler- if meet Forward declaration (which is in the form of function/method prototypes; or + struct class; - all without definition) will tell the compiler - the function/class is declared but defined later (main.cpp) or later in other files (order.cpp) to be linked - so that compiled ok to binary file
(bcc32=compile/check declarators main.cpp & order.cpp)
Compile error – if function/class is not declared before accessed in each file; (if function is forward declared and no definition, still compile ok)
Start linker- link the definition to main to form exe file p.s. iostream auto link if it is declared #include <iostream>
(bcc32=link/check definition main.cpp + order.cpp)
Runtime error on linker stage (depend on situation) – if function/class is accessed but no definition (unlike declaration, can put anywhere in a file or in another file to be linked), compile ok but linker will be error; if function is not call and no definition, compile ok and run fine
Bcc32 main.cpp compile ok without linker error becoz order.h include all the definition can be found, not only the function prototypes

All components are in exe file now and can run exe file to perform results (start from start, variables, functions, class above main are being referred- see below)

7.        For the header file, if other file has to be used, then use forward declaration instead (see below table) of include that header file to avoid conflict; Duplicate methods are ok

Grade.h

Student.h include grade.h (consist of Grade class definition- method definition)

//something declared in student.h need class grade, e.g. student method (Grade a, b)
Student.cpp include student.h
Main.h
Main.cpp include main.h, student.h and grade.hàConflict as multiple class definition- method definition + method definition
Main.cpp include main.h, student.h Or
Grade.h
Student.h (with a forward declaration struct Grade; instead of include grade.h = Grade class definition- method definition in .h file) – NOT WORK!
Student.cpp include student.h and grade.h
Main.h – OMIT GRADE.H AS STUDENT.H ALREADY INCLUDE
Main.cpp include main.h, student.h and grade.h à no Conflict as only one definition













(above set 3 rules for function, class, and now add variable rules)

(First check what happen inside class structure – field, method, constructor)

Basic Class Structure (declare, define, access, scope [ where can be accessed, requirement, after access])

class Student {                                      //class declaration

                                                                //class definition = field (variable like) method (function like) declaration

                                                                //thus can be access/call without compile error even without definition

(private:)/protected – member/instance data - only member of class Student (and derived class anywhere for protected) can access/call, after declaration. Destroyed if out of block and can be re-declared

[ declare – access – access to where ]

int no ;                                                   //field declaration – can’t be Student ivan

////static int no ;                                                                     ////ignore re-declare so that all objects share this field

public: - outside member of class Student can also access/call, after declaration. Destroyed if out of block and can be re-declared

void display () ;                                      //method declaration

Student () ;                                            //constructor declaration

~ Student () ;                                         //destructor declaration

};                                                             //separate .h and .cpp



Student :: Student() {…}                    //constructor definition – empty insert by compiler if no declaration - inher             

Student :: ~ Student() {…}                 //destructor definition – &default doesn’t initialize, not NULL/new/0

void Student :: display() {…}              //method definition

//field definition is in constructor definition i.e. gab val and then define OR

Student :: Student() : field(var/val/exp)            //declare and define at same time – initialization list – for const

                                                                                //field(var/val/exp) instead of gabage value and then { body }

////int Something::s_nValue = 1;                                        ////definition do not need to be in constructor definition



//another file main.cpp to show how to access field, constructor, method

int main() {                                            //function declaration

                                                                //function definition starts

Student ivan ; extend details below   //call constructor Create [ object/instance (i.e. fields) ] – [ variable ],

//corresponding address – see inheritance for details

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

Student venven ( number, name );                     //argument constructor can only set up one object          


//if struct Student; then struct Student ivan or struct //Student ivan= { number, …name }

////Something::s_nValue                      ////call static field ( obj.s_nvalue can also be used )

////Something::get_value ( )                 ////call static method to access static field even field is private and not ////member of class (e.g. main) want to access  p.s. or use public method call ////but need to create object to call the public method. Now is more easy       

ivan.number = 5 ;                                 //call field to assign a value

number= 6 ;                                                           //object can be omit if this statement is inside object method //implementation à object.method() called and object is assumed

                                                                                //object= *this= *OBJaddress ; *this.no= *address.no= obj.no; //even OBJaddress is same as MEMaddress, this - OBJaddress

                                                                                                //(*address).member==addressàmember

                                                                                                //&instance.member=&(instance.member)     

ivan.display() ;                                      //call method to do a task

display() ;                                                               //object can be omit if this statement is inside object method

//implementation à object.method() called and object is assumed

//object= *this= *OBJaddress ; *this.no= *address.no= obj.no; //even OBJaddress is same as MEMaddress, this – OBJaddress

}

//finish show class field method constructor’s declare, define, access, scope, now show file variable function class’s declare, define, access, scope



Global variables (outside any block) - program scope – can be access throughout the file (another file if #include or forward declaration in another file) after declaration. Destroyed if out of program  //difficult control, avoid

#include others.h                                  //keep in .cpp

#define   extend details below             //keep in this.h, copy code by pre-processor and expand this macro-directiv

extern Int a ;                                         //variable declaration (real declare somewhere else)

                                                                                //put in the header file (won’t affect below)so that another file use

class Student…                                     //(class definition-method definition) + method definition (see above)

int set() ;                                                                //function declaration (main) above  (arg= variable/value/expr

//extend details below)

//separate .h and .cpp



int a;                                                       //real variable declaration in .cpp file, not in other file who use it

a = 5 ; extend details below                 //variable definition

////static int a ;       ////decrease to file scope

////a = 5 ;                 ////static variable definition

class Student…                                     //class definition-method definition + (method definition) (see above)

int set(){                                                 //function definition – this time we show variable instead of class members

Local variables (inside block) – block/local scope – can be access within the block which they declare, after declaration. Destroyed if out of block

int b;                                                       //variable declaration, not for class and not function, not written down

////static int b = 0 ; ////same access. Not destroyed if out of block and ignore this statement ( e.g. call set() 2nd )

                                ////but it is still a local variable and in other blocks int b still can be declared (better avoid)

cout << ::a;                                            //call global variable if above not int b but int a (same name) to distinguish

}



//another file main.cpp to show how to access variable function class

int main() { extend details below       //function declaration

                                                                //function definition starts

cout << a ;                                              //call variable – refer to the most suitable declaration and definition

                                                                //call class’s field, method, constructors like above but not call the class

::set() ;/ set() ;                                       //call function – refer to the most suitable declaration and definition

return 0 ;

//Comment proper use:

//At the library, program, or function level, describe what

//Inside the library, program, or function, describe how

//At the statement level, describe why.

//Formatting:

//Whitespace (space, tab, newline are ignore except quote)

//Statement:

//1statement; = 1{…;…;} e.g. if () statement ; = if() {…}

                                                               







struct
Student
harry
address
2ff2b8c4 (occupy to the end with type student)
member
int
no
char
grade[]
address
2ff2b8c4
2ff2b8c8 (same to the end with char
bytes






















struct
Student
member
int
no
char
grade[]
bytes























UML Unified Modelling language’s class diagram
Student
 - no : int //- means private
 - grade[14] : char
 + set ( int, const char* ) : void 
 + display ( ) const : void  





Implicit and Explicit Parameters Definition for above:

Member functions on current object have 2 types of parameters


1.        Implicit parameters=

a.        Fields inside method, which allocated memory when construct current object and deallocated when destruct.

b.        Declare in Field declaration as private/public

2.        Explicit parameters=

a.        Method parameters, which allocated memory when method is called and deallocated when method call ends

b.        Declare in Method declaration











Operator are implemented as built in functions

e.g. 5+6 is +(int, int); a=b is =(double, double); cout << “hello” is << (cout, char[])

Overloading operator is overloading functions with different parameters! NOT METHODS!

//method declaration //function declaration – extend to special //operator declaration

void Operator++ () ;                             //operator declaration -  method name replaced by OperatorSymbol

void Operator++/-- (int)                                       //header for post-fix, int just for purpose distinguish (information

void Operator+ (type right_operand)                 //binary expression (2 operand 1 opto); unary (1 operand 1 optor)

void Student :: Operator++ () {…}     //operator definition

ivan ++;                                                  //call operator to do a task - .method name () replaced OperatorSymbol r.o



Operators: (information)

1.        Post/pre-fix ++ difference

a.        ++c, c++,c=0:

b.        both are c = c + 1; c=1

c.        (++c) = 1 =new value of c

d.        (c++)= 0= old value of c

e.        both = a variable, 1 just the meaning

2.        Candidates for overloading=

a.        post/pre-fix (++ --)

b.        assignment (= += -= *= /= %=)

c.        unary arithmetic (+ -)

d.        binary arithmetic (+ - * / %)

e.        relational (== > < >= <= !=)

f.         logical (&& || !)

g.        not for (:: . .* ?: sizeof type())



function overloading by differ para

function call: function(a,b)                 implementation: function(a,b)

operator function call: a+b                  implementation: operator+(a,b)         overloads +(build in a, build in b)

method overloading by differ para

method call: a.method(b)                     implementation: method(b)

operator method call: a+b                   implementation: operator+(b) (*this)                overloads operator+(classb b)

operator is always overloaded when u provide 1st operator to overload built in operator
method function is overloaded when u provided 2nd method to overload 1st method










//function declaration //operator declaration –

extend to special // friend helper function declaration // friend helper operator declaration

private: field1                                                        // the field is private (information)

main { object.field1 }                                           // this is wrong as main is not a member of class

Class Student {

Public:

friend void display ();                           //helper function declaration - declare function into class from outside class

}

void display (){                                      //helper function implementation

Object.field1                                                         //this is right now

X field1                                                                  //need to state the object because it is not called by object

}

display () ;                                              //call helper function to do a task - not ivan.display() as it is not a method



extend to special // non-friend helper function declaration //  non friend helper operator declaration

Student function ();                             //non friend helper function declaration

Student function () {                            //non friend helper function implementation

….call other public method to access the field

}

function ();                                            //call non friend helper function to do a task













Memory

1.         Static memory=

a.         Space in RAM.

b.         When user starts/loads application.

c.          OS used it to store program instructions and local variables and objects (when defined). Amount is determined by linker at link time.

d.         When user terminates applications or objects end defined, OS recovers all space.

2.         Dynamic memory=

a.         Space in OS.

b.         When keyword new is used.

c.          Additional memory’s address will be stored in pointer variable, which is stored in static memory. The additional memory’s data will be stored in the dynamic memory.

d.         When program explicitly deallocates the variable/object but not return space to OS

e.          When program terminates, recovers all space

3.         Until now, in all our programs, we have only had as much memory available as we declared for our variables, having the size of all of them to be determined in the source code, before the execution of the program. But, what if we need a variable amount of memory that can only be determined during runtime? For example, in the case that we need some user input to determine the necessary amount of memory space. Also, pls see file Stack Heap Dynamic
The answer is dynamic memory, for which C++ integrates the operators
new and delete.



Dynamic Memory

Student* student=NULL;  (even no =NULL, NULL is default value for a pointer, until new is used)

//declare student as type student *, which takes address with Student type or Student[] type as data (see ipc)

//declare student as type int *, which takes address, which stores integer, as data (&num / variables with a_data)

//declare variable x as type int, which takes integer as data (1/‘c’ (value) / variables/exp with int value)

//int x=5; variable=changing data= ? is determined by type, variable/changing data is stored in address

//variable correspond address, store changing data, which determined by type

//student* ivan – ivan correspond address, store address, which determined by ; repeat-address stores student, which determined by student*’s student, variable=*address



student= new Student ; à student=new; Student (*student);      //initialize address and *address

student= new Student[size] ; à student=new[size]; Student (*student)[size];


student= new Student ( parameter ) ; à student=new; Student (*student) ( parameter );


int* integer= new int;               

//new int return dynamic address and create size for an int) and stored in integer (int *)

int* integer= new int[nSize]      

//new[] int[nSize] return dynamic address of 1st element and create nSize for an int array 

//student which takes address as data- the address, which is dynamic memory (Heap), is allocated by new

//call constructor without object name (*student) to create object (*student) of type Student, which addres stores

//simple data- no constructor is called- *integer=default; but there is no built in default *student

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

Student venven ( number, name );                    //argument constructor can only set up one object




delete []student; à ~Student (*student); student=null;                                       //change *address and address                       

delete student; à ~Student (*student)[size]; student=null;

//student which takes address as data- the address, which is in dynamic memory (Heap), is deallocated by delete

//call destructor without object name (coz *student is obj) to destory an object/instance *student of type Student

//once u allocate dynamic memory u have to free it inside, within the scope and b4 change valu to avoid

//memory leak – pointer goes out of scope / pointer change value (address) without deallocation

//e.g. destructor – prevent pointer goes out of score e.g. assignment operator  - prevents change address

student= Null;                                                   //good programming style, as student actually= Null in delete statement



Static Memory


Student ivan;

Student* student= NULL;

student=&ivan;

Student *student;                      //constructor called



Example: smart integer arrayà make an array(5); set elements; get elements; increase the size à set size, set address and call 5 times constructor (integer) to make *address 0,0,0,0,0; set elements using for loop and address; same for get; or use reference= element variable; make a new array and replace old one;

Please see intarr1.cpp











Shallow copy- only copy address and ignore content!

Object Assignment – Assignment operator, Copy constructor

Test t1, t2;                                             //simple constructor already called

t2 = t1;                                                    //Assignment operator called (created vs created)

Test t3 = t1;                                           //Copy constructor (single argument) called (creating vs exist) - Test t3(t1);



//method declaration //function declaration – extend to special //operator declaration (=)

Assignment Operator

Student& operator= (const Student&);                                            //operator= declaration

Student& Student :: Operator= (const Student& source) {           //operator= implementation

if (this = &source) { return *this }                     //check self-assignmt- objects are already created, can made same

no=source.no;                                                       //shallow copy for non-resource instance variable (field) - deepà

if (grade!=NULL) delete [] grade;                       //grade= NULL à deallocated already and ready for changes

if (source.grade != NULL)                                    //if source.grade value is address, grade also need an address

grade= new char[strlen(source.grade)+1]        

strcpy(grade, g)                                                     //initial values to replace default values

else grade= NULL;                                              

return *this;



//constructor declaration - extend to special // copy constructor (single-argument) declaration

Copy Constructor

Student (const Student&);                                                                  //copy constructor declaration

Student :: Student (const Student& source){                                  //copy constructor implementation

//if (this = &source) { return *this }                   //copy con called, t3 allocated mem (this), exe this log, can’t be=t1

no=source.no;                                                       //shallow copy for non-resource instance variable (field) – deepà

//if (grade!=NULL) delete [] grade;                     //grade= none, not even NULL (default for ptr), as not yet created

if (source.grade != NULL)                                    //if source.grade value is address, grade also need an address

grade= new char[strlen(source.grade)+1]         //without this statement, grade=nothing – not initialized

strcpy(grade, g)                                                     //initial values to replace default values

else grade= NULL;



Default Assignment operator and Copy constructor (provided by compiler, no coding is needed)

1.        Default Assignment operator and Copy constructor provide only shallow copy= data copy to data members

2.        member of student (field) is a resource instance variable, which contains dynamic address (resources)àcopyàboth student share same dynamic address and change to one value also change the otherà

3.        Modify Assignment operator and Copy constructor provide deep copy



Difference between Assignment operator and Copy constructor

1.        assignment operator= copy constructor + self assignment check + deallocate previous memory for existing

2.        Can simplify by putting common code in a private method and call it by both copy constructor and assignment operator











Namespace – other than variable, function, class – to include both .h and .cpp file (continuation)


Foo::function declaration, Foo::function defination

//#include goo.h=below

Global variables (outside any block) - program scope – can be access throughout the file (another file if #include or forward declaration in another file) after declar

Int a;                                                       //variable declaration

class Student;                                       //class declaration and definition above

int set();                                                 //function declaration (main) above

int set(){                                                 //function definition – this time we show variable instead of class members

Local variables (inside block) – block/local scope – can be access within the block which they declare, after decla

int b;                                                       //variable declaration, not for class and not function, not written down

}

//#include foo.h=below

Global variables (outside any block) - program scope – can be access throughout the file (another file if #include or forward declaration in another file) after declar

Int a;                                                       //variable declaration

class Student;                                       //class declaration and definition above

int set();                                                 //function declaration (main) above

int set(){                                                 //function definition – this time we show variable instead of class members

Local variables (inside block) – block/local scope – can be access within the block which they declare, after decla

int b;                                                       //variable declaration, not for class and not function, not written down

}

//calling which set? 2 files with same function name!

//another file main.cpp to show how to access variable function class

int main() {                                            //function declaration

                                                                //function definition starts

a=5 ;                                                       //call variable

                                                                //call class’s field, method, constructors like above but not call the class

set() ;                                                      //call function

//to solve name conflict by using different file name – namespace for .h and .cpp both

namespace foo {…} ;                            //namespace declaration and definition

namespace goo{…} ;                                            //contain the code above

foo :: set() ; goo :: set() ;                      //call namespace for function

goo :: a=5 ;                                             //call namespace for variable

using namespace foo;                           //2nd way to call

//using is like a variable scope – declare with program/local scope

set();                                                       //cannot find set() so that look in namespace foo { set() } disadv: cannot goo

                                                                //example as always see

#include <iostream> extend details below//iostream.h (library) contain namespace std { cout function } - declare

using namspace std ;                            //2nd way to call

cout << “something” ;                         //std :: cout

#include <cstdio>                                 //cstdio.h (library) contain namespace std { printf function } - declare        

using namspace std ;                                           

printf("%d, %c\n", ch, ch) ;                //arg= “string” sub in by ch to %d     



//library – .lib/.dll contains header file and .o binary file (no .cpp as machine code .o already (pre-compiled to prevent source code leak and seldome change) linkage will use runtime support library .o

//<iostream> actually means iostream.h – history lesson               - non .h without std namespace, as well as our header files




No comments:

Post a Comment