Pages

July 26, 2010

Revew OOP244 - Derived Class

The subject of an "is-a-kind-of" relationship is the derived class. The object is the base class.

Little notes
student.Person::display();

Derived Class with resource copy constructor, please refer here.

Revew OOP244 - Conversion Operators

The form of a conversion operator declaration is
 operator dataType() const;

example: operator int() const;



In our case, the compiler fails to find an exact, promoted,
or standard-conversion match for any argument-parameter pair,
and searches the single argument constructors for a derived data
type conversion match. The compiler inserts the
constructor code to convert 1234 to a
Student and then calls the assignment
operator that receives a Student as
its right operand. That is,
harry = 1234; // calls operator=(const Student& Student(1234))
If the Student(int) constructor were absent, the compiler could not convert 1234 to a Student and would reject the assignment expression. However, if our class declaration had a Student(long long) constructor, the compiler could convert 1234 to 1234LL, then convert 1234LL to a Student data type, and finally assign the right Student operand to the left Student operand.

To comprehend above please refer more detail

Revew OOP244 - Custom iostream Operators

Revew OOP244 - deep copy

In object-oriented programming, an object is not limited to the information stored in its own memory. An object can also access resources. A resource is information that is available to the object but is stored outside the object. The structure of such objects is described by classes with resources.

Resources

Resources include dynamic memory and files. These collections of information contain data that is stored outside the memory allocated to an object. An object keeps track of its resources through instance variables that hold the addresses of the resources. Such instance variables include

  • pointers to dynamic arrays in freestore memory
  • pointers to file structures
  • references
We call such instance variables resource instance variables.

To enable deep copying, we overwrite the compiler defaults for two member functions:

  1. the copy constructor
  2. the assignment operator

A copy constructor declaration takes the form

 Identifier ( const Identifier& );

Assignment Operator

The assignment operator is an operator that copies data from an existing object into an existing object. The compiler calls this operator whenever the compiler encounters an expression of the form

identifier = identifier where identifier is the name of an object.

The form of an assignment operator declaration is

Identifier& operator=(const Identifier&);

No Copies Allowed

In certain applications, it may be wise to avoid the making copies or assignments altogether. To prohibit the copying and the assigning of objects, we declare the copy constructor and the assignment operator as private members. For example,


class Student { int no; char* grade; Student(const Student& source); void operator=(const Student& source); public: Student(); Student(int, const char*); ~Student(); void display() const; };

Revew OOP244 - Operator +

 Student operator+(const Student &student, char grade) {
Student modified = student;
modified += grade; // calls += operator
return modified;
}

Student operator+(char grade, const Student &student) {
return student + grade; // calls operator+(const
// Student&, char)
}


Revew OOP244 - friend & friend class

friend type helper(...);
in .h file
friend int operator==(const Student&, const Student&);
in .cpp file
int operator==(const Student& lhs, const Student& rhs) {
return lhs.no == rhs.no &&
strcmp(lhs.grade, rhs.grade) == 0;
}


Friend Classes (Optional)

A class can grant access to its own private members to all of the member functions of another class. A class friendship declaration takes the form

friend class Identifier;

where Identifier is the name of the class that is to have private access privileges.

class student{

...

public:

...

friend class Administrator;

}

Revew OOP244 - Operators overload

Candidates for Overloading

We may overload the following operators (amongst others):

  1. post-fix/pre-fix (++ --)
  2. assignment (= += -= *= /= %=)
  3. unary arithmetic (+ -)
  4. binary arithmetic (+ - * / %)
  5. relational (== < > <= >= !=)
  6. logical (&& || !)

We may NOT overload the following operators

  • the scope resolution operator (::)
  • the member selection operator (.)
  • the member selection through pointer to member operator (.*)
  • the ternary operator (?:)
  • the sizeof operator (sizeof)
  • the typeid operator (type())
Post-Fix Operators
Type operator++(int)  or  Type operator--(int)
The int type in the parameter list
distinguishes the post-fix operator from its pre-fix
counterpart.

 Student Student::operator++() {
for (int i = 0; grade[i] != '\0'; i++)
if (grade[i] == 'F') grade[i] = 'D';
else if (grade[i] != 'A') grade[i]--;
return *this;
}

Student Student::operator++(int) {
Student s = *this; // save the original
++(*this); // call the pre-fix operator
return s; // return the original
}

Revew OOP244 -

Manipulator Effect
fixed display floats in fixed-point format
scientific display floats in floating-point format
left left justify
right right justify
flush flush the output buffer
endl send end of line and flush
setprecision(int) set number of digits output
setfill(int) set fill character
setbase(int) set base for int output
setw(int) set field width for next output only

call global function

 display();   // calls member function from inside a member function
::display(); // calls global function from inside a member function

Revew OOP244 - Insufficient Memory

include
Student* student = NULL;
student = new (nothrow) Student[n];
if (student == NULL)
cout << "Memory Allocation Failed" <<>
else {
...
}

Revew OOP244 - Dynamic Memory

A program that the operating system has loaded into primary memory may obtain additional memory from the operating system at run-time. We refer to this additional memory as dynamic memory.

Variables and objects stored in dynamic memory can survive until the program terminates if necessary. Their lifetime only ends when the program explicitly deallocates their dynamic memory. Note that, unlike variables and objects in static memory, those in dynamic memory do not go of out scope at the closing brace of the block within which they have been defined.

July 25, 2010

Review OOP244 - Primitive types & Derived Types

Both C and C++ predefine all of their primitive types. We cannot redefine these types or introduce new primitive types.
int,double,float,char

derived types
struct Type{
...
};

 struct Student {
int no; // student number
char grade[14]; // grades
};


struct Student harry;


to access harry's student number, we write

harry.no;


to get address of harry's student number, we write

&harry.no;
//&harry.grade[0];

We retrieve the address of a non-array member using the address of operator (&)


&instance.member

Revew OOP244 - Array and Pointer

y=NULL;
cout < < y; output is 0 double* address= NULL; y=*address; cout< < y; output is segementation fault

Tips on char* and char array
 char str[] = "This is OOP244";
char* s;

s = &str[8]; // points to the first 'O' in OOP244
cout << *(s + 3) << endl; // displays 244

Review OOP244 - Modular Programs

3 concepts applies to designing classes
Encapsulation, Inheritance, Polymorphism


What Does Compiler Do?
  1. the pre-processor inserts the contents of the header files into the implementation file for each module and substitutes all #define strings to create a single source file ready for compilation
  2. the compiler properly compiles each pre-processed source file and create a binary file
  3. the linker assembles the binary files for the application with the library binary files to form a single executable file
Summary
  • an application may be divided into a number of independent components: these components are called modules
  • a different module can be defined for each class in an application due to the encapsulated nature of the class
  • preparation of an executable file entails three separate stages: pre-processing, compilation and linking
  • each module consists of a header file and an implementation file and is pre-processed and compiled independently
  • a module's header file contains the declarations of the module's names without definitions or any executable statements
  • a module's implementation file contains the definitions of the module's functions
  • for compilation, a module's implementation file only needs to include the header files of those modules that contain declarations of the names referred to in the implementation file itself

swap is a common function name which be used in basic libraries

try to avoid use it "swap" as function name

New Style Casts

New Style Casts

The new style casts are both more specific and much easier to spot. Their syntax includes the letters _cast, which makes searching more straightforward. The casts are in template function form, where the variable or object to be cast is passed as the function argument and the destination type is passed as the template argument. There are four distinct categories of casts:

  • static cast
    static_cast( minutes )
  • const cast
    const_cast(&p)(Polygon is a class here)
  • re-interpret cast
  • Re-Interpret Cast

    A re-interpret cast converts a value between unrelated data types such asinteger to pointer type, pointer to unrelated pointer type

For example,


 // Re-Interpret Cast
// reinterpret.cpp
// Nov 21 2005

#include
using namespace std;

int main( ) {
int* p;
int x = 0x00ff00;

p = reinterpret_cast( x ); // New Style Cast
cout << hex << p << endl;

return 0;
}
  • dynamic cast

July 24, 2010

shortcut to compile on matrix

To compile in matrix, use: g++ yada.cpp yadoo.cpp -x c iof.c -lncurses If you have many cpp's, you may also do g++ *.cpp -x c iof.c -lncurses

keywords throw / try /catch and example of their usage

 void divide(int a[], int i, int n, int divisor) {
if(i <>= n)
throw "Outside array bounds";
else if(divisor == 0)
throw divisor;
else
a[i] = i / divisor;
}

int main() {
bool keepgoing = true;
int a[MAX] = {1,2,3,4,5,6,7,8,9,10}, index,
divisor;

do {
try {
cout << "Index: "; cin >> index;
cout << "Divisor: "; cin >> divisor;
divide(a, index, MAX, divisor);
cout << "a[index] = " << class="high">} catch(const char* msg) {

cout << keepgoing =" false;" class="high">} catch(int value) {
cout << "Zero divisor" << class="high">}
} while (keepgoing);

return 0;
}

All of the code within the try
block is executed repeatedly unless an exception is thrown by
any of the statements within the block. If an exception is
thrown, any remaining code within the try block is skipped and the code in the first
catch block that receives a type
matching the type of the thrown exception is executed. If
an exception is thrown and no match is found at any point in the
program, the program calls std::terminate(), which terminates
execution.


what is dynamic_cast?

 bool Box::operator==(const Shape& s) const {
return hght == dynamic_cast(s).hght &&
wdth == dynamic_cast(s).wdth &&
dpth == dynamic_cast(s).dpth;
}


Answer:

The cast of the reference to a Shape to a reference to a Box is necessary to enable access to the size instance variables of the Box object. We call this a dynamic cast. Without this cast, the compiler would generate an error to the effect that the size variables are not members of the Shape class:

 bool Box::operator==(const Shape& s) const {
return hght == s.hght && // ERROR hght is not a member of s
wdth == s.wdth && // ERROR wdth is not a member of s
dpth == s.dpth; // ERROR dpth is not a member of s
}

On the other hand, receiving a reference to a Box object directly would accept the definition
bool Box::operator==(const Box& s) const { // ERROR does not define
// == const Shape&

return hght == s.hght && wdth == s.wdth && dpth == s.dpth;
}

abstract class Pure Virtual Functions

An abstract class identifies the properties that need to be defined through pure virtual functions. For instance, if a Shape has a volume, then the abstract Shape class would include a pure virtual function for volume.

The term interface refers to an abstract class that contains no data members.

and / or

A class that includes at least one pure virtual function is an abstract base class. (may contains data members on this situation)

Pure Virtual Functions

A pure virtual function is a virtual function that has form but no implementation. The declaration of a pure virtual function takes the form

 virtual type identifier(parameters) = 0;

Virtual Inheritance

To avoid duplication of the instance of the base class, the Box and ColouredShape object can share the same Shape object.

// A Box
// Box.h
// Jun 9 2007

#include "Shape.h"

class Box :
virtual public Shape {
int hght;
int wdth;
int dpth;
protected:
void displayDetails() const;
public:
Box(const char* s, int h, int w, int d);
virtual void display() const;
};


Read more details https://cs.senecac.on.ca/~btp300/pages/content/minhe.html

Diamond problem

From Wikipedia, the free encyclopedia
Jump to: navigation, search
A diamond class inheritance diagram.

In object-oriented programming languages with multiple inheritance and knowledge organization, the diamond problem is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If a method in D calls a method defined in A (and does not override the method), and B and C have overridden that method differently, then from which class does it inherit: B, or C?

Please refer to http://en.wikipedia.org/wiki/Diamond_problem

July 22, 2010

UNIX and Linux Scripts

The Unix environment variable $? holds the return value from the program that has just completed execution.

MS DOS

The MS-DOS environment variable %errorlevel% holds the return value from the program that has just completed execution.
The macro NULL is defined in several system header files, including stddef.h and stdio.h.
It is good style to set every pointer that is not currently holding a valid address to NULL.

Odd Test

The & operator provides a simple way to check if an integral value is odd: that is, whether its least significant bit is 1.

 odd  = value & 1

odd has the value 1 if value is odd, 0 if value is even.

July 21, 2010

Note that sizeof() takes a type, while sizeof takes a variable, object or expression. With some compilers, the two operators are interchangeable.

For normal usage, we may add the keyword auto (for automatic) to the definition


 auto int local = 2;

Since this is the default for any function parameter or any variable defined within a block, we seldom see this keyword in practice.

For very frequent usage, we add the keyword register to the definition


 register int local = 2;
static int local = 2;

External Linkage

A variable of static duration with external linkage can be shared by several modules. The compiler allocates memory for the variable in one module and the linker allows all modules access to that memory location. Each reference to the variable accesses the same memory location, regardless of the module from which the reference is made. To identify external linkage, we add the keyword extern to the declaration


extern int shared;


C Conversion Specifiers

The C language conversion specifiers for the int type used in calls to scanf() are

Specifier Input Value Argument Default Conversion
%c cc...c char* one or more characters
%d [-|+]dd...d int* signed decimal
%i [-|+][0[x]]dd...d int* signed integer
%u [-|+]dd...d unsigned* unsigned decimal
%o [-|+]dd...d unsigned* unsigned octal
%x [-|+][0x]dd...d unsigned* unsigned hexadecimal

July 16, 2010

for myself remind

create an account on the silverhouse.com?
explorer the binary file format and operation in C++ to prepare for assignment

July 11, 2010

Linked List

2 posted articles I googled them
http://www.fredosaurus.com/notes-cpp/ds-lists/list-ex1a.html it supports *head and *back pointer. which I'm perfer.
http://www.dreamincode.net/code/snippet82.htm this one easy and clean for the beginner.

To enable removeBack() method wihout using loop in linked list. I guess unless I put another attribute of a point* of node to point the previous node; otherwise it is an unsolved quest.