Sept. 12, 1996
Bit Fields
Recall: Structure Format
struct date
{
int year;
float month
int day;
};
struct date
{
char name[20];
float miles;
int boroughs;
struct date inc_date;
struct date orig_date;
}info;
Recall:
- To assign a value to the variable miles
: info.miles = 2500;
- To assign a value to the variable month:
strcpy("May", info.inc_day.month);
Bit Fields are Used For
1. Increasing Efficiency
- to reduce read time
- to reduce write time
- to reduce storage/file requirements
2. Communications Programming
- protocols between devices (underline, bold, italic)
3. Security Purposes
- encrypting/decrypting data
Format
type name: size
Examples:
{
unsigned underline: 1;
unsigned boldface: 1;
unsigned italics: 1;
}printer;
- To set underline to off:
printer.underline = 0;
- To set boldface to on:
printer.boldface = 1;
- Number of bits used:
3
struct
{
unsigned code1: 4;
unsigned code2: 2;
unsigned code3: 8;
}p;
- Number of bits used:
14
- Number of bytes used:
2 (two bits are wasted)
struct
{
unsigned code1: 4;
unsigned: 3;
unsigned code2: 2;
unsigned code3: 8;
}p;
Remember
compiling will not expose errors in bit fields
bits do not have addresses and cannot be assigned to an array
bits are not always portable
Sept. 19, 1996
Function Pointers
References
Turbo C/C++ pages 104-107 & 149-151
Function Pointers
a variable that contains the address of the starting point of a function
Example:
int sum(int a, int b);
void main(void)
{
int result;
result = sum(10, 12)
printf(" %d ", result);
}
sum(int a, int b)
{
return(a+b);
}
Can be coded as follows:
int (*p) (int a, int b);
int sum(int a, int b);
void main(void)
{
int result;
p = sum
result = (*p)(10, 20);
printf(" %d ", result);
}
sum(int a, int b)
{
return(a+b);
}
Sept 19, 1996
Quick Sort
References
Business Programming in C pages 215-217
Turbo C/C++ pages 697-699
Format
- qsort(address, elements, size, function pointer);
- requires stdlib.h
Example:
qsort(array, 100, sizeof(int), comp);
Oct. 3, 1996
Dynamic Allocation
Reference
- Black Book - pages 368 - 372
- Turbo C/C++ - pages 122-125 & 140 - 142
Purpose
Problem: In our first assignment, we coded an array of structures called homres_records[50]. The said structure is capable of holding 50 records.
Question 1: What if the user has 75 homes? (not enough memory)
Question 2: What if the user has only 10 homes? (too much memory)
The purpose of Dynamic Allocation is to allot the available RAM to a program on a need to basis
Dynamic Allocation
- four functions: maloc(), colloc(), realloc(), and free()
- malloc(), calloc, and realloc() all allocate memory
- free() releases memory that has been previously allocated
- malloc() assigns memory space and fills said space with garbage
- calloc() also assigns memory space, but fills said space with zeros
- realloc() reallocates memory if the initial allocation is insufficient
Example 1
int *p;
p = (int *) malloc(100);
- assigns the starting address of 100 consecutive bytes of RAM to a pointer (p)
Example 2
int *addr;
addr = (int *)calloc(200, sizeof(int));
- assigns the starting address of 400 consecutive bytes of RAM to a pointer (addr)
- 400 = (200 * 2)
Example 3
char *wordpointer;
char word[25];
wordpointer = (char *) malloc(strlen(word) +1);
- assigns the starting address of 26 consecutive bytes of RAM to a pointer (wordpointer)
Example 4
wordpointer = (char *) realloc(wordpointer, 15);
- reallocates 15 consecutive bytes of RAM to the address pointer wordpointer
- wordpointer now points to the starting address of 15 consecutive bytes (original allocation is forgotten)
Example 5
free(wordpointer);
- releases the 15 bytes of memory allocated to wordpointer
- memory is also released when the program is exited
- computer will hang if all available RAM is allocated
Oct 10, 1996
Colours and Graphics
Reference
- Black Book Chapter 13
- Turbo C/C++ Chapter 11 and 23
Setting the Monitor Mode
- in text mode, the smallest unit the monitor can address is a character
- in graphics mode, the smallest unit the monitor can address is a pixel
- the first address in test mode is (1,1)
- the first address in graphics mode is (0,0)
- in text mode, the monitor dimensions are 80 x 24
- in graphics mode, the monitor dimensions are 360 x 240
Format:
void main(void)
{
textmode(C80); /* sets the monitor mode */
-
-
textmode(LASTMODE); /* rests the monitor to its original setting */
}
Adding a Background Colour
Format:
textbackground(COLOUR); /* page 264 - 265 */
clrscr();
Adding a Text Background
Format:
textbackground(COLOUR); /* page 264 - 265 */
cprintf(" ")
Adding Colour to Text
Format:
textcolor(COLOUR);
cprintf(" ");
Moving the Cursor
Format:
gotoxy(column, rows); /* page 269 */
- if you need to know the coordinates of the cursor, use the wherex() and the wherey() functions
The cprintf() Function
- reference: page 258 - 259
- replaces the printf() function
- used to display text in colour on the screen
Example:
textcolor(RED);
cprintf("Hello /r ");
- use /r instead of /n
- /r moves the cursor down one row across to the first column
- /n will only move the cursor down one row (column position remains the same)
The cscanf() Function
- adds colour to input data
- replaces the scanf() function
Example:
printf("Enter List Price: ");
textcolor(BLUE);
cscanf(" %d ", num); /* page 600 */
The getche() Function
- flushes the buffer
- replaces the fflush() function
Example:
printf("Enter List Price: ");
textcolor(BLUE);
cscanf(" %d ", num);
getche();
The cgets() Function
- adds colour to input data
- replaces the gets() function
Example:
char name[22], *pointer;
*/ We always need to code two extra elements. The first element (name[0] in this example) holds the value of the maximum string size. The second element (name[1] in this example) holds the size of the string that is actually keyed in by the user. The remaining elements (in this example, name[2] through name[22]) contain the actual characters keyed in by the user */
name[0] = 19; */ maximum string size is set at 19 (20 if we include the null) */
printf("Enter Owner’s Name: ");
textcolor(BLUE);
pointer = cgets(name); */ assigns the address of name to the variable pointer */
textcolor(RED);
cprintf("The Home Owner’s Name is %s", pointer);
Available Colours
- black
- blue
- green
- cyan
- red
- megenta (purple)
- brown
- lightgrey
- darkgrey
- lightblue
- lightgreen
- lightcyan
- lightred
- light megenta
- yellow
- white
Oct. 17, 1996
Graphics
require the header file graphics.h
Setting the Background Colour
Format:
setbkcolor(COLOUR); \* Reference: page 275 *\
Setting the Text Colour
Format:
setcolor(COLOUR); \* Reference: page 276 *\
Moving the Cursor
Format:
moveto(X, Y); \* Reference: page 639 *\
Displaying Text
Format:
outtext("STRING");
Setting the Text Style
Format
settextstyle(FONT, DIRECTION, SIZE);
- direction refers to the flow of the text (HORIZ_DIR or VERT_DIR)
- size refers to the size each character (0-10)
- font refers to the style of the print
Centering Text
use getmaxx() and getmaxy()
getmaxx() will return the maximum row value
getmaxy() will return the maximau column value
Pie Charts
Format:
pieslice(X, Y, START, END, RADIUS);
- (x, y) refer to the origin of the slice
- START refers to the starting angle
- END refers to the ending angle
- RADIUS refers to the distance between the origin and the edge of the slice
Example:
pieslice(100, 150, 0, 60, 5)
Oct. 31, 1996
Classes
Definitions
Data Hiding - protecting your data from unauthorized access
User Defined Data (UDT) - a variable type defined by the user (also known as Abstract Data Type (ADT))
Private - main() does not have access
Public - main() has access
Encapsulation - combining data and functions inside a class
Access Functions - allow main to see the value of a private data member (get functions)
Classes
- default to private (structures default to public)
- a user defined data type
- contains data and functions
Format:
class Payroll
{
char name[30];
float salary;
};
void main(void)
{
Payroll employee;
}
Example 1:
class Store
{
int s_num;
double sales;
float pr_margin;
public:
char name[25];
char address[30];
long int sq_feet;
};
Store big_store;
strcpy(big_store.name, "Save All");
/* big_store.sales = 84543.43 will not compile */
Example 2:
class Date
{
int day;
int month;
int year;
public:
int get_month(void) { return(month); }
int get_day(void) { return(day); }
int get_year(void) { return(year); }
void set(const int d, const int m, const int y);
{
day = d;
month = m;
year = y;
}
};
Date today;
today.set(31, 10, 1996); /* Sets the date to October 31, 1996 */
printf(" %d", today.get_day()); /* Displays the Current Day */
Non-Inline Functions
- the function definition is located outside of the class
Format:
class Date
{
public:
int test_date(const int d);
int test_month(const int m);
int test_year(const int y);
};
int Date :: test_day(const int d)
{
return (d > 31) ? 0 : 1;
}
- can be saved as class.h
- :: is referred to as a scope resolution operator
The cin Operator
- is an object belonging to the class iostream.h
- refers to the keyboard buffer
- similar to the scanf() function
Example:
cin >> d >> m >> y ;
- >> is called an extractor
- do not need to worry about format specifiers
The cout Operator
- is an object belonging to the class iostream.h
- similar to the printf() function
- << is called an insert operator
- stops at white space
Examples:
1. cout << "What is today’s day, month, and year?"; // Displays a message on the screen
2. cout << "The date is set to " today.get_month(); // Displays a message and other data (details)
void main(void)
{
int years = 4;
char mesg[] = {I want to learn C++);
cout << "I’ve known C for " <<years<< "years."<<mesg;
}
4. cout << "Chun" <<endl; // Displays a message and moves the cursor down one line (same as \n
Formatting Detail
require the header file manip.h
referred to as manipulators
setw( ); // Sets the minimum width size
setprecision( ); // Sets the decimal precision
setiosflag(ios :: fixed); // Sets the notation (fixed, scientific)
setiosflag(ios :: UPERCASE); // Sets all letters to uppercase (uppercase, lowercase)
setiosflag(ios :: SHOWPOS); // Shows the sign
setiosflag(ios :: SHOWPOINT); // Shows the decimal point and all significant digits
Nov. 14, 1996
Dynamic Allocation
Reference
- Moving from C to C++
Chapter 4 Pages 67-72
Format
struct patient
{
char name[20];
int age;
} * patient_ptr;
patient_ptr = (patient *) malloc(sizeof(patient)); */ C method of allocating memory */
free(patient_ptr); */ C method of freeing memory */
patient_ptr = new patient; */ C++ method of allocating memory */
delete patient_ptr; */ C++ method of freeing memory */
- new and delete are operators
- cannot mix and-match-techniques (must use new and delete together)
Nov. 14, 1996
Throwing an Exception
- used to catch errors
- will replace previously learned error checking techniques
Format
extern void (*set_new_handler (void (*memory_err) () )) ();
void memory_err()
{
cout << "A Memory Allocation Error Occurred. \n";
exit(1);
}
void main()
{
set_new_handler(memory_error);
-
-
-
}
Nov. 14, 1996
Polymorphism
Reference
- Moving from C to C++
Chapter 9
Definition
- is using the same function name to work on objects of different classes
- similar to overloading functions, but significantly different
Example:
Let us assume two classes exist in a particular program. One class is called "Employee", and the other class is called "Customer". Both classes possess a public member function called "print()".
void main()
{
Employee employee; */ creates an object of the class Employee */
Customer customer */ creates an object of the class Customer */
employee.print(); */ calls print() defined in the Employee class */
customer.print(); */ calls print() defined in the Customer class */
}
Nov. 14, 1996
Constructors and Destructors
Reference
- Moving from C to C++
Chapter 10
Constructor Rules
- posses the same name as the class
- possess no return type
- must be public
- may uses constructors of the same name (function overloading)
- may use arguments and defaults
- system calls constructors automatically (do not code a call)
Example:
class Sample
{
-
-
public:
Sample();
Sample (int init)
{
C = ‘A’;
I = init;
x = 20;
}
-
-
};
void main()
{
Sample avar;
Sample avar(7);
-
-
}
Destructor Rules
- given the same name as the class plus a ~
- never posses a return type
- cannot be overloaded
- must be coded public
- cannot contain arguments
- must be called implicitly
Example:
class Sample
{
-
-
-
public:
~Sample();
-
-
}
Sample :: ~Sample()
{
cout << "Destructor was Called"
}
Nov. 20, 1996
Inheritance
Reference
- Moving from C to C++
Chapters 14 and 15
- Turbo C/C++
Chapter 28
- Complete Reference
Pages 723-24, 733-737, 763, and 773
- Errors: 248 - 254)
Notes:
- cannot use inheritance in C (code will not compile)
- allows one to reuse code over and over
- associated with the class concepts discussed earlier
- Parent or Base Class
- data members and member functions are passed down to its children
- Child or Derived Class
- receives or inherits data members and member functions from a parent
- Primary Base Class
- root class in an inheritance
- Single Inheritance
- child has a one parent
- Multiple Inheritance
- child has two parents
Format
class Name
{
private:
-
-
-
protected:
-
-
-
public:
-
-
-
};
class Name2 : (DERIVED CLASS ACCESS) Name
{
private:
-
-
public:
-
-
-
};
- class Name2 inherits all data members and member functions from the Name class
Data Member/Member Function Classifications
- three types: private, protected, and public
- define the accessibility of a data member or member function
- when a data member is classified private, only member functions inside the class have access
- when a data member is classified public, main ( ) and all member functions have access
- when a data member is classified protected, only member functions have access
Derived Class Classifications
- three types: private, protected, and public
- play a role in defining the accessibility of a data member or member function
- refer to the chart on page 68 for an accessibly summary
Nov. 21, 1996
Initialization List
Reference
- Moving from C to C++
Page 261
Notes:
- a different way to initialize variables
- more compact (single line of code)
Example:
class Store
{
int num;
float sales;
public:
Store(int n, float s)
{
num = n;
sales = s;
}
-
-
-
};
Nov. 29, 1996
THIS Pointer
Reference
Moving from C to C++ Chapter 9 Pages 141-142
Turbo C and C++ Chapter 27 Pages 786-787
Notes
- included in the iostream.h header file
- automatically created when a call to a member function is made
- points to the object of a class
- format: this
Example:
- program coded without the THIS pointer:
#include <iostream.h>
class Test
{
int variable;
public:
void load_variable(int val) {variable = val;}
void get_variable (void) {return(variable);}
};
void main(void)
{
Test Object;
Object.load_variable(100);
cout << Object.get_variable();
}
- same program coded using the THIS pointer:
#include <iostream.h>
class Test
{
int variable;
public:
void load_variable(int val) {this -> variable = val;}
void get_variable (void) {return(this -> variable);}
};
void main(void)
{
Test Object;
Object.load_variable(100);
cout << Object.get_variable();
}
Dec. 5, 1996
Static Data Members
global variable with class scope
Example:
class People
{
char name[30];
int age;
public:
static int total;
People();
~People();
Getit();
};
People :: People() {}
People :: ~People() {}
int People :: total = 1; \\ Function Definition
void main(void)
{
cout << People :: total << endl;
People :: total++;
cout << People :: total;
}
Dec. 5, 1996
Operator Overloading
- using an operator for more than one purpose
- compiler know which purpose by the context of the statement