+7 (905) 507-49-35

Гарантии качества

Наша компания уже более 10 лет работает на рынке города и области!

У нас работают ПРОФЕССИОНАЛЫ высочайшего класса.

Проводим предварительную консультацию.

Отзывы
  • Смолякова Ирина

    Очень благодарны Ларисе Михайловне, Екатерине Михайловне за чуткое отношение, добрый настрой и профессионализм.

  • Арбузова Светлана

    Очень довольна работой. Спасибо большое! Все четко, организованно и качественно. Теперь мы довольные и счастливые!

Новости
  • Полная настройка asterisk и всего что с ним связано

    17 апреля 2017 г.

    Никоноров М.Ю, Ефременко А.В Телефония Asterisk с нуля Подробное пошаговое руководство Приложение к одноименному видеокурсу © Никоноров М.Ю, 2014 2 Оглавление 1. Устанавливаем ОС Linux сборки CentOS………………………………………………………………………………………….. 4 2. Установка Putty………………………………………………………………………………………………………………………………. 5 3. Установка Asterisk. …………………………………………………………………………………………………………………………. 5 4. Конфигурация Asterisk для совершения звонков между внутренними абонентами. ……………………… 9 5. Конфигурация Asterisk на работу через транк […]

  • День победы

    22 декабря 2015 г.

    День Победы – это праздник, который объединяет всех: и молодежь, и пожилые люди, и дети хранят светлую память о героях войны.

Исходники Герберта Шилдта

Исходники Герберта Шилдта.

listing 1
/* Program #1 — A first C++ program.

Enter this program, then compile and run it.
*/

#include <iostream>
using namespace std;

// main() is where program execution begins.
int main()
{
cout << «This is my first C++ program.»;

return 0;
}

listing 2
/* Program #1 — A first C++ program.

Enter this program, then compile and run it.
*/

listing 3
#include <iostream>

listing 4
using namespace std;

listing 5
// main() is where program execution begins.

listing 6
int main()

listing 7
cout << «This is my first C++ program.»;

listing 8
return 0;

listing 9
#include <iostream.h>

listing 10
using namespace std;

listing 11
#include <iostream>
using namespace std;

listing 12
#include <iostream.h>

listing 13
// Program #2 — Using a variable

#include <iostream>
using namespace std;

int main()
{
int x; // this declares a variable

x = 1023; // this assigns 1023 to x

cout << «This program prints the value of x: «;
cout << x; // This displays 1023

return 0;
}

listing 14
int x; // this declares a variable

listing 15
x = 1023; // this assigns 1023 to x

listing 16
cout << x; // This displays 1023

listing 17
// This program converts gallons to liters.

#include <iostream>
using namespace std;

int main()
{
int gallons, liters;

cout << «Enter number of gallons: «;
cin >> gallons; // this inputs from the user

liters = gallons * 4; // convert to liters

cout << «Liters: » << liters;

return 0;
}

listing 18
cin >> gallons; // this inputs from the user

listing 19
cout << «Liters: » << liters;

listing 20
/* This program converts gallons to liters using
floating point numbers. */

#include <iostream>
using namespace std;

int main()
{
double gallons, liters;

cout << «Enter number of gallons: «;
cin >> gallons; // this inputs from the user

liters = gallons * 3.7854; // convert to liters

cout << «Liters: » << liters;

return 0;
}

listing 21
/* This program contains two functions: main()
and myfunc().
*/
#include <iostream>
using namespace std;

void myfunc(); // myfunc’s protoype

int main()
{
cout << «In main()»;
myfunc(); // call myfunc()
cout << «Back in main()»;

return 0;
}

void myfunc()
{
cout << » Inside myfunc() «;
}

listing 22
void myfunc(); // myfunc’s prototype

listing 23
// Use the abs() function.
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
cout << abs(-10);

return 0;
}

listing 24
void mul(int x, int y)
{
cout << x * y << » «;
}

listing 25
// A simple program that demonstrates mul().

#include <iostream>
using namespace std;

void mul(int x, int y); // mul()’s prototype

int main()
{
mul(10, 20);
mul(5, 6);
mul(8, 9);

return 0;
}

void mul(int x, int y)
{
cout << x * y << » «;
}

listing 26
// Returning a value.

#include <iostream>
using namespace std;

int mul(int x, int y); // mul()’s prototype

int main()
{
int answer;

answer = mul(10, 11); // assign return value
cout << «The answer is » << answer;

return 0;
}

// This function returns a value.
int mul(int x, int y)
{
return x * y; // return product of x and y
}

listing 27
// An old-style way to code mul().
mul(int x, int y) // default to int return type
{
return x * y; // return product of x and y
}

listing 28
/* This program demonstrates the \n code, which
generates a new line.
*/
#include <iostream>
using namespace std;

int main()
{
cout << «one\n»;
cout << «two\n»;
cout << «three»;
cout << «four»;

return 0;
}

listing 29
if(10 < 11) cout << «10 is less than 11»;

listing 30
if(10==11) cout << «hello»;

listing 31
// This program illustrates the if statement.

#include <iostream>
using namespace std;

int main()
{
int a, b;

cout << «Enter first number: «;
cin >> a;
cout << «Enter second number: «;
cin >> b;

if(a < b) cout << «First number is less than second.»;

return 0;
}

listing 32
// A program that illustrates the for loop.

#include <iostream>
using namespace std;

int main()
{
int count;

for(count=1; count<=100; count=count+1)
cout << count << » «;

return 0;
}

listing 33
for(count=1; count<=100; count++)
cout << count << » «;

listing 34
if(x<10) {
cout << «too low, try again»;
cin >> x;
}

listing 35
// This program demonstrates a block of code.

#include <iostream>
using namespace std;

int main()
{
int a, b;

cout << «Enter first number: «;
cin >> a;
cout << «Enter second number: «;
cin >> b;

if(a < b) {
cout << «First number is less than second.\n»;
cout << «Their difference is: » << b-a;
}

return 0;
}

listing 36
x = y;
y = y+1;
mul(x, y);

listing 37
x = y; y = y+1; mul(x, y);



listing 1
int i, j, k;

char ch, chr;

float f, balance;

double d;

listing 2
#include <iostream>
using namespace std;

void func();

int main()
{
int x; // local to main()

x = 10;
func();
cout << «\n»;
cout << x; // displays 10

return 0;
}

void func()
{
int x; // local to func()

x = -199;
cout << x; // displays -199
}

listing 3
int func1(int first, int last, char ch)
{
.
.
.
}

listing 4
#include <iostream>
using namespace std;

void func1();
void func2();

int count; // this is a global variable

int main()
{
int i; // this is a local variable

for(i=0; i<10; i++) {
count = i * 2;
func1();
}

return 0;
}

void func1()
{
cout << «count: » << count; // access global count
cout << ‘\n’; // output a newline
func2();
}

void func2()
{
int count; // this is a local variable

for(count=0; count<3; count++) cout << ‘.’;
}

listing 5
#include <iostream>
using namespace std;

/* This program shows the difference between
signed and unsigned integers.
*/
int main()
{
short int i; // a signed short integer
short unsigned int j; // an unsigned short integer

j = 60000;
i = j;
cout << i << » » << j;

return 0;
}

listing 6
unsigned x;
unsigned int y;

listing 7
// This program prints the alphabet in reverse order.

#include <iostream>
using namespace std;

int main()
{
char letter;

for(letter = ‘Z’; letter >= ‘A’; letter—)
cout << letter;

return 0;
}

listing 8
ch = ‘Z’;

listing 9
wchar_t wc;
wc = L’A’;

listing 10
hex = 0xFF; // 255 in decimal
oct = 011; // 9 in decimal

listing 11
#include <iostream>
using namespace std;

int main()
{
cout << «\n\\\b»;

return 0;
}

listing 12
char ch = ‘a’;
int first = 0;
float balance = 123.23F;

listing 13
// An example that uses variable initialization.

#include <iostream>
using namespace std;

void total(int x);

int main()
{
cout << «Computing summation of 5.\n»;
total(5);

cout << «\nComputing summation of 6.\n»;
total(6);

return 0;
}

void total(int x)
{
int sum=0; // initialize sum
int i, count;

for(i=1; i<=x; i++) {
sum = sum + i;
for(count=0; count<10; count++) cout << ‘.’;
cout << «The current sum is » << sum << ‘\n’;
}
}

listing 14
#include <iostream>
using namespace std;

int main()
{
int x, y;

x = 10;
y = 3;
cout << x/y; // will display 3
cout << «\n»;
cout << x%y; /* will display 1, the remainder of
the integer division */
cout << «\n»;

x = 1;
y = 2;
cout << x/y << » » << x%y; // will display 0 1

return 0;
}

listing 15
x = x+1;

listing 16
++x;

listing 17
x = x-1;

listing 18
—x;

listing 19
x = x+1;

listing 20
++x; // prefix form

listing 21
x++; // postfix form

listing 22
x = 10;
y = ++x;

listing 23
x = 10;
y = x++;

listing 24
bool xor(bool a, bool b)
{
return (a || b) && !(a && b);
}

listing 25
// This program demonstrates the xor() function.
#include <iostream>
using namespace std;

bool xor(bool a, bool b);

int main()
{
bool p, q;

cout << «Enter P (0 or 1): «;
cin >> p;
cout << «Enter Q (0 or 1): «;
cin >> q;

cout << «P AND Q: » << (p && q) << ‘\n’;
cout << «P OR Q: » << (p || q) << ‘\n’;
cout << «P XOR Q: » << xor(p, q) << ‘\n’;

return 0;
}

bool xor(bool a, bool b)
{
return (a || b) && !(a && b);
}

listing 26
var>15 || !(10<count) && 3<=item

listing 28
(float) x / 2

listing 29
#include <iostream>
using namespace std;

int main() // print i and i/2 with fractions
{
int i;

for(i=1; i<=100; ++i )
cout << i << «/ 2 is: » << (float) i / 2 << ‘\n’;

return 0;
}

listing 30
x=10/y*(127/x);

x = 10 / y * (127/x);

listing 31
x = y/3-34*temp+127;

x = (y/3) — (34*temp) + 127;



listing 1
// Magic Number program.
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
int magic; // magic number
int guess; // user’s guess

magic = rand(); // get a random number

cout << «Enter your guess: «;
cin >> guess;

if(guess == magic) cout << «** Right **»;

return 0;
}

listing 2
// Magic Number program: 1st improvement.

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
int magic; // magic number
int guess; // user’s guess

magic = rand(); // get a random number

cout << «Enter your guess: «;
cin >> guess;

if(guess == magic) cout << «** Right **»;
else cout << «…Sorry, you’re wrong.»;

return 0;
}

listing 3
// Divide the first number by the second.

#include <iostream>
using namespace std;

int main()
{
int a, b;

cout << «Enter two numbers: «;
cin >> a >> b;

if(b) cout << a/b << ‘\n’;
else cout << «Cannot divide by zero.\n»;

return 0;
}

listing 4
if(b == 0) cout << a/b << ‘\n’;

listing 5
if(i) {
if(j) statement1;
if(k) statement2; // this if
else statement3; // is associated with this else
}
else statement4; // associated with if(i)

listing 6
// Magic Number program: 2nd improvement.

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
int magic; // magic number
int guess; // user’s guess

magic = rand(); // get a random number

cout << «Enter your guess: «;
cin >> guess;

if (guess == magic) {
cout << «** Right **\n»;
cout << magic << » is the magic number.\n»;
}
else {
cout << «…Sorry, you’re wrong.»;
if(guess > magic) cout <<» Your guess is too high.\n»;
else cout << » Your guess is too low.\n»;
}

return 0;
}

listing 7
// Demonstrate an if-else-if ladder.
#include <iostream>
using namespace std;

int main()
{
int x;

for(x=0; x<6; x++) {
if(x==1) cout << «x is one\n»;
else if(x==2) cout << «x is two\n»;
else if(x==3) cout << «x is three\n»;
else if(x==4) cout << «x is four\n»;
else cout << «x is not between 1 and 4\n»;
}

return 0;
}

listing 8
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
int num;
double sq_root;

for(num=1; num < 100; num++) {
sq_root = sqrt((double) num);
cout << num << » » << sq_root << ‘\n’;
}

return 0;
}

listing 9
#include <iostream>
using namespace std;

int main()
{
int i;

for(i=100; i >= -100; i = i-5) cout << i << ‘ ‘;

return 0;
}

listing 10
for(count=10; count < 5; count++)
cout << count; // this statement will not execute

listing 11
for(x=0, y=10; x<=10; ++x, —y)
cout << x << ‘ ‘ << y << ‘\n’;

listing 12
#include <iostream>
#include <conio.h>
using namespace std;

int main()
{
int i;

// print numbers until a key is pressed
for(i=0; !kbhit(); i++) cout << i << ‘ ‘;

return 0;
}

listing 13
#include <iostream>
using namespace std;

int main()
{
int x;

for(x=0; x != 123; ) {
cout << «Enter a number: «;
cin >> x;
}

return 0;
}

listing 14
cout << «Enter tab position: «;
cin >> x;

for( ; x < tablimit; x++) cout << ‘ ‘;

listing 15
for(;;)
{
//…
}

listing 16
for(x=0; x<1000; x++) ;

listing 17
// Demonstrate the switch using a simple «help» program.
#include <iostream>
using namespace std;

int main()
{
int choice;

cout << «Help on:\n\n»;
cout << «1. for\n»;
cout << «2. if\n»;
cout << «3. switch\n\n»;

cout << «Enter choice (1-3): «;
cin >> choice;
cout << «\n»;

switch(choice) {
case 1:
cout << «for is C++’s most versatile loop.\n»;
break;
case 2:
cout << «if is C++’s conditional branch statement.\n»;
break;
case 3:
cout << «switch is C++’s multi-way branch statement.\n»;
break;
default:
cout << «You must enter a number between 1 and 3.\n»;
}

return 0;
}

listing 18
#include <iostream>
using namespace std;

int main()
{
int i;

for(i=0; i<5; i++) {
switch(i) {
case 0: cout << «less than 1\n»;
case 1: cout << «less than 2\n»;
case 2: cout << «less than 3\n»;
case 3: cout << «less than 4\n»;
case 4: cout << «less than 5\n»;
}
cout << ‘\n’;
}

return 0;
}

listing 19
switch(i) {
case 1:
case 2:
case 3: do_something();
break;
case 4: do_something_else();
break;

listing 20
switch(ch1) {
case ‘A’: cout << «This A is part of outer switch»;
switch(ch2) {
case ‘A’:
cout << «This A is part of inner switch»;
break;
case ‘B’: // …
}
break;
case ‘B’: // …

listing 21
/* This program displays all printable characters,
including the extended character set, if one exists.
*/

#include <iostream>
using namespace std;

int main()
{
unsigned char ch;

ch = 32;
while(ch) {
cout << ch;
ch++;
}

return 0;
}

listing 22
#include <iostream>
using namespace std;

int main()
{
int len;

cout << «Enter length (1 to 79): «;
cin >> len;

while(len>0 && len<80) {
cout << ‘.’;
len—;
}

return 0;
}

listing 23
while(rand() != 100) ;

listing 24
#include <iostream>
using namespace std;

int main()
{
int num;

do {
cout << «Enter a number (100 to stop): «;
cin >> num;
} while(num != 100);

return 0;
}

listing 25
// Magic Number program: 3rd improvement.

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
int magic; // magic number
int guess; // user’s guess

magic = rand(); // get a random number

do {
cout << «Enter your guess: «;
cin >> guess;
if(guess == magic) {
cout << «** Right ** «;
cout << magic << » is the magic number.\n»;
}
else {
cout << «…Sorry, you’re wrong.»;
if(guess > magic)
cout << » Your guess is too high.\n»;
else cout << » Your guess is too low.\n»;
}
} while(guess != magic);

return 0;
}

listing 26
#include <iostream>
using namespace std;

int main()
{
int x;

for(x=0; x<=100; x++) {
if(x%2) continue;
cout << x << ‘ ‘;
}

return 0;
}

listing 27
#include <iostream>
using namespace std;

int main()
{
int t;

// Loops from 0 to 9, not to 100!
for(t=0; t<100; t++) {
if(t==10) break;
cout << t << ‘ ‘;
}

return 0;
}

listing 28
for(i=0; i<1000; i++) {
// do something
if(kbhit()) break;
}

listing 29
#include <iostream>
using namespace std;

int main()
{
int t, count;

for(t=0; t<100; t++) {
count = 1;
for(;;) {
cout << count << ‘ ‘;
count++;
if(count==10) break;
}
cout << ‘\n’;
}

return 0;
}

listing 30
/* This program finds the prime numbers from
2 to 1000.
*/

#include <iostream>
using namespace std;

int main()
{
int i, j;

for(i=2; i<1000; i++) {
for(j=2; j <= (i/j); j++)
if(!(i%j)) break; // if factor found, not prime
if(j > (i/j)) cout << i << » is prime\n»;
}

return 0;
}

listing 31
x = 1;
loop1:
x++;
if(x < 100) goto loop1;

listing 32
for(…) {
for(…) {
while(…) {
if(…) goto stop;
.
.
.
}
}
}
stop:
cout << «Error in program.\n»;

listing 33
// Magic Number program: Final improvement.

#include <iostream>
#include <cstdlib>
using namespace std;

void play(int m);

int main()
{
int option;
int magic;

magic = rand();

do {
cout << «1. Get a new magic number\n»;
cout << «2. Play\n»;
cout << «3. Quit\n»;
do {
cout << «Enter your choice: «;
cin >> option;
} while(option<1 || option>3);

switch(option) {
case 1:
magic = rand();
break;
case 2:
play(magic);
break;
case 3:
cout << «Goodbye\n»;
break;
}
} while(option!=3);

return 0;
}

// Play the game.
void play(int m)
{
int t, x;

for(t=0; t<100; t++) {
cout << «Guess the number: «;
cin >> x;
if(x==m) {
cout << «** Right **\n»;
return;
}
else
if(x<m) cout << «Too low.\n»;
else cout << «Too high.\n»;
}
cout << «You’ve used up all your guesses. Try again.\n»;
}



listing 1
int sample[10];

listing 2
#include <iostream>
using namespace std;

int main()
{
int sample[10]; // this reserves 10 integer elements
int t;

// load the array
for(t=0; t<10; ++t) sample[t]=t;

// display the array
for(t=0; t<10; ++t) cout << sample[t] << ‘ ‘;

return 0;
}

listing 3
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
int i, min_value, max_value;
int list[10];

for(i=0; i<10; i++) list[i] = rand();

// find minimum value
min_value = list[0];
for(i=1; i<10; i++)
if(min_value > list[i]) min_value = list[i];

cout << «minimum value: » << min_value << ‘\n’;

// find maximum value
max_value = list[0];
for(i=1; i<10; i++)
if(max_value < list[i]) max_value = list[i];

cout << «maximum value: » << max_value << ‘\n’;

return 0;
}

listing 4
int a[10], b[10];

// …

a = b; // error — illegal

listing 5
// An incorrect program. Do Not Execute!

int main()
{
int crash[10], i;

for(i=0; i<100; i++) crash[i]=i;

return 1;
}

listing 6
// Using the bubble sort to order an array.
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
int nums[10];
int a, b, t;
int size;

size = 10; // number of elements to sort

// give the array some random initial values
for(t=0; t<size; t++) nums[t] = rand();

// display original array
cout << «Original array is: «;
for(t=0; t<size; t++) cout << nums[t] << ‘ ‘;
cout << ‘\n’;

// This is the bubble sort.
for(a=1; a<size; a++)
for(b=size-1; b>=a; b—) {
if(nums[b-1] > nums[b]) { // if out of order
// exchange elements
t = nums[b-1];
nums[b-1] = nums[b];
nums[b] = t;
}
}
// This is the end of the bubble sort.

// display sorted array
cout << «Sorted array is: «;
for(t=0; t<size; t++) cout << nums[t] << ‘ ‘;

return 0;
}

listing 7
char str[11];

listing 8
// Using cin to read a string from the keyboard.

#include <iostream>
using namespace std;

int main()
{
char str[80];

cout << «Enter a string: «;
cin >> str; // read string from keyboard
cout << «Here is your string: «;
cout << str;

return 0;
}

listing 9
// Using gets() to read a string from the keyboard.

#include <iostream>
#include <cstdio>
using namespace std;

int main()
{
char str[80];

cout << «Enter a string: «;
gets(str); // read a string from the keyboard
cout << «Here is your string: «;
cout << str;

return 0;
}

listing 10
#include <iostream>
#include <cstring>
using namespace std;

int main()
{
char str[80];

strcpy(str, «hello»);
cout << str;

return 0;
}

listing 11
#include <iostream>
#include <cstring>
using namespace std;

int main()
{
char s1[20], s2[10];

strcpy(s1, «hello»);
strcpy(s2, » there»);
strcat(s1, s2);
cout << s1;

return 0;
}

listing 12
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;

bool password();

int main()
{
if(password()) cout << «Logged on.\n»;
else cout << «Access denied.\n»;

return 0;
}

// Return true if password accepted; false otherwise.
bool password()
{
char s[80];

cout << «Enter password: «;
gets(s);

if(strcmp(s, «password»)) { // strings differ
cout << «Invalid password.\n»;
return false;
}

// strings compared the same
return true;
}

listing 13
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

int main()
{
char s[80];

for(;;) {
cout << «Enter a string: «;
gets(s);
if(!strcmp(«quit», s)) break;
}

return 0;
}

listing 14
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

int main()
{
char str[80];

cout << «Enter a string: «;

gets(str);

cout << «Length is: » << strlen(str);

return 0;
}

listing 15
// Print a string backwards.
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

int main()
{
char str[80];
int i;

cout << «Enter a string: «;
gets(str);

for(i=strlen(str)-1; i>=0; i—) cout << str[i];

return 0;
}

listing 16
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

int main()
{
char s1[80], s2[80];

cout << «Enter two strings: «;

gets(s1); gets(s2);

cout << «lengths: » << strlen(s1);
cout << ‘ ‘ << strlen(s2) << ‘\n’;

if(!strcmp(s1, s2))
cout << «The strings are equal\n»;
else cout << «not equal\n»;

strcat(s1, s2);
cout << s1 << ‘\n’;

strcpy(s1, s2);
cout << s1 << » and » << s2 << ‘ ‘;
cout << «are now the same\n»;

return 0;
}

listing 17
// Convert a string to uppercase.
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;

int main()
{
char str[80];
int i;

strcpy(str, «this is a test»);

for(i=0; str[i]; i++) str[i] = toupper(str[i]);

cout << str;

return 0;
}

listing 18
int twod[10][20];

listing 19
#include <iostream>
using namespace std;

int main()
{
int t,i, num[3][4];

for(t=0; t<3; ++t) {
for(i=0; i<4; ++i) {
num[t][i] = (t*4)+i+1;
cout << num[t][i] << ‘ ‘;
}
cout << ‘\n’;
}

return 0;
}

listing 20
int multidim[4][10][3];

listing 21
int i[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

listing 22
char str[6] = «hello»;

listing 23
char str[6] = {‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’};

listing 24
int sqrs[10][2] = {
1, 1,
2, 4,
3, 9,
4, 16,
5, 25,
6, 36,
7, 49,
8, 64,
9, 81,
10, 100
};

listing 25
int sqrs[10][2] = {
{1, 1},
{2, 4},
{3, 9},
{4, 16},
{5, 25},
{6, 36},
{7, 49},
{8, 64},
{9, 81},
{10, 100}
};

listing 26
#include <iostream>
using namespace std;

int sqrs[10][2] = {
{1, 1},
{2, 4},
{3, 9},
{4, 16},
{5, 25},
{6, 36},
{7, 49},
{8, 64},
{9, 81},
{10, 100}
};

int main()
{
int i, j;

cout << «Enter a number between 1 and 10: «;
cin >> i;

// look up i
for(j=0; j<10; j++)
if(sqrs[j][0]==i) break;
cout << «The square of » << i << » is «;
cout << sqrs[j][1];

return 0;
}

listing 27
#include <iostream>
#include <cstring>
using namespace std;

void f1();

int main()
{
f1();
f1();

return 0;
}

void f1()
{
char s[80]=»this is a test\n»;

cout << s;
strcpy(s, «CHANGED\n»); // change s
cout << s;
}

listing 28
char e1[14] = «Divide by 0\n»;
char e2[23] = «End-of-File\n»;
char e3[21] = «Access Denied\n»;

listing 29
char e1[] = «Divide by 0\n»;
char e2[] = «End-of-File\n»;
char e3[] = «Access Denied\n»;

listing 30
int sqrs[][2] = {
1, 1,
2, 4,
3, 9,
4, 16,
5, 25,
6, 36,
7, 49,
8, 64,
9, 81,
10, 100
};

listing 31
char str_array[30][80];

listing 32
gets(str_array[2]);

listing 33
// Enter and display strings.
#include <iostream>
#include <cstdio>
using namespace std;

int main()
{
int t, i;
char text[100][80];

for(t=0; t<100; t++) {
cout << t << «: «;
gets(text[t]);
if(!text[t][0]) break; // quit on blank line
}

// redisplay the strings
for(i=0; i<t; i++)
cout << text[i] << ‘\n’;

return 0;
}

listing 34
char name[10][80]; // this array holds employee names
char phone[10][20]; // their phone numbers
float hours[10]; // hours worked per week
float wage[10]; // wage

listing 35
// Enter information.
void enter()
{
int i;
char temp[80];

for(i=0; i<10; i++) {
cout << «Enter last name: «;
cin >> name[i];
cout << «Enter phone number: «;
cin >> phone[i];
cout << «Enter number of hours worked: «;
cin >> hours[i];
cout << «Enter wage: «;
cin >> wage[i];
}
}

listing 36
// Display report.
void report()
{
int i;

for(i=0; i<10; i++) {
cout << name[i] << ‘ ‘ << phone[i] << ‘\n’;
cout << «Pay for the week: » << wage[i] * hours[i];
cout << ‘\n’;
}
}

listing 37
// A simple employee database program.

#include <iostream>
using namespace std;

char name[10][80]; // this array holds employee names
char phone[10][20]; // their phone numbers
float hours[10]; // hours worked per week
float wage[10]; // wage

int menu();
void enter(), report();

int main()
{
int choice;

do {
choice = menu(); // get selection
switch(choice) {
case 0: break;
case 1: enter();
break;
case 2: report();
break;
default: cout << «Try again.\n\n»;
}
} while(choice != 0);

return 0;
}

// Return a user’s selection.
int menu()
{
int choice;

cout << «0. Quit\n»;
cout << «1. Enter information\n»;
cout << «2. Report information\n»;
cout << «\nChoose one: «;
cin >> choice;

return choice;
}

// Enter information.
void enter()
{
int i;
char temp[80];

for(i=0; i<10; i++) {
cout << «Enter last name: «;
cin >> name[i];
cout << «Enter phone number: «;
cin >> phone[i];
cout << «Enter number of hours worked: «;
cin >> hours[i];
cout << «Enter wage: «;
cin >> wage[i];
}
}

// Display report.
void report()
{
int i;

for(i=0; i<10; i++) {
cout << name[i] << ‘ ‘ << phone[i] << ‘\n’;
cout << «Pay for the week: » << wage[i] * hours[i];
cout << ‘\n’;
}
}



listing 1
int *p;

listing 2
float *p;

listing 3
int *ip; // pointer to integers

double *dp; // pointer to doubles

listing 4
balptr = &balance;

listing 5
value = *balptr;

listing 6
#include <iostream>
using namespace std;

int main()
{
int balance;
int *balptr;
int value;

balance = 3200;
balptr = &balance;
value = *balptr;
cout << «balance is: » << value << ‘\n’;

return 0;
}

listing 7
int *p;
double f;
// …
p = &f; // ERROR

listing 8
int *p ;
double f;
// …
p = (int *) &f; // Now technically OK

listing 9
// This program will not work right.
#include <iostream>
using namespace std;

int main()
{
double x, y;
int *p;

x = 123.23;
p = (int *) &x; // use cast to assign double * to int *

y = *p; // What will this do?
cout << y; // What will this print?

return 0;
}

listing 10
*p = 101;

listing 11
(*p)++;

listing 12
#include <iostream>
using namespace std;

int main()
{
int *p, num;

p = &num;

*p = 100;
cout << num << ‘ ‘;
(*p)++;
cout << num << ‘ ‘;
(*p)—;
cout << num << ‘\n’;

return 0;
}

listing 13
p1++;

listing 14
p1—;

listing 15
p1 = p1 + 9;

listing 16
#include <iostream>
using namespace std;

int main()
{
int *i, j[10];
double *f, g[10];
int x;

i = j;
f = g;

for(x=0; x<10; x++)
cout << i+x << ‘ ‘ << f+x << ‘\n’;

return 0;
}

listing 17
char str[80];
char *p1;

p1 = str;

listing 18
str[4]

listing 20
// Tokenizing program: pointer version.
#include <iostream>
#include <cstdio>
using namespace std;

int main()
{
char str[80];
char token[80];
char *p, *q;

cout << «Enter a sentence: «;
gets(str);

p = str;

// Read a token at a time from the string.
while(*p) {
q = token; // set q pointing to start of token

/* Read characters until either a space or the
null terminator is encountered. */
while(*p!=’ ‘ && *p) {
*q = *p;
q++; p++;
}
if(*p) p++; // advance past the space
*q = ‘\0’; // null terminate the token
cout << token << ‘\n’;
}

return 0;
}

listing 21
// Tokenizing program: array-indexing version.
#include <iostream>
#include <cstdio>
using namespace std;

int main()
{
char str[80];
char token[80];
int i, j;

cout << «Enter a sentence: «;
gets(str);

// Read a token at a time from the string.
for(i=0; ; i++) {
/* Read characters until either a space or the
null terminator is encountered. */
for(j=0; str[i]!=’ ‘ && str[i]; j++, i++)
token[j] = str[i];

token[j] = ‘\0’; // null terminate the token
cout << token << ‘\n’;
if(!str[i]) break;
}

return 0;
}

listing 22
// Indexing a pointer like an array.

#include <iostream>
#include <cctype>
using namespace std;

int main()
{
char str[20] = «hello tom»;
char *p;
int i;

p = str;

// index a pointer
for(i=0; p[i]; i++) p[i] = toupper(p[i]);
cout << p; // display the string

return 0;
}

listing 23
int num[10];
int i;

for(i=0; i<10; i++) {
*num = i; // this is OK
num++; // ERROR — cannot modify num
}

listing 24
*(num+3) = 100; // This is OK because num is not changed

listing 25
cout << strlen(«C++ Compiler»);

listing 26
#include <iostream>
using namespace std;

int main()
{
char *s;

s = «Pointers are fun to use.\n»;

cout << s;

return 0;
}

listing 27
#include <iostream>
using namespace std;

int main()
{
int num[10];
int *start, *end;

start = num;
end = &num[9];

while(start <= end) {
cout << «Enter a number: «;
cin >> *start;
start++;
}
start = num; /* reset the starting pointer */
while(start <= end) {
cout << *start << ‘ ‘;
start++;
}

return 0;
}

listing 28
int *pi[10];

listing 29
int var;

pi[2] = &var;

listing 30
*pi[2]

listing 31
char *fortunes[] = {
«Soon, you will come into some money.\n»,
«A new love will enter your life.\n»,
«You will live long and prosper.\n»,
«Now is a good time to invest for the future.\n»,
«A close friend will ask for a favor.\n»
};

listing 32
cout << fortunes[1];

listing 33
#include <iostream>
#include <cstdlib>
#include <conio.h>
using namespace std;

char *fortunes[] = {
«Soon, you will come into some money.\n»,
«A new love will enter your life.\n»,
«You will live long and prosper.\n»,
«Now is a good time to invest for the future.\n»,
«A close friend will ask for a favor.\n»
};

int main()
{
int chance;

cout << «To see your fortune, press a key: «;

// randomize the random number generator
while(!kbhit()) rand();

cout << ‘\n’;

chance = rand();
chance = chance % 5;
cout << fortunes[chance];

return 0;
}

listing 34
// A simple C++ keyword synopsis program.

#include <iostream>
#include <cstring>
using namespace std;

char *keyword[][2] = {
«for», «for(initialization; condition; increment)»,
«if», «if(condition) … else …»,
«switch», «switch(value) { case-list }»,
«while», «while(condition) …»,
// add the rest of the C++ keywords here
«», «» // terminate the list with nulls
};

int main()
{
char str[80];
int i;

cout << «Enter keyword: «;
cin >> str;

// display syntax
for(i=0; *keyword[i][0]; i++)
if(!strcmp(keyword[i][0], str))
cout << keyword[i][1];

return 0;
}

listing 35
float *p = 0; // p is now a null pointer

listing 36
if(p) // succeeds if p is not null

if(!p) // succeeds if p is null

listing 37
int **balance;

listing 38
// Multiple indirection.
#include <iostream>
using namespace std;

int main()
{
int x, *p, **q;

x = 10;
p = &x;
q = &p;

cout << **q; // prints the value of x

return 0;
}

listing 39
// This program is wrong.
int main(){
int x, *p;

x = 10;
*p = x; // where does p point?

return 0;
}

listing 40
char s[80];
char y[80];
char *p1, *p2;

p1 = s;
p2 = y;
if(p1 < p2) . . .

listing 41
int first[10];
int second[10];

int *p, t;

p = first;
for(t=0; t<20; ++t) {
*p = t;
p++;
}

listing 42
// This program is wrong.

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

int main()
{
char s[80];
char *p1;

p1 = s;

do {
cout << «Enter a string: «;
gets(p1); // read a string
// print the ASCII values of each character
while(*p1) cout << (int) *p1++ << ‘ ‘;
cout << ‘\n’;
} while(strcmp(s, «done»));

return 0;
}

listing 43
// This program is correct.

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

int main()
{
char s[80];
char *p1;

do {
p1 = s; // reset p1 each time through the loop

cout << «Enter a string: «;
gets(p1); // read a string
// print the ASCII values of each character
while(*p1) cout << (int) *p1++ << ‘ ‘;
cout << ‘\n’;
} while(strcmp(s, «done»));

return 0;
}



listing 1
#include <iostream>
using namespace std;

void f1();

int main()
{
char str[]=»this is str in main()»;

cout << str << ‘\n’;
f1();
cout << str << ‘\n’;

return 0;
}

void f1()
{
char str[80];

cout << «Enter something: «;
cin >> str;
cout << str << ‘\n’;
}

listing 2
auto char ch;

listing 3
/* This program illustrates how variables can be
local to a block.
*/

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
int choice;

cout << «(1) add numbers or «;
cout << «(2) concatenate strings?: «;

cin >> choice;
if(choice == 1) {
int a, b; /* activate two integer vars */
cout << «Enter two numbers: «;
cin >> a >> b;
cout << «Sum is » << a+b << ‘\n’;
}
else {
char s1[80], s2[80]; /* activate two strings */
cout << «Enter two strings: «;
cin >> s1;
cin >> s2;
strcat(s1, s2);
cout << «Concatenation is » << s1 << ‘\n’;
}

return 0;
}

listing 4
/* This program is incorrect. */

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
int choice;

cout << «(1) add numbers or «;
cout << «(2) concatenate strings?: «;

cin >> choice;
if(choice == 1) {
int a, b; /* activate two integer vars */
cout << «Enter two numbers: «;
cin >> a >> b;
cout << «Sum is » << a+b << ‘\n’;
}
else {
char s1[80], s2[80]; /* activate two strings */
cout << «Enter two strings: «;
cin >> s1;
cin >> s2;
strcat(s1, s2);
cout << «Concatenation is » << s1 << ‘\n’;
}

a = 10; // *** Error *** — a not known here!

return 0;
}

listing 5
#include <iostream>
using namespace std;

int main()
{
int i, j;

i = 10;
j = 100;

if(j > 0) {
int i; // this i is separate from outer i

i = j / 2;
cout << «inner i: » << i << ‘\n’;
}

cout << «outer i: » << i << ‘\n’;

return 0;
}

listing 6
#include <iostream>
using namespace std;

int main()
{
cout << «Enter a number: «;
int a; // declare one variable
cin >> a;

cout << «Enter a second number: «;
int b; // declare another variable
cin >> b;

cout << «Product: » << a*b << ‘\n’;

return 0;
}

listing 7
#include <iostream>
using namespace std;

int main()
{
// i is local to for
for(int i = 0; i<10; i++) {
cout << i << » «;
cout << «squared is » << i * i << «\n»;
}

// i = 10; // *** Error *** — i not known here!

return 0;
}

listing 8
if(int x = 20) {
cout << «This is x: «;
cout << x;
}

listing 9
// A simple addition drill program.

#include <iostream>
#include <cstdlib>
using namespace std;

void drill();

int count; // count and num_right are global
int num_right;

int main()
{
cout << «How many practice problems: «;
cin >> count;

num_right = 0;
do {
drill();
count—;
} while(count);
cout << «You got » << num_right << » right.\n»;

return 0;
}

void drill()
{
int count; /* This count is local and unrelated to
the global one.
*/
int a, b, ans;

// Generate two numbers between 0 and 99.
a = rand() % 100;
b = rand() % 100;

// The user gets three tries to get it right.
for(count=0; count<3; count++) {
cout << «What is » << a << » + » << b << «? «;
cin >> ans;
if(ans==a+b) {
cout << «Right\n»;
num_right++;
return;
}
}
cout << «You’ve used up all your tries.\n»;
cout << «The answer is » << a+b << ‘\n’;
}

listing 10
// Pass a pointer to a function.
#include <iostream>
using namespace std;

void f(int *j);

int main()
{
int i;
int *p;

p = &i; // p now points to i

f(p);

cout << i; // i is now 100

return 0;
}

void f(int *j)
{
*j = 100; // var pointed to by j is assigned 100
}

listing 11
// Pass a pointer to a function — revised version.
#include <iostream>
using namespace std;

void f(int *j);

int main()
{
int i;

f(&i);

cout << i;

return 0;
}

void f(int *j)
{
*j = 100; // var pointed to by j is assigned 100
}

listing 12
#include <iostream>
using namespace std;

void display(int num[10]);

int main()
{
int t[10],i;

for(i=0; i<10; ++i) t[i]=i;

display(t); // pass array t to a function

return 0;
}

// Print some numbers.
void display(int num[10])
{
int i;

for(i=0; i<10; i++) cout << num[i] << ‘ ‘;
}

listing 13
void display(int num[])
{
int i;

for(i=0; i<10; i++) cout << num[i] << ‘ ‘;
}

listing 14
void display(int *num)
{
int i;

for(i=0; i<10; i++) cout << num[i] << ‘ ‘;
}

listing 15
#include <iostream>
using namespace std;

void display(int num);

int main()
{
int t[10],i;

for(i=0; i<10; ++i) t[i]=i;
for(i=0; i<10; i++) display(t[i]);

return 0;
}

// Print some numbers.
void display(int num)
{
cout << num << ‘ ‘;
}

listing 16
#include <iostream>
using namespace std;

void cube(int *n, int num);

int main()
{
int i, nums[10];

for(i=0; i<10; i++) nums[i] = i+1;
cout << «Original contents: «;
for(i=0; i<10; i++) cout << nums[i] << ‘ ‘;
cout << ‘\n’;

cube(nums, 10); // compute cubes

cout << «Altered contents: «;
for(i=0; i<10; i++) cout << nums[i] << ‘ ‘;

return 0;
}

void cube(int *n, int num)
{
while(num) {
*n = *n * *n * *n;
num—;
n++;
}
}

listing 17
// Pass a string to a function.
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;

void stringupper(char *str);

int main()
{
char str[80];

strcpy(str, «this is a test»);

stringupper(str);
cout << str; // display uppercase string
return 0;
}

void stringupper(char *str)
{
while(*str) {
*str = toupper(*str); // uppercase one char
str++; // move on to next char
}
}

listing 18
// A custom version of strlen().
#include <iostream>
using namespace std;

int mystrlen(char *str);

int main()
{
cout << «Length of Hello There is: «;
cout << mystrlen(«Hello There»);

return 0;
}

// A custom version of strlen().
int mystrlen(char *str)
{
int i;

for(i=0; str[i]; i++) ; // find the end of the string

return i;
}

listing 19
#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
if(argc!=2) {
cout << «You forgot to type your name.\n»;
return 1;
}
cout << «Hello » << argv[1] << ‘\n’;

return 0;
}

listing 20
/* The program prints all command line arguments it is
called with one character at a time. */
#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
int t, i;

for(t=0; t<argc; ++t) {
i = 0;
while(argv[t][i]) {
cout << argv[t][i];
++i;
}
cout << ‘ ‘;
}

return 0;
}

listing 21
/* This program displays the sum of the two numeric
command line arguments.
*/

#include <iostream>
#include <cstdlib>
using namespace std;

int main(int argc, char *argv[])
{

double a, b;

if(argc!=3) {
cout << «Usage: add num num\n»;
return 1;
}

a = atof(argv[1]);
b = atof(argv[2]);

cout << a + b;

return 0;
}

listing 22
// Demonstrate atoi(), atol(), and atof().
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
int i;
long j;
double k;

i = atoi(«100»);
j = atol(«100000»);
k = atof(«-0.123»);

cout << i << ‘ ‘ << j << ‘ ‘ << k;
cout << ‘\n’;

return 0;
}

listing 23
void power(int base, int exp)
{
int i;

if(exp<0) return; /* Can’t do negative exponents,
so return to calling routine
and bypass the rest of the
function. */

i = 1;

for( ; exp; exp—) i = base * i;
cout << «The answer is: » << i;
}

listing 24
void f()
{
// …

switch(c) {
case ‘a’: return;
case ‘b’: // …
case ‘c’: return;
}
if(count<100) return;
// …
}

listing 25
x = power(y);

if(max(x, y)) > 100) cout << «greater»;

switch(abs(x)) {

listing 26
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
int i;

i = abs(-10); // line 1
cout << abs(-23); // line 2
abs(100); // line 3

return 0;
}

listing 27
#include <iostream>
using namespace std;

int find_substr(char *sub, char *str);

int main()
{
int index;

index = find_substr(«three», «one two three four»);

cout << «Index of three is » << index; // index is 8

return 0;
}

// Return index of substring or -1 if not found.
int find_substr(char *sub, char *str)
{
int t;
char *p, *p2;

for(t=0; str[t]; t++) {
p = &str[t]; // reset pointers
p2 = sub;
while(*p2 && *p2==*p) { // check for substring
p++;
p2++;
}

/* If at end of p2 (i.e., substring), then
a match has been found. */
if(!*p2) return t; // return index of match
}
return -1; // no match found
}

listing 28
#include <iostream>
using namespace std;

void print_vertical(char *str);

int main(int argc, char *argv[])
{
if(argc==2) print_vertical(argv[1]);

return 0;
}

void print_vertical(char *str)
{
while(*str)
cout << *str++ << ‘\n’;
}

listing 29
x = print_vertical(«hello»); // Error

listing 30
// Rework find_substr() to return a pointer.
#include <iostream>
using namespace std;

char *find_substr(char *sub, char *str);

int main()
{
char *substr;

substr = find_substr(«three», «one two three four»);

cout << «substring found: » << substr;

return 0;
}

// Return pointer to substring or null if not found.
char *find_substr(char *sub, char *str)
{
int t;
char *p, *p2, *start;

for(t=0; str[t]; t++) {
p = &str[t]; // reset pointers
start = p;
p2 = sub;
while(*p2 && *p2==*p) { // check for substring
p++;
p2++;
}

/* If at end of p2 (i.e., substring), then
a match has been found. */
if(!*p2)
return start; // return pointer to beginning of substring
}
return 0; // no match found
}

listing 31
/* This program uses a function prototype to
enforce strong type checking.
*/

void sqr_it(int *i); // prototype

int main()
{
int x;

x = 10;
sqr_it(x); // *** Error *** — type mismatch!

return 0;
}

void sqr_it(int *i)
{
*i = *i * *i;
}

listing 32
float f(int a, int b, char ch)
{ …

listing 33
float f(a, b, ch)
int a, b;
char ch;
{ …

listing 34
#include <iostream>
using namespace std;

int factr(int n);
int fact(int n);

int main()
{
// use recursive version
cout << «4 factorial is » << factr(4);
cout << ‘\n’;

// use iterative version
cout << «4 factorial is » << fact(4);
cout << ‘\n’;

return 0;
}

// Recursive version.
int factr(int n)
{
int answer;

if(n==1) return(1);
answer = factr(n-1)*n;
return(answer);
}

// Iterative version.
int fact(int n)
{
int t, answer;

answer = 1;
for(t=1; t<=n; t++) answer = answer*(t);
return(answer);
}

listing 35
// Print a string backwards using recursion.
#include <iostream>
using namespace std;

void reverse(char *s);

int main()
{
char str[] = «this is a test»;

reverse(str);

return 0;
}

// Print string backwards.
void reverse(char *s)
{
if(*s)
reverse(s+1);
else
return;

cout << *s;
}



listing 1
#include <iostream>
using namespace std;

void f1();

int main()
{
char str[]=»this is str in main()»;

cout << str << ‘\n’;
f1();
cout << str << ‘\n’;

return 0;
}

void f1()
{
char str[80];

cout << «Enter something: «;
cin >> str;
cout << str << ‘\n’;
}

listing 2
auto char ch;

listing 3
/* This program illustrates how variables can be
local to a block.
*/

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
int choice;

cout << «(1) add numbers or «;
cout << «(2) concatenate strings?: «;

cin >> choice;
if(choice == 1) {
int a, b; /* activate two integer vars */
cout << «Enter two numbers: «;
cin >> a >> b;
cout << «Sum is » << a+b << ‘\n’;
}
else {
char s1[80], s2[80]; /* activate two strings */
cout << «Enter two strings: «;
cin >> s1;
cin >> s2;
strcat(s1, s2);
cout << «Concatenation is » << s1 << ‘\n’;
}

return 0;
}

listing 4
/* This program is incorrect. */

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
int choice;

cout << «(1) add numbers or «;
cout << «(2) concatenate strings?: «;

cin >> choice;
if(choice == 1) {
int a, b; /* activate two integer vars */
cout << «Enter two numbers: «;
cin >> a >> b;
cout << «Sum is » << a+b << ‘\n’;
}
else {
char s1[80], s2[80]; /* activate two strings */
cout << «Enter two strings: «;
cin >> s1;
cin >> s2;
strcat(s1, s2);
cout << «Concatenation is » << s1 << ‘\n’;
}

a = 10; // *** Error *** — a not known here!

return 0;
}

listing 5
#include <iostream>
using namespace std;

int main()
{
int i, j;

i = 10;
j = 100;

if(j > 0) {
int i; // this i is separate from outer i

i = j / 2;
cout << «inner i: » << i << ‘\n’;
}

cout << «outer i: » << i << ‘\n’;

return 0;
}

listing 6
#include <iostream>
using namespace std;

int main()
{
cout << «Enter a number: «;
int a; // declare one variable
cin >> a;

cout << «Enter a second number: «;
int b; // declare another variable
cin >> b;

cout << «Product: » << a*b << ‘\n’;

return 0;
}

listing 7
#include <iostream>
using namespace std;

int main()
{
// i is local to for
for(int i = 0; i<10; i++) {
cout << i << » «;
cout << «squared is » << i * i << «\n»;
}

// i = 10; // *** Error *** — i not known here!

return 0;
}

listing 8
if(int x = 20) {
cout << «This is x: «;
cout << x;
}

listing 9
// A simple addition drill program.

#include <iostream>
#include <cstdlib>
using namespace std;

void drill();

int count; // count and num_right are global
int num_right;

int main()
{
cout << «How many practice problems: «;
cin >> count;

num_right = 0;
do {
drill();
count—;
} while(count);
cout << «You got » << num_right << » right.\n»;

return 0;
}

void drill()
{
int count; /* This count is local and unrelated to
the global one.
*/
int a, b, ans;

// Generate two numbers between 0 and 99.
a = rand() % 100;
b = rand() % 100;

// The user gets three tries to get it right.
for(count=0; count<3; count++) {
cout << «What is » << a << » + » << b << «? «;
cin >> ans;
if(ans==a+b) {
cout << «Right\n»;
num_right++;
return;
}
}
cout << «You’ve used up all your tries.\n»;
cout << «The answer is » << a+b << ‘\n’;
}

listing 10
// Pass a pointer to a function.
#include <iostream>
using namespace std;

void f(int *j);

int main()
{
int i;
int *p;

p = &i; // p now points to i

f(p);

cout << i; // i is now 100

return 0;
}

void f(int *j)
{
*j = 100; // var pointed to by j is assigned 100
}

listing 11
// Pass a pointer to a function — revised version.
#include <iostream>
using namespace std;

void f(int *j);

int main()
{
int i;

f(&i);

cout << i;

return 0;
}

void f(int *j)
{
*j = 100; // var pointed to by j is assigned 100
}

listing 12
#include <iostream>
using namespace std;

void display(int num[10]);

int main()
{
int t[10],i;

for(i=0; i<10; ++i) t[i]=i;

display(t); // pass array t to a function

return 0;
}

// Print some numbers.
void display(int num[10])
{
int i;

for(i=0; i<10; i++) cout << num[i] << ‘ ‘;
}

listing 13
void display(int num[])
{
int i;

for(i=0; i<10; i++) cout << num[i] << ‘ ‘;
}

listing 14
void display(int *num)
{
int i;

for(i=0; i<10; i++) cout << num[i] << ‘ ‘;
}

listing 15
#include <iostream>
using namespace std;

void display(int num);

int main()
{
int t[10],i;

for(i=0; i<10; ++i) t[i]=i;
for(i=0; i<10; i++) display(t[i]);

return 0;
}

// Print some numbers.
void display(int num)
{
cout << num << ‘ ‘;
}

listing 16
#include <iostream>
using namespace std;

void cube(int *n, int num);

int main()
{
int i, nums[10];

for(i=0; i<10; i++) nums[i] = i+1;
cout << «Original contents: «;
for(i=0; i<10; i++) cout << nums[i] << ‘ ‘;
cout << ‘\n’;

cube(nums, 10); // compute cubes

cout << «Altered contents: «;
for(i=0; i<10; i++) cout << nums[i] << ‘ ‘;

return 0;
}

void cube(int *n, int num)
{
while(num) {
*n = *n * *n * *n;
num—;
n++;
}
}

listing 17
// Pass a string to a function.
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;

void stringupper(char *str);

int main()
{
char str[80];

strcpy(str, «this is a test»);

stringupper(str);
cout << str; // display uppercase string
return 0;
}

void stringupper(char *str)
{
while(*str) {
*str = toupper(*str); // uppercase one char
str++; // move on to next char
}
}

listing 18
// A custom version of strlen().
#include <iostream>
using namespace std;

int mystrlen(char *str);

int main()
{
cout << «Length of Hello There is: «;
cout << mystrlen(«Hello There»);

return 0;
}

// A custom version of strlen().
int mystrlen(char *str)
{
int i;

for(i=0; str[i]; i++) ; // find the end of the string

return i;
}

listing 19
#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
if(argc!=2) {
cout << «You forgot to type your name.\n»;
return 1;
}
cout << «Hello » << argv[1] << ‘\n’;

return 0;
}

listing 20
/* The program prints all command line arguments it is
called with one character at a time. */
#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
int t, i;

for(t=0; t<argc; ++t) {
i = 0;
while(argv[t][i]) {
cout << argv[t][i];
++i;
}
cout << ‘ ‘;
}

return 0;
}

listing 21
/* This program displays the sum of the two numeric
command line arguments.
*/

#include <iostream>
#include <cstdlib>
using namespace std;

int main(int argc, char *argv[])
{

double a, b;

if(argc!=3) {
cout << «Usage: add num num\n»;
return 1;
}

a = atof(argv[1]);
b = atof(argv[2]);

cout << a + b;

return 0;
}

listing 22
// Demonstrate atoi(), atol(), and atof().
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
int i;
long j;
double k;

i = atoi(«100»);
j = atol(«100000»);
k = atof(«-0.123»);

cout << i << ‘ ‘ << j << ‘ ‘ << k;
cout << ‘\n’;

return 0;
}

listing 23
void power(int base, int exp)
{
int i;

if(exp<0) return; /* Can’t do negative exponents,
so return to calling routine
and bypass the rest of the
function. */

i = 1;

for( ; exp; exp—) i = base * i;
cout << «The answer is: » << i;
}

listing 24
void f()
{
// …

switch(c) {
case ‘a’: return;
case ‘b’: // …
case ‘c’: return;
}
if(count<100) return;
// …
}

listing 25
x = power(y);

if(max(x, y)) > 100) cout << «greater»;

switch(abs(x)) {

listing 26
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
int i;

i = abs(-10); // line 1
cout << abs(-23); // line 2
abs(100); // line 3

return 0;
}

listing 27
#include <iostream>
using namespace std;

int find_substr(char *sub, char *str);

int main()
{
int index;

index = find_substr(«three», «one two three four»);

cout << «Index of three is » << index; // index is 8

return 0;
}

// Return index of substring or -1 if not found.
int find_substr(char *sub, char *str)
{
int t;
char *p, *p2;

for(t=0; str[t]; t++) {
p = &str[t]; // reset pointers
p2 = sub;
while(*p2 && *p2==*p) { // check for substring
p++;
p2++;
}

/* If at end of p2 (i.e., substring), then
a match has been found. */
if(!*p2) return t; // return index of match
}
return -1; // no match found
}

listing 28
#include <iostream>
using namespace std;

void print_vertical(char *str);

int main(int argc, char *argv[])
{
if(argc==2) print_vertical(argv[1]);

return 0;
}

void print_vertical(char *str)
{
while(*str)
cout << *str++ << ‘\n’;
}

listing 29
x = print_vertical(«hello»); // Error

listing 30
// Rework find_substr() to return a pointer.
#include <iostream>
using namespace std;

char *find_substr(char *sub, char *str);

int main()
{
char *substr;

substr = find_substr(«three», «one two three four»);

cout << «substring found: » << substr;

return 0;
}

// Return pointer to substring or null if not found.
char *find_substr(char *sub, char *str)
{
int t;
char *p, *p2, *start;

for(t=0; str[t]; t++) {
p = &str[t]; // reset pointers
start = p;
p2 = sub;
while(*p2 && *p2==*p) { // check for substring
p++;
p2++;
}

/* If at end of p2 (i.e., substring), then
a match has been found. */
if(!*p2)
return start; // return pointer to beginning of substring
}
return 0; // no match found
}

listing 31
/* This program uses a function prototype to
enforce strong type checking.
*/

void sqr_it(int *i); // prototype

int main()
{
int x;

x = 10;
sqr_it(x); // *** Error *** — type mismatch!

return 0;
}

void sqr_it(int *i)
{
*i = *i * *i;
}

listing 32
float f(int a, int b, char ch)
{ …

listing 33
float f(a, b, ch)
int a, b;
char ch;
{ …

listing 34
#include <iostream>
using namespace std;

int factr(int n);
int fact(int n);

int main()
{
// use recursive version
cout << «4 factorial is » << factr(4);
cout << ‘\n’;

// use iterative version
cout << «4 factorial is » << fact(4);
cout << ‘\n’;

return 0;
}

// Recursive version.
int factr(int n)
{
int answer;

if(n==1) return(1);
answer = factr(n-1)*n;
return(answer);
}

// Iterative version.
int fact(int n)
{
int t, answer;

answer = 1;
for(t=1; t<=n; t++) answer = answer*(t);
return(answer);
}

listing 35
// Print a string backwards using recursion.
#include <iostream>
using namespace std;

void reverse(char *s);

int main()
{
char str[] = «this is a test»;

reverse(str);

return 0;
}

// Print string backwards.
void reverse(char *s)
{
if(*s)
reverse(s+1);
else
return;

cout << *s;
}



listing 1
#include <iostream>
using namespace std;

int sqr_it(int x);

int main()
{
int t=10;

cout << sqr_it(t) << ‘ ‘ << t;

return 0;
}

int sqr_it(int x)
{
x = x*x;
return x;
}

listing 2
void swap(int *x, int *y)
{
int temp;

temp = *x; // save the value at address x
*x = *y; // put y into x
*y = temp; // put x into y
}

listing 3
#include <iostream>
using namespace std;

// Declare swap() using pointers.
void swap(int *x, int *y);

int main()
{
int i, j;

i = 10;
j = 20;

cout << «initial values of i and j: «;
cout << i << ‘ ‘ << j << ‘\n’;
swap(&j, &i); // call swap() with addresses of i and j
cout << «swapped values of i and j: «;
cout << i << ‘ ‘ << j << ‘\n’;

return 0;
}

// Exchange arguments.
void swap(int *x, int *y)
{
int temp;

temp = *x; // save the value at address x
*x = *y; // put y into x
*y = temp; // put x into y
}

listing 4
// Using a reference parameter.
#include <iostream>
using namespace std;

void f(int &i);

int main()
{
int val = 1;

cout << «Old value for val: » << val << ‘\n’;

f(val); // pass address of val to f()

cout << «New value for val: » << val << ‘\n’;

return 0;
}

void f(int &i)
{
i = 10; // this modifies calling argument
}

listing 5
void f(int &i)
{
i = 10; // this modifies calling argument
}

listing 6
i = 10;

listing 7
f(val); // pass address of val to f()

listing 8
#include <iostream>
using namespace std;

// Declare swap() using reference parameters.
void swap(int &x, int &y);

int main()
{
int i, j;

i = 10;
j = 20;

cout << «initial values of i and j: «;
cout << i << ‘ ‘ << j << ‘\n’;
swap(j, i);
cout << «swapped values of i and j: «;
cout << i << ‘ ‘ << j << ‘\n’;

return 0;
}

/* Here, swap() is defined as using call-by-reference,
not call-by-value. Thus, it can exchange the two
arguments it is called with.
*/
void swap(int &x, int &y)
{
int temp;

temp = x; // save the value at address x
x = y; // put y into x
y = temp; // put x into y
}

listing 9
void swap(int& x, int& y);

listing 10
float* p;

listing 11
int* a, b;

listing 12
// Returning a reference.
#include <iostream>
using namespace std;

double &f();

double val = 100.0;

int main()
{
double newval;

cout << f() << ‘\n’; // display val’s value

newval = f(); // assign value of val to newval
cout << newval << ‘\n’; // display newval’s value

f() = 99.1; // change val’s value
cout << f() << ‘\n’; // display val’s new value

return 0;
}

double &f()
{
return val; // return reference to val
}

listing 13
cout << f() << ‘\n’; // display val’s value

listing 14
return val; // return reference to val

listing 15
newval = f(); // assign value of val to newval

listing 16
f() = 99.1; // change val’s value

listing 17
#include <iostream>
using namespace std;

double &change_it(int i); // return a reference

double vals[] = {1.1, 2.2, 3.3, 4.4, 5.5};

int main()
{
int i;

cout << «Here are the original values: «;
for(i=0; i<5; i++)
cout << vals[i] << ‘ ‘;
cout << ‘\n’;

change_it(1) = 5298.23; // change 2nd element
change_it(3) = -98.8; // change 4th element

cout << «Here are the changed values: «;
for(i=0; i<5; i++)
cout << vals[i] << ‘ ‘;
cout << ‘\n’;

return 0;
}

double &change_it(int i)
{
return vals[i]; // return a reference to the ith element
}

listing 18
// Error, cannot return reference to local var.
int &f()
{
int i=10;
return i;
}

listing 19
#include <iostream>
using namespace std;

int &put(int i); // put value into the array
int get(int i); // obtain a value from the array

int vals[10];
int error = -1;

int main()
{
put(0) = 10; // put values into the array
put(1) = 20;
put(9) = 30;

cout << get(0) << ‘ ‘;
cout << get(1) << ‘ ‘;
cout << get(9) << ‘ ‘;

// now, intentionally generate an error
put(12) = 1; // Out of Bounds

return 0;
}

// Put a value into the array.
int &put(int i)
{
if(i>=0 && i<10)
return vals[i]; // return a reference to the ith element
else {
cout << «Bounds Error!\n»;
return error; // return a reference to error
}
}

// Get a value from the array.
int get(int i)
{
if(i>=0 && i<10)
return vals[i]; // return the value of the ith element
else {
cout << «Bounds Error!\n»;
return error; // return an error
}
}

listing 20
#include <iostream>
using namespace std;

int main()
{
int j, k;
int &i = j; // independent reference

j = 10;

cout << j << » » << i; // outputs 10 10

k = 121;
i = k; // copies k’s value into j
// not k’s address

cout << «\n» << j; // outputs 121

return 0;
}

listing 21
// Overload a function three times.
#include <iostream>
using namespace std;

void f(int i); // integer parameter
void f(int i, int j); // two integer parameters
void f(double k); // one double parameter

int main()
{
f(10); // call f(int)

f(10, 20); // call f(int, int)

f(12.23); // call f(double)

return 0;
}

void f(int i)
{
cout << «In f(int), i is » << i << ‘\n’;
}

void f(int i, int j)
{
cout << «In f(int, int), i is » << i;
cout << «, j is » << j << ‘\n’;
}

void f(double k)
{
cout << «In f(double), k is » << k << ‘\n’;
}

listing 22
// Create an overloaded abs function.
#include <iostream>
using namespace std;

// myabs() is overloaded three ways.
int myabs(int i);
double myabs(double d);
long myabs(long l);

int main()
{
cout << myabs(-10) << «\n»;

cout << myabs(-11.0) << «\n»;

cout << myabs(-9L) << «\n»;

return 0;
}

int myabs(int i)
{
cout << «Using integer myabs(): «;

if(i<0) return -i;
else return i;
}

double myabs(double d)
{
cout << «Using double myabs(): «;

if(d<0.0) return -d;
else return d;
}

long myabs(long l)
{
cout << «Using long myabs(): «;

if(l<0) return -l;
else return l;
}

listing 23
overload myfunc;

listing 24
void myfunc(double num = 0.0, char ch = ‘X’)
{
.
.
.
}

listing 25
myfunc(198.234, ‘A’); // pass explicit values

myfunc(10.1); // pass num a value, let ch default

myfunc(); // let both num and ch default

listing 26
#include <iostream>
using namespace std;

void clrscr(int size=25);

int main()
{
int i;

for(i=0; i<30; i++ ) cout << i << ‘\n’;
clrscr(); // clears 25 lines

for(i=0; i<30; i++ ) cout << i << ‘\n’;
clrscr(10); // clears 10 lines

return 0;
}

void clrscr(int size)
{
for(; size; size—) cout << ‘\n’;
}

listing 27
// wrong!
void f(int a = 1, int b);

listing 28
int myfunc(float f, char *str, int i=10, int j);

listing 29
void mystrcat(char *s1, char *s2, int len);
void mystrcat(char *s1, char *s2);

listing 30
// A customized version of strcat().
#include <iostream>
#include <cstring>
using namespace std;

void mystrcat(char *s1, char *s2, int len = -1);

int main()
{
char str1[80] = «This is a test»;
char str2[80] = «0123456789»;

mystrcat(str1, str2, 5); // concatenate 5 chars
cout << str1 << ‘\n’;

strcpy(str1, «this is a test»); // reset str1

mystrcat(str1, str2); // concatenate entire string
cout << str1 << ‘\n’;

return 0;
}

// A custom version of strcat().
void mystrcat(char *s1, char *s2, int len)
{
// find end of s1
while(*s1) s1++;

if(len == -1) len = strlen(s2);

while(*s2 && len) {
*s1 = *s2; // copy chars
s1++;
s2++;
len—;
}

*s1 = ‘\0’; // null terminate s1
}

listing 31
int myfunc(double d);
.
.
.
cout << myfunc(‘c’); // not an error, conversion applied

listing 32
// Overloading ambiguity
#include <iostream>
using namespace std;

float myfunc(float i);
double myfunc(double i);

int main()
{
// unambiguous, calls myfunc(double)
cout << myfunc(10.1) << » «;

// ambiguous
cout << myfunc(10);

return 0;
}

float myfunc(float i)
{
return i;
}

double myfunc(double i)
{
return -i;
}

listing 33
#include <iostream>
using namespace std;

char myfunc(unsigned char ch);
char myfunc(char ch);

int main()
{
cout << myfunc(‘c’); // this calls myfunc(char)
cout << myfunc(88) << » «; // ambiguous

return 0;
}

char myfunc(unsigned char ch)
{
return ch-1;
}
char myfunc(char ch)
{
return ch+1;
}

listing 34
#include <iostream>
using namespace std;

int myfunc(int i);
int myfunc(int i, int j=1);

int main()
{
cout << myfunc(4, 5) << » «; // unambiguous
cout << myfunc(10); // ambiguous

return 0;
}

int myfunc(int i)
{
return i;
}

int myfunc(int i, int j)
{
return i*j;
}



listing 1
const double version = 3.2;

listing 2
#include <iostream>
using namespace std;

void code(const char *str);

int main()
{
code(«this is a test»);

return 0;
}

/* Use of const ensures str cannot modify the
argument to which it points. */
void code(const char *str)
{
while(*str) {
cout << (char) (*str+1);
str++;
}
}

listing 3
// This is wrong.
void code(const char *str)
{
while(*str) {
*str = *str + 1; // Error, can’t modify the argument
cout << (char) *str;
str++;
}
}

listing 4
// const references cannot be modified.
#include <iostream>
using namespace std;

void f(const int &i);

int main()
{
int k = 10;

f(k);
return 0;
}

// Use a const reference parameter.
void f(const int &i)
{
i = 100; // Error, can’t modify a const reference.
cout << i;
}

listing 5
#include <iostream>
using namespace std;

const int size = 10;

int main()
{
int A1[size], A2[size], A3[size];

// …
}

listing 6
int clock, timer;
// …
timer = clock; // line A
// … do something
cout << «Elapsed type is » << clock-timer; // line B

listing 7
volatile int clock;

listing 8
const volatile unsigned char *port;

listing 9
#include <iostream>
using namespace std;

int main()
{
extern int first, last; // use global vars

cout << first << » » << last << «\n»;

return 0;
}

// global definition of first and last
int first = 10, last = 20;

listing 10
static int count;

listing 11
static int count = 200;

listing 12
/* Compute a running average of numbers entered by
the user.
*/
#include <iostream>
using namespace std;

int r_avg(int i);

int main()
{
int num;

do {
cout << «Enter numbers (-1 to quit): «;
cin >> num;
if(num != -1) cout << «Running average is: » << r_avg(num);
cout << ‘\n’;
} while(num > -1);

return 0;
}

// Compute a running average.
int r_avg(int i)
{
static int sum=0, count=0;

sum = sum + i;

count++;

return sum / count;
}

listing 13
// ———————- First File ———————-

#include <iostream>
using namespace std;

int r_avg(int i);
void reset();

int main()
{
int num;

do {
cout << «Enter numbers (-1 to quit, -2 to reset): «;
cin >> num;
if(num==-2) {
reset();
continue;
}
cout << «Running average is: » << r_avg(num);
cout << ‘\n’;
} while(num != -1);

return 0;
}

// ———————- Second File ———————-

static int sum=0, count=0;

int r_avg(int i)
{
sum = sum + i;

count++;

return sum / count;
}

void reset()
{
sum = 0;
count = 0;
}

listing 14
int signed_pwr(register int m, register int e)
{
register int temp;
int sign;

if(m < 0) sign = -1;
else sign = 1;

temp = 1;
for( ;e ;e—) temp = temp * m;

return temp * sign;
}

listing 15
/* This program shows the difference a register variable
can make to the speed of program execution.
*/

#include <iostream>
#include <ctime>
using namespace std;

unsigned int i; // non-register
unsigned int delay;

int main()
{
register unsigned int j;
long start, end;

start = clock();
for(delay=0; delay<50; delay++)
for(i=0; i<6400000; i++);
end = clock();
cout << «Number of clock ticks for non-register loop: «;
cout << end-start << ‘\n’;

start = clock();
for(delay=0; delay<50; delay++)
for(j=0; j<6400000; j++) ;
end = clock();
cout << «Number of clock ticks for register loop: «;
cout << end-start << ‘\n’;

return 0;
}

listing 16
enum apple {Jonathan, Golden_Del, Red_Del, Winesap,
Cortland, McIntosh} red, yellow;

listing 17
apple fruit;

listing 18
enum apple fruit;

listing 19
fruit = Winesap;
if(fruit==Red_Del) cout << «Red Delicious\n»;

listing 20
cout << Jonathan << ‘ ‘ << Cortland;

listing 21
fruit = 1; // Error

listing 22
fruit = (apple) 1; // now OK, but probably poor style

listing 23
enum apple {Jonathan, Golden_Del, Red_Del, Winesap=10,
Cortland, McIntosh};

listing 24
// This will not print «McIntosh» on the screen.
fruit = McIntosh;
cout << fruit;

listing 25
switch(fruit) {
case Jonathan: cout << «Jonathan»;
break;
case Golden_Del: cout << «Golden Delicious»;
break;
case Red_Del: cout << «Red Delicious»;
break;
case Winesap: cout << «Winesap»;
break;
case Cortland: cout << «Cortland»;
break;
case McIntosh: cout << «McIntosh»;
break;
}

listing 26
#include <iostream>
using namespace std;

enum apple {Jonathan, Golden_Del, Red_Del, Winesap,
Cortland, McIntosh};

// Array of strings that correspond to the apple enumeration.
char name[][20] = {
«Jonathan»,
«Golden Delicious»,
«Red Delicious»,
«Winesap»,
«Cortland»,
«McIntosh»
};

int main()
{
apple fruit;

fruit = Jonathan;
cout << name[fruit] << ‘\n’;

fruit = Winesap;
cout << name[fruit] << ‘\n’;

fruit = McIntosh;
cout << name[fruit] << ‘\n’;

return 0;
}

listing 27
typedef float balance;

listing 28
balance over_due;

listing 29
// Uppercase letters.
#include <iostream>
using namespace std;

int main()
{
char ch;

do {
cin >> ch;

// This statement turns off the 6th bit.
ch = ch & 223; // ch is now uppercase

cout << ch;
} while(ch!=’Q’);

return 0;
}

listing 30
if(status & 8) cout << «bit 4 is on»;

listing 31
// Display the bits within a byte.
void disp_binary(unsigned u)
{
register int t;

for(t=128; t>0; t = t/2)
if(u & t) cout << «1 «;
else cout << «0 «;
cout << «\n»;
}

listing 32
// Lowercase letters.
#include <iostream>
using namespace std;

int main()
{
char ch;

do {
cin >> ch;

/* This lowercases the letter by turning
on bit 6.
*/
ch = ch | 32;

cout << ch;
} while(ch != ‘q’);

return 0;
}

listing 33
#include <iostream>
using namespace std;

void disp_binary(unsigned u);

int main()
{
unsigned u;

cout << «Enter a number between 0 and 255: «;
cin >> u;

cout << «Here’s the number in binary: «;
disp_binary(u);

cout << «Here’s the complement of the number: «;
disp_binary(~u);

return 0;
}

// Display the bits within a byte.
void disp_binary(unsigned u)
{
register int t;

for(t=128; t>0; t = t/2)
if(u & t) cout << «1 «;
else cout << «0 «;
cout << «\n»;
}

listing 34
// Example of bitshifting.

#include <iostream>
using namespace std;

void disp_binary(unsigned u);

int main()
{
int i=1, t;

for(t=0; t<8; t++) {
disp_binary(i);
i = i << 1;
}

cout << «\n»;

for(t=0; t<8; t++) {
i = i >> 1;
disp_binary(i);
}

return 0;
}

// Display the bits within a byte.
void disp_binary(unsigned u)
{
register int t;

for(t=128; t>0; t=t/2)
if(u & t) cout << «1 «;
else cout << «0 «;
cout << «\n»;
}

listing 35
while(something) {
x = count > 0 ? 0 : 1;
// …
}

listing 36
while(something) {
if(count > 0) x = 0;
else x = 1;
// …
}

listing 37
/* This program uses the ? operator to prevent
a division by zero. */

#include <iostream>
using namespace std;

int div_zero();

int main()
{
int i, j, result;

cout << «Enter dividend and divisor: «;
cin >> i >> j;

// This statement prevents a divide by zero error.
result = j ? i/j : div_zero();

cout << «Result: » << result;

return 0;
}

int div_zero()
{
cout << «Cannot divide by zero.\n»;
return 0;
}

listing 38
x = x+10;

listing 39
x += 10;

listing 40
x = x-100;

listing 41
x -= 100;

listing 42
var = (count=19, incr=10, count+1);

listing 43
#include <iostream>
using namespace std;

int main()
{
int i, j;

j = 10;

i = (j++, j+100, 999+j);

cout << i;

return 0;
}

listing 44
count = incr = index = 10;

listing 45
// Demonstrate sizeof.
#include <iostream>
using namespace std;

int main()
{
char ch;
int i;

cout << sizeof ch << ‘ ‘; // size of char
cout << sizeof i << ‘ ‘; // size of int
cout << sizeof (float) << ‘ ‘; // size of float
cout << sizeof (double) << ‘ ‘; // size of double

return 0;
}

listing 46
int nums[4];

cout << sizeof nums; // displays 16

listing 47
#include <iostream>
using namespace std;

int main()
{
int *p;

p = new int; // allocate memory for int

*p = 20; // assign that memory the value 20
cout << *p; // prove that it works by displaying value

delete p; // free the memory

return 0;
}

listing 48
#include <iostream>
using namespace std;

int main()
{
int *p;

p = new int (99); // initialize with 99

cout << *p; // displays 99

delete p;

return 0;
}

listing 49
#include <iostream>
using namespace std;

int main()
{
double *p;
int i;

p = new double [10]; // get a 10-element array

// assign the values 100 through 109
for(i=0; i<10; i++) p[i] = 100.00 + i;

// display the contents of the array
for(i=0; i<10; i++) cout << p[i] << » «;

delete [] p; // delete the entire array

return 0;
}

listing 50
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
int *i;
double *j;

i = (int *) malloc(sizeof(int));
if(!i) {
cout << «Allocation Failure.\n»;
return 1;
}

j = (double *) malloc(sizeof(double));
if(!j) {
cout << «Allocation Failure.\n»;
return 1;
}

*i= 10;
*j = 100.123;

cout << *i << ‘ ‘ << *j;

// free the memory
free(i);
free(j);

return 0;
}



listing 1
struct inv_type {
char item[40]; // name of item
double cost; // cost
double retail; // retail price
int on_hand; // amount on hand
int lead_time; // number of days before resupply
};

listing 2
inv_type inv_var;

listing 3
struct inv_type {
char item[40]; // name of item
double cost; // cost
double retail; // retail price
int on_hand; // amount on hand
int lead_time; // number of days before resupply
} inv_varA, inv_varB, inv_varC;

listing 4
struct {
char item[40]; // name of item
double cost; // cost
double retail; // retail price
int on_hand; // amount on hand
int lead_time; // number of days before resupply
} temp;

listing 5
inv_var.cost = 10.39;

listing 6
cout << inv_var.cost;

listing 7
gets(inv_var.item);

listing 8
int t;

for(t=0; inv_var.item[t]; t++)
cout << inv_var.item[t];

listing 9
inv_type invtry[100];

listing 10
cout << invtry[2].on_hand;

listing 11
const int SIZE = 100;

struct inv_type {
char item[40]; // name of item
double cost; // cost
double retail; // retail price
int on_hand; // amount on hand
int lead_time; // number of days before resupply
} invtry[SIZE];

listing 12
// Initialize the inv_type_info array.
void init_list()
{
int t;

// a zero length name signifies empty
for(t=0; t<SIZE; t++) *invtry[t].item = ‘\0’;
}

listing 13
// Get a menu selection.
int menu()
{
char ch;

cout << ‘\n’;
do {
cout << «(E)nter\n»;
cout << «(D)isplay\n»;
cout << «(U)pdate\n»;
cout << «(Q)uit\n\n»;
cout << «choose one: «;
cin >> ch;
} while(!strchr(«eduq», tolower(ch)));
return tolower(ch);
}

listing 14
// Enter items into the list.
void enter()
{
int i;

// find the first free structure
for(i=0; i<SIZE; i++)
if(!*invtry[i].item) break;

// i will equal SIZE if the list is full
if(i==SIZE) {
cout << «List full.\n»;
return;
}

input(i);
}

// Input the information.
void input(int i)
{
// enter the information
cout << «Item: «;
cin >> invtry[i].item;

cout << «Cost: «;
cin >> invtry[i].cost;

cout << «Retail price: «;
cin >> invtry[i].retail;

cout << «On hand: «;
cin >> invtry[i].on_hand;

cout << «Lead time to resupply (in days): «;
cin >> invtry[i].lead_time;
}

listing 15
// Modify an existing item.
void update()
{
int i;
char name[80];

cout << «Enter item: «;
cin >> name;

for(i=0; i<SIZE; i++)
if(!strcmp(name, invtry[i].item)) break;

if(i==SIZE) {
cout << «Item not found.\n»;
return;
}

cout << «Enter new information.\n»;
input(i);
}

listing 16
// Display the list.
void display()
{
int t;

for(t=0; t<SIZE; t++) {
if(*invtry[t].item) {
cout << invtry[t].item << ‘\n’;
cout << «Cost: $» << invtry[t].cost;
cout << «\nRetail: $»;
cout << invtry[t].retail << ‘\n’;
cout << «On hand: » << invtry[t].on_hand;
cout << «\nResupply time: «;
cout << invtry[t].lead_time << » days\n\n»;
}
}
}

listing 17
/* A simple inventory program that uses an array
of structures. */

#include <iostream>
#include <cctype>
#include <cstring>
#include <cstdlib>
using namespace std;

const int SIZE = 100;

struct inv_type {
char item[40]; // name of item
double cost; // cost
double retail; // retail price
int on_hand; // amount on hand
int lead_time; // number of days before resupply
} invtry[SIZE];

void enter(), init_list(), display();
void update(), input(int i);
int menu();

int main()
{
char choice;

init_list();

for(;;) {
choice = menu();
switch(choice) {
case ‘e’: enter();
break;
case ‘d’: display();
break;
case ‘u’: update();
break;
case ‘q’: return 0;
}
}
}

// Initialize the inv_type_info array.
void init_list()
{
int t;

// a zero length name signifies empty
for(t=0; t<SIZE; t++) *invtry[t].item = ‘\0’;
}

// Get a menu selection.
int menu()
{
char ch;

cout << ‘\n’;
do {
cout << «(E)nter\n»;
cout << «(D)isplay\n»;
cout << «(U)pdate\n»;
cout << «(Q)uit\n\n»;
cout << «choose one: «;
cin >> ch;
} while(!strchr(«eduq», tolower(ch)));
return tolower(ch);
}

// Enter items into the list.
void enter()
{
int i;

// find the first free structure
for(i=0; i<SIZE; i++)
if(!*invtry[i].item) break;

// i will equal SIZE if the list is full
if(i==SIZE) {
cout << «List full.\n»;
return;
}

input(i);
}

// Input the information.
void input(int i)
{
// enter the information
cout << «Item: «;
cin >> invtry[i].item;

cout << «Cost: «;
cin >> invtry[i].cost;

cout << «Retail price: «;
cin >> invtry[i].retail;

cout << «On hand: «;
cin >> invtry[i].on_hand;

cout << «Lead time to resupply (in days): «;
cin >> invtry[i].lead_time;
}

// Modify an existing item.
void update()
{
int i;
char name[80];

cout << «Enter item: «;
cin >> name;

for(i=0; i<SIZE; i++)
if(!strcmp(name, invtry[i].item)) break;

if(i==SIZE) {
cout << «Item not found.\n»;
return;
}

cout << «Enter new information.\n»;
input(i);
}

// Display the list.
void display()
{
int t;

for(t=0; t<SIZE; t++) {
if(*invtry[t].item) {
cout << invtry[t].item << ‘\n’;
cout << «Cost: $» << invtry[t].cost;
cout << «\nRetail: $»;
cout << invtry[t].retail << ‘\n’;
cout << «On hand: » << invtry[t].on_hand;
cout << «\nResupply time: «;
cout << invtry[t].lead_time << » days\n\n»;
}
}
}

listing 18
// Pass a structure to a function.
#include <iostream>
using namespace std;

// Define a structure type.
struct sample {
int a;
char ch;
} ;

void f1(sample parm);

int main()
{
struct sample arg; // declare arg

arg.a = 1000;
arg.ch = ‘X’;

f1(arg);

return 0;
}

void f1(sample parm)
{
cout << parm.a << » » << parm.ch;
cout << «\n»;
}

listing 19
// Demonstrate structure assignments.
#include <iostream>
using namespace std;

struct stype {
int a, b;
};

int main()
{
stype svar1, svar2;

svar1.a = svar1.b = 10;
svar2.a = svar2.b = 20;

cout << «Structures before assignment.\n»;
cout << «svar1: » << svar1.a << ‘ ‘ << svar1.b;
cout << ‘\n’;
cout << «svar2: » << svar2.a << ‘ ‘ << svar2.b;
cout << «\n\n»;

svar2 = svar1; // assign structures

cout << «Structures after assignment.\n»;
cout << «svar1: » << svar1.a << ‘ ‘ << svar1.b;
cout << ‘\n’;
cout << «svar2: » << svar2.a << ‘ ‘ << svar2.b;

return 0;
}

listing 20
struct stype1 {
int a, b;
};

struct stype2 {
int a, b;
};

stype1 svar1;
stype2 svar2;

svar2 = svar1; // Error — type mismatch

listing 21
inv_type *inv_pointer;

listing 22
struct bal {
float balance;
char name[80];
} person;

bal *p; // declare a structure pointer

listing 23
p = &person;

listing 24
p->balance

listing 25
struct tm {
int tm_sec; // seconds, 0-61
int tm_min; // minutes, 0-59
int tm_hour; // hours, 0-23
int tm_mday; // day of the month, 1-31
int tm_mon; // months since Jan, 0-11
int tm_year; // years from 1900
int tm_wday; // days since Sunday, 0-6
int tm_yday; // days since Jan 1, 0-365
int tm_isdst; // Daylight Saving Time indicator
};

listing 26
// This program displays the current system time.

#include <iostream>
#include <ctime>
using namespace std;

int main()
{
struct tm *ptr;
time_t lt;

lt = time(‘\0’);

ptr = localtime(&lt);

cout << ptr->tm_hour << ‘:’ << ptr->tm_min;
cout << ‘:’ << ptr->tm_sec;

return 0;
}

listing 27
// This program displays the current system time.

#include <iostream>
#include <ctime>
using namespace std;

int main()
{
struct tm *ptr;
time_t lt;

lt = time(‘\0’);

ptr = localtime(&lt);
cout << asctime(ptr);

return 0;
}

listing 28
// Demonstrate a reference to a structure.
#include <iostream>
using namespace std;

struct mystruct {
int a;
int b;
};

mystruct &f(mystruct &var);

int main()
{
mystruct x, y;
x.a = 10; x.b = 20;

cout << «Original x.a and x.b: «;
cout << x.a << ‘ ‘ << x.b << ‘\n’;

y = f(x);

cout << «Modified x.a and x.b: «;
cout << x.a << ‘ ‘ << x.b << ‘\n’;
cout << «Modified y.a and y.b: «;
cout << y.a << ‘ ‘ << y.b << ‘\n’;

return 0;
}

// Receive and return a reference to a structure.
mystruct &f(mystruct &var)
{
var.a = var.a * var.a;
var.b = var.b / var.b;
return var;
}

listing 29
struct stype {
int nums[10][10]; // 10 x 10 array of ints
float b;
} var;

listing 30
var.nums[3][7]

listing 31
struct addr {
char name[40];
char street[40];
char city[40];
char zip[10];
}

struct emp {
addr address;
float wage;
} worker;

listing 32
worker.address.zip = 98765;

listing 33
struct mystruct {
int a;
char str[80];
mystruct *sptr; // pointer to mystruct objects
};

listing 34
struct C_struct {
int a;
int b;
}

// declare a C_struct variable
struct C_struct svar:

listing 35
struct status_type {
unsigned delta_cts: 1;
unsigned delta_dsr: 1;
unsigned tr_edge: 1;
unsigned delta_rec: 1;
unsigned cts: 1;
unsigned dsr: 1;
unsigned ring: 1;
unsigned rec_line: 1;
} status;

listing 36
status = get_port_status();

if(status.cts) cout << «clear to send»;
if(status.dsr) cout << «data ready»;

listing 37
status.ring = 0;

listing 38
struct status_type {
unsigned : 4;
unsigned cts: 1;
unsigned dsr: 1;
} status;

listing 39
struct emp {
struct addr address;
float pay;
unsigned lay_off: 1; // lay off or active
unsigned hourly: 1: // hourly pay or wage
unsigned deductions: 3: // IRS deductions
};

listing 40
union utype {
short int i;
char ch;
} ;

listing 41
utype u_var;

listing 42
u_var.ch = ‘A’;

listing 43
// …
func1(&u_var); // pass func1() a pointer to u_var
// …
}

void func1(utype *un)
{
un->i = 10; /* Assign 10 to u_var using
a pointer. */
}

listing 44
// Use a union to exchange the bytes within a short integer.
#include <iostream>
using namespace std;

void disp_binary(unsigned u);

union swap_bytes {
short int num;
char ch[2];
};

int main()
{
swap_bytes sb;
char temp;

sb.num = 15; // binary: 0000 0000 0000 1111
cout << «Original bytes: «;
disp_binary(sb.ch[1]);
cout << » «;
disp_binary(sb.ch[0]);
cout << «\n\n»;
// exchange the bytes
temp = sb.ch[0];
sb.ch[0] = sb.ch[1];
sb.ch[1] = temp;

cout << «Exchanged bytes: «;
disp_binary(sb.ch[1]);
cout << » «;
disp_binary(sb.ch[0]);
cout << «\n\n»;

return 0;
}

// Display the bits within a byte.
void disp_binary(unsigned u)
{
register int t;

for(t=128; t>0; t=t/2)
if(u & t) cout << «1 «;
else cout << «0 «;
}

listing 45
// Display the ASCII code in binary for characters.

#include <iostream>
#include <conio.h>
using namespace std;

// a bit field that will be decoded
struct byte {
unsigned a : 1;
unsigned b : 1;
unsigned c : 1;
unsigned d : 1;
unsigned e : 1;
unsigned f : 1;
unsigned g : 1;
unsigned h : 1;
};

union bits {
char ch;
struct byte bit;
} ascii ;

void disp_bits(bits b);

int main()
{
do {
cin >> ascii.ch;
cout << «: «;
disp_bits(ascii);
} while(ascii.ch!=’q’); // quit if q typed

return 0;
}

// Display the bit pattern for each character.
void disp_bits(bits b)
{
if(b.bit.h) cout << «1 «;
else cout << «0 «;
if(b.bit.g) cout << «1 «;
else cout << «0 «;
if(b.bit.f) cout << «1 «;
else cout << «0 «;
if(b.bit.e) cout << «1 «;
else cout << «0 «;
if(b.bit.d) cout << «1 «;
else cout << «0 «;
if(b.bit.c) cout << «1 «;
else cout << «0 «;
if(b.bit.b) cout << «1 «;
else cout << «0 «;
if(b.bit.a) cout << «1 «;
else cout << «0 «;
cout << «\n»;
}

listing 46
// Demonstrate an anonymous union.
#include <iostream>
using namespace std;

int main()
{
// this is an anonymous union
union {
short int count;
char ch[2];
};

// Here, refer to union members directly
ch[0] = ‘X’;
ch[1] = ‘Y’;
cout << «union as chars: » << ch[0] << ch[1] << ‘\n’;
cout << «union as integer: » << count << ‘\n’;

return 0;
}

listing 47
union x {
char ch;
int i;
double f;
} u_var;



listing 1
// This creates the class queue.
class queue {
int q[100];
int sloc, rloc;
public:
void init();
void qput(int i);
int qget();
};

listing 2
queue Q1, Q2;

listing 3
void queue::qput(int i)
{
if(sloc==100) {
cout << «Queue is full.\n»;
return;
}
sloc++;
q[sloc] = i;
}

listing 4
queue ob1, ob2;

ob1.init();

listing 5
#include <iostream>
using namespace std;

// This creates the class queue.
class queue {
int q[100];
int sloc, rloc;
public:
void init();
void qput(int i);
int qget();
};

// Initialize the queue.
void queue::init()
{
rloc = sloc = 0;
}

// Put an integer into the queue.
void queue::qput(int i)
{
if(sloc==100) {
cout << «Queue is full.\n»;
return;
}
sloc++;
q[sloc] = i;
}

// Get an integer from the queue.
int queue::qget()
{
if(rloc == sloc) {
cout << «Queue underflow.\n»;
return 0;
}
rloc++;
return q[rloc];
}

int main()
{
queue a, b; // create two queue objects

a.init();
b.init();

a.qput(10);
b.qput(19);

a.qput(20);
b.qput(1);

cout << «Contents of queue a: «;
cout << a.qget() << » «;
cout << a.qget() << «\n»;

cout << «Contents of queue b: «;
cout << b.qget() << » «;
cout << b.qget() << «\n»;

return 0;
}

listing 6
a.rloc = 0;

listing 7
// Demonstrate class member access.
#include <iostream>
using namespace std;

class myclass {
int a; // private data
public:
int b; // public data
void setab(int i); // public functions
int geta();
void reset();
};

void myclass::setab(int i)
{
a = i; // refer directly to a
b = i*i; // refer directly to b
}

int myclass::geta()
{
return a; // refer directly to a
}

void myclass::reset()
{
// call setab() directly
setab(0); // the object is already known
}

int main()
{
myclass ob;

ob.setab(5); // set ob.a and ob.b
cout << «ob after setab(5): «;
cout << ob.geta() << ‘ ‘;
cout << ob.b; // can access b because it is public
cout << ‘\n’;

ob.b = 20; // can access b because it is public
cout << «ob after ob.b=20: «;
cout << ob.geta() << ‘ ‘;
cout << ob.b;
cout << ‘\n’;

ob.reset();
cout << «ob after ob.reset(): «;
cout << ob.geta() << ‘ ‘;
cout << ob.b;
cout << ‘\n’;

return 0;
}

listing 8
// This creates the class queue.
class queue {
int q[100];
int sloc, rloc;
public:
queue(); // constructor
void qput(int i);
int qget();
};

listing 9
// This is the constructor.
queue::queue()
{
sloc = rloc = 0;
cout << «Queue Initialized.\n»;
}

listing 10
// This creates the class queue.
class queue {
int q[100];
int sloc, rloc;
public:
queue(); // constructor
~queue(); // destructor
void qput(int i);
int qget();
};

// This is the constructor.
queue::queue()
{
sloc = rloc = 0;
cout << «Queue initialized.\n»;
}

// This is the destructor.
queue::~queue()
{
cout << «Queue destroyed.\n»;
}

listing 11
// Demonstrate a constructor and a destructor.
#include <iostream>
using namespace std;

// This creates the class queue.
class queue {
int q[100];
int sloc, rloc;
public:
queue(); // constructor
~queue(); // destructor
void qput(int i);
int qget();
};

// This is the constructor.
queue::queue()
{
sloc = rloc = 0;
cout << «Queue initialized.\n»;
}

// This is the destructor.
queue::~queue()
{
cout << «Queue destroyed.\n»;
}

// Put an integer into the queue.
void queue::qput(int i)
{
if(sloc==100) {
cout << «Queue is full.\n»;
return;
}
sloc++;
q[sloc] = i;
}

// Get an integer from the queue.
int queue::qget()
{
if(rloc == sloc) {
cout << «Queue Underflow.\n»;
return 0;
}
rloc++;
return q[rloc];
}

int main()
{
queue a, b; // create two queue objects

a.qput(10);
b.qput(19);

a.qput(20);
b.qput(1);

cout << a.qget() << » «;
cout << a.qget() << » «;
cout << b.qget() << » «;
cout << b.qget() << «\n»;

return 0;
}

listing 12
// This creates the class queue.
class queue {
int q[100];
int sloc, rloc;
int who; // holds the queue’s ID number
public:
queue(int id); // parameterized constructor
~queue(); // destructor
void qput(int i);
int qget();
};

listing 13
// This is the constructor.
queue::queue(int id)
{
sloc = rloc = 0;
who = id;
cout << «Queue » << who << » initialized.\n»;
}

listing 14
queue a = queue(101);

listing 15
queue a(101);

listing 16
// Use a parameterized constructor.
#include <iostream>
using namespace std;

// This creates the class queue.
class queue {
int q[100];
int sloc, rloc;
int who; // holds the queue’s ID number
public:
queue(int id); // parameterized constructor
~queue(); // destructor
void qput(int i);
int qget();
};

// This is the constructor.
queue::queue(int id)
{
sloc = rloc = 0;
who = id;
cout << «Queue » << who << » initialized.\n»;
}

// This is the destructor.
queue::~queue()
{
cout << «Queue » << who << » destroyed.\n»;
}

// Put an integer into the queue.
void queue::qput(int i)
{
if(sloc==100) {
cout << «Queue is full.\n»;
return;
}
sloc++;
q[sloc] = i;
}

// Get an integer from the queue.
int queue::qget()
{
if(rloc == sloc) {
cout << «Queue underflow.\n»;
return 0;
}
rloc++;
return q[rloc];
}

int main()
{
queue a(1), b(2); // create two queue objects

a.qput(10);
b.qput(19);

a.qput(20);
b.qput(1);

cout << a.qget() << » «;
cout << a.qget() << » «;
cout << b.qget() << » «;
cout << b.qget() << «\n»;

return 0;
}

listing 17
#include <iostream>
using namespace std;

class widget {
int i;
int j;
public:
widget(int a, int b);
void put_widget();
} ;

// Pass 2 arguments to widget().
widget::widget(int a, int b)
{
i = a;
j = b;
}

void widget::put_widget()
{
cout << i << » » << j << «\n»;
}

int main()
{
widget x(10, 20), y(0, 0);

x.put_widget();
y.put_widget();

return 0;
}

listing 18
#include <iostream>
using namespace std;

class myclass {
int a;
public:
myclass(int x);
int get_a();
};

myclass::myclass(int x)
{
a = x;
}

int myclass::get_a()
{
return a;
}

int main()
{
myclass ob = 4; // calls myclass(4)

cout << ob.get_a();

return 0;
}

listing 19
myclass ob = myclass(4);

listing 20
// Use struct to create a class.
#include <iostream>
using namespace std;

struct cl {
int get_i(); // these are public
void put_i(int j); // by default
private:
int i;
};

int cl::get_i()
{
return i;
}

void cl::put_i(int j)
{
i = j;
}

int main()
{
cl s;

s.put_i(10);
cout << s.get_i();

return 0;
}

listing 21
// Now, use class, instead.
#include <iostream>
using namespace std;

class cl {
int i; // private by default
public:
int get_i();
void put_i(int j);
};

int cl::get_i()
{
return i;
}

void cl::put_i(int j)
{
i = j;
}

int main()
{
cl s;

s.put_i(10);
cout << s.get_i();

return 0;
}

listing 22
// Create union-based class.
#include <iostream>
using namespace std;

union u_type {
u_type(short int a); // public by default
void showchars();
short int i;
char ch[2];
};

// constructor
u_type::u_type(short int a)
{
i = a;
}

// Show the characters that comprise a short int.
void u_type::showchars()
{
cout << ch[0] << » «;
cout << ch[1] << «\n»;
}

int main()
{
u_type u(1000);

u.showchars();

return 0;
}

listing 23
#include <iostream>
using namespace std;

class cl {
int i; // private by default
public:
int get_i();
void put_i(int j);
} ;

inline int cl::get_i()
{
return i;
}

inline void cl::put_i(int j)
{
i = j;
}

int main()
{
cl s;

s.put_i(10);
cout << s.get_i();

return 0;
}

listing 24
#include <iostream>
using namespace std;

class cl {
int i; // private by default
public:
// automatic inline functions
int get_i() { return i; }
void put_i(int j) { i = j; }
} ;

int main()
{
cl s;

s.put_i(10);
cout << s.get_i();

return 0;
}

listing 25
class cl {
int i; // private by default
public:
// inline functions
int get_i()
{
return i;
}

void put_i(int j)
{
i = j;
}
};

listing 26
// An example of arrays of objects

#include <iostream>
using namespace std;

enum resolution {low, medium, high};

class display {
int width;
int height;
resolution res;
public:
void set_dim(int w, int h) {width = w; height = h;}
void get_dim(int &w, int &h) {w = width; h = height;}
void set_res(resolution r) {res = r;}
resolution get_res() {return res;}
};

char names[3][7] = {
«low»,
«medium»,
«high»,
} ;

int main()
{
display display_mode[3];
int i, w, h;

display_mode[0].set_res(low);
display_mode[0].set_dim(640, 480);

display_mode[1].set_res(medium);
display_mode[1].set_dim(800, 600);

display_mode[2].set_res(high);
display_mode[2].set_dim(1600, 1200);

cout << «Available display modes:\n\n»;

for(i=0; i<3; i++) {
cout << names[display_mode[i].get_res()] << «: «;
display_mode[i].get_dim(w, h);
cout << w << » by » << h << «\n»;
}

return 0;
}
listing 27
// Initialize an array of objects.
#include <iostream>
using namespace std;

class samp {
int a;
public:
samp(int n) { a = n; }
int get_a() { return a; }
};

int main()
{
samp sampArray[4] = { -1, -2, -3, -4 };
int i;

for(i=0; i<4; i++) cout << sampArray[i].get_a() << ‘ ‘;

cout << «\n»;

return 0;
}

listing 28
samp sampArray[4] = { samp(-1), samp(-2), samp(-3), samp(-4) };

listing 29
#include <iostream>
using namespace std;

class samp {
int a, b;
public:
samp(int n, int m) { a = n; b = m; }
int get_a() { return a; }
int get_b() { return b; }
};

int main()
{
samp sampArray[4][2] = {
samp(1, 2), samp(3, 4),
samp(5, 6), samp(7, 8),
samp(9, 10), samp(11, 12),
samp(13, 14), samp(15, 16)
};

int i;

for(i=0; i<4; i++) {
cout << sampArray[i][0].get_a() << ‘ ‘;
cout << sampArray[i][0].get_b() << «\n»;
cout << sampArray[i][1].get_a() << ‘ ‘;
cout << sampArray[i][1].get_b() << «\n»;
}

cout << «\n»;

return 0;
}

listing 30
// A simple example using an object pointer.

#include <iostream>
using namespace std;

class P_example {
int num;
public:
void set_num(int val) {num = val;}
void show_num();
};

void P_example::show_num()
{
cout << num << «\n»;
}

int main()
{
P_example ob, *p; // declare an object and pointer to it

ob.set_num(1); // access ob directly

ob.show_num();

p = &ob; // assign p the address of ob
p->show_num(); // access ob using pointer

return 0;
}

listing 31
// Incrementing and decrementing an object pointer.
#include <iostream>
using namespace std;

class P_example {
int num;
public:
void set_num(int val) {num = val;}
void show_num();
};

void P_example::show_num()
{
cout << num << «\n»;
}

int main()
{
P_example ob[2], *p;

ob[0].set_num(10); // access objects directly
ob[1].set_num(20);

p = &ob[0]; // obtain pointer to first element
p->show_num(); // show value of ob[0] using pointer

p++; // advance to next object
p->show_num(); // show value of ob[1] using pointer

p—; // retreat to previous object
p->show_num(); // again show value of ob[0]

return 0;
}



listing 1
class cl {
// …
public:
friend void frnd(cl ob);
// …
};

listing 2
// Demonstrate a friend function.
#include <iostream>
using namespace std;

class myclass {
int a, b;
public:
myclass(int i, int j) { a=i; b=j; }
friend int sum(myclass x); // sum() is a friend of myclass
};

// Note: sum() is not a member function of any class.
int sum(myclass x)
{
/* Because sum() is a friend of myclass, it can
directly access a and b. */

return x.a + x.b;
}

int main()
{
myclass n(3, 4);

cout << sum(n);

return 0;
}

listing 3
// Use a friend function.
#include <iostream>
using namespace std;

const int IDLE=0;
const int INUSE=1;

class C2; // forward declaration

class C1 {
int status; // IDLE if off, INUSE if on screen
// …
public:
void set_status(int state);
friend int idle(C1 a, C2 b);
};

class C2 {
int status; // IDLE if off, INUSE if on screen
// …
public:
void set_status(int state);
friend int idle(C1 a, C2 b);
};

void C1::set_status(int state)
{
status = state;
}

void C2::set_status(int state)
{
status = state;
}

// idle( ) is a friend of C1 and C2.
int idle(C1 a, C2 b)
{
if(a.status || b.status) return 0;
else return 1;
}

int main()
{
C1 x;
C2 y;

x.set_status(IDLE);
y.set_status(IDLE);

if(idle(x, y)) cout << «Screen Can Be Used.\n»;
else cout << «Pop-up In Use.\n»;

x.set_status(INUSE);

if(idle(x, y)) cout << «Screen Can Be Used.\n»;
else cout << «Pop-up In Use.\n»;

return 0;
}

listing 4
/* A function can be a member of one class and
a friend of another. */
#include <iostream>
using namespace std;

const int IDLE=0;
const int INUSE=1;

class C2; // forward declaration

class C1 {
int status; // IDLE if off, INUSE if on screen
// …
public:
void set_status(int state);
int idle(C2 b); // now a member of C1
};

class C2 {
int status; // IDLE if off, INUSE if on screen
// …
public:
void set_status(int state);
friend int C1::idle(C2 b);
};

void C1::set_status(int state)
{
status = state;
}

void C2::set_status(int state)
{
status = state;
}

// idle() is member of C1, but friend of C2.
int C1::idle(C2 b)
{
if(status || b.status) return 0;
else return 1;
}

int main()
{
C1 x;
C2 y;

x.set_status(IDLE);
y.set_status(IDLE);

if(x.idle(y)) cout << «Screen Can Be Used.\n»;
else cout << «Pop-up In Use.\n»;

x.set_status(INUSE);

if(x.idle(y)) cout << «Screen Can Be Used.\n»;
else cout << «Pop-up In Use.\n»;

return 0;
}

listing 5
// Use overloaded constructors.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

class timer{
int seconds;
public:
// seconds specified as a string
timer(char *t) { seconds = atoi(t); }

// seconds specified as integer
timer(int t) { seconds = t; }

// time specified in minutes and seconds
timer(int min, int sec) { seconds = min*60 + sec; }

void run();
} ;

void timer::run()
{
clock_t t1;

t1 = clock();

while((clock()/CLOCKS_PER_SEC — t1/CLOCKS_PER_SEC) < seconds);

cout << «\a»; // ring the bell
}

int main()
{
timer a(10), b(«20»), c(1, 10);

a.run(); // count 10 seconds
b.run(); // count 20 seconds
c.run(); // count 1 minute, 10 seconds

return 0;
}

listing 6
int n = strlen(str);

double arc = sin(theta);

float d = 1.02 * count / deltax;

listing 7
// Demonstrate dynamic initialization.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

class timer{
int seconds;
public:
// seconds specified as a string
timer(char *t) { seconds = atoi(t); }

// seconds specified as integer
timer(int t) { seconds = t; }

// time specified in minutes and seconds
timer(int min, int sec) { seconds = min*60 + sec; }

void run();
} ;

void timer::run()
{
clock_t t1;

t1 = clock();

while((clock()/CLOCKS_PER_SEC — t1/CLOCKS_PER_SEC) < seconds);

cout << «\a»; // ring the bell
}

int main()
{
timer a(10);

a.run();

cout << «Enter number of seconds: «;
char str[80];
cin >> str;
timer b(str); // initialize at run time
b.run();

cout << «Enter minutes and seconds: «;
int min, sec;
cin >> min >> sec;
timer c(min, sec); // initialize at run time
c.run();

return 0;
}

listing 8
// Demonstrate object assignment.
#include <iostream>
using namespace std;

class myclass {
int a, b;
public:
void setab(int i, int j) { a = i, b = j; }
void showab();
};

void myclass::showab()
{
cout << «a is » << a << ‘\n’;
cout << «b is » << b << ‘\n’;
}

int main()
{
myclass ob1, ob2;

ob1.setab(10, 20);
ob2.setab(0, 0);
cout << «ob1 before assignment: \n»;
ob1.showab();
cout << «ob2 before assignment: \n»;
ob2.showab();
cout << ‘\n’;

ob2 = ob1; // assign ob1 to ob2

cout << «ob1 after assignment: \n»;
ob1.showab();
cout << «ob2 after assignment: \n»;
ob2.showab();

return 0;
}

listing 9
#include <iostream>
using namespace std;

class OBJ {
int i;
public:
void set_i(int x) { i = x; }
void out_i() { cout << i << » «; }
};

void f(OBJ x)
{
x.out_i(); // outputs 10
x.set_i(100); // this affects only local copy
x.out_i(); // outputs 100
}

int main()
{
OBJ o;

o.set_i(10);
f(o);
o.out_i(); // still outputs 10, value of i unchanged

return 0;
}

listing 10
// Constructors, destructors, and passing objects.
#include <iostream>
using namespace std;

class myclass {
int val;
public:
myclass(int i) { val = i; cout << «Constructing\n»; }
~myclass() { cout << «Destructing\n»; }
int getval() { return val; }
};

void display(myclass ob)
{
cout << ob.getval() << ‘\n’;
}

int main()
{
myclass a(10);

display(a);

return 0;
}

listing 11
// Demonstrate a problem when passing objects.
#include <iostream>
#include <cstdlib>
using namespace std;

class myclass {
int *p;
public:
myclass(int i);
~myclass();
int getval() { return *p; }
};

myclass::myclass(int i)
{
cout << «Allocating p\n»;
p = new int;

*p = i;
}

myclass::~myclass()
{
cout << «Freeing p\n»;
delete p;
}

// This will cause a problem.
void display(myclass ob)
{
cout << ob.getval() << ‘\n’;
}

int main()
{
myclass a(10);

display(a);

return 0;
}

listing 12
// One solution to the problem of passing objects.
#include <iostream>
#include <cstdlib>
using namespace std;

class myclass {
int *p;
public:
myclass(int i);
~myclass();
int getval() { return *p; }
};

myclass::myclass(int i)
{
cout << «Allocating p\n»;
p = new int;

*p = i;
}

myclass::~myclass()
{
cout << «Freeing p\n»;
delete p;
}

/* This will NOT cause a problem.

Because ob is now passed by reference, no
copy of the calling argument is made and thus,
no object goes out-of-scope when display()
terminates.
*/
void display(myclass &ob)
{
cout << ob.getval() << ‘\n’;
}

int main()
{
myclass a(10);

display(a);

return 0;
}

listing 13
// Returning an object.
#include <iostream>
#include <cstring>
using namespace std;

class sample {
char s[80];
public:
void show() { cout << s << «\n»; }
void set(char *str) { strcpy(s, str); }
};

// Return an object of type sample.
sample input()
{
char instr[80];
sample str;

cout << «Enter a string: «;
cin >> instr;

str.set(instr);

return str;
}

int main()
{
sample ob;

// assign returned object to ob
ob = input();
ob.show();

return 0;
}

listing 14
// An error generated by returning an object.
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;

class sample {
char *s;
public:
sample() { s = 0; }
~sample() { if(s) delete [] s; cout << «Freeing s\n»; }
void show() { cout << s << «\n»; }
void set(char *str);
};

// Load a string.
void sample::set(char *str)
{
s = new char[strlen(str)+1];

strcpy(s, str);
}

// Return an object of type sample.
sample input()
{
char instr[80];
sample str;

cout << «Enter a string: «;
cin >> instr;

str.set(instr);
return str;
}

int main()
{
sample ob;

// assign returned object to ob
ob = input(); // This causes an error!!!!
ob.show();

return 0;
}

listing 15
myclass x = y; // y explicitly initializing x
func1(y); // y passed as a parameter
y = func2(); // y receiving a returned object

listing 16
// Use a copy constructor to construct a parameter.
#include <iostream>
#include <cstdlib>
using namespace std;

class myclass {
int *p;
public:
myclass(int i); // normal constructor
myclass(const myclass &ob); // copy constructor
~myclass();
int getval() { return *p; }
};

// Copy constructor.
myclass::myclass(const myclass &obj)
{
p = new int;

*p = *obj.p; // copy value
cout << «Copy constructor called.\n»;
}

// Normal Constructor.
myclass::myclass(int i)
{
cout << «Allocating p\n»;
p = new int;

*p = i;
}

myclass::~myclass()
{
cout << «Freeing p\n»;
delete p;
}

// This function takes one object parameter.
void display(myclass ob)
{
cout << ob.getval() << ‘\n’;
}

int main()
{
myclass a(10);

display(a);

return 0;
}

listing 17
// The copy constructor is called for initialization.
#include <iostream>
#include <cstdlib>
using namespace std;

class myclass {
int *p;
public:
myclass(int i); // normal constructor
myclass(const myclass &ob); // copy constructor
~myclass();
int getval() { return *p; }
};

// Copy constructor.
myclass::myclass(const myclass &ob)
{
p = new int;

*p = *ob.p; // copy value
cout << «Copy constructor allocating p.\n»;
}

// Normal constructor.
myclass::myclass(int i)
{
cout << «Normal constructor allocating p.\n»;
p = new int;

*p = i;
}

myclass::~myclass()
{
cout << «Freeing p\n»;
delete p;
}

int main()
{
myclass a(10); // calls normal constructor

myclass b = a; // calls copy constructor

return 0;
}

listing 18
myclass a(2), b(3);
// …
b = a;

listing 19
/* Copy constructor is called when a temporary object
is created as a function return value.
*/
#include <iostream>
using namespace std;

class myclass {
public:
myclass() { cout << «Normal constructor.\n»; }
myclass(const myclass &obj) { cout << «Copy constructor.\n»; }
};

myclass f()
{
myclass ob; // invoke normal constructor

return ob; // implicitly invoke copy constructor
}

int main()
{
myclass a; // invoke normal constructor

a = f(); // invoke copy constructor

return 0;
}

listing 20
class cl {
int i;
void f() { … };
.
.
.
};

listing 21
i = 10;

listing 22
this->i = 10;

listing 23
#include <iostream>
using namespace std;

class cl {
int i;
public:
void load_i(int val) { this->i = val; } // same as i = val
int get_i() { return this->i; } // same as return i
} ;

int main()
{
cl o;

o.load_i(100);
cout << o.get_i();

return 0;
}



listing 1
// Overload operators using member functions.
#include <iostream>
using namespace std;

class three_d {
int x, y, z; // 3-D coordinates
public:
three_d() { x = y = z = 0; }
three_d(int i, int j, int k) {x = i; y = j; z = k; }

three_d operator+(three_d op2); // op1 is implied
three_d operator=(three_d op2); // op1 is implied

void show() ;
};

// Overload +.
three_d three_d::operator+(three_d op2)
{
three_d temp;

temp.x = x + op2.x; // These are integer additions
temp.y = y + op2.y; // and the + retains is original
temp.z = z + op2.z; // meaning relative to them.
return temp;
}

// Overload assignment.
three_d three_d::operator=(three_d op2)
{
x = op2.x; // These are integer assignments
y = op2.y; // and the = retains its original
z = op2.z; // meaning relative to them.
return *this;
}

// Show X, Y, Z coordinates.
void three_d::show()
{
cout << x << «, «;
cout << y << «, «;
cout << z << «\n»;
}

int main()
{
three_d a(1, 2, 3), b(10, 10, 10), c;

a.show();
b.show();

c = a + b; // add a and b together
c.show();

c = a + b + c; // add a, b and c together
c.show();

c = b = a; // demonstrate multiple assignment
c.show();
b.show();

return 0;
}

listing 2
temp.x = x + op2.x;

listing 3
a = b = c = d;

listing 4
// Overload a unary operator.
#include <iostream>
using namespace std;

class three_d {
int x, y, z; // 3-D coordinates
public:
three_d() { x = y = z = 0; }
three_d(int i, int j, int k) {x = i; y = j; z = k; }

three_d operator+(three_d op2); // op1 is implied
three_d operator=(three_d op2); // op1 is implied
three_d operator++(); // prefix version of ++

void show() ;
} ;

// Overload +.
three_d three_d::operator+(three_d op2)
{
three_d temp;

temp.x = x + op2.x; // These are integer additions
temp.y = y + op2.y; // and the + retains is original
temp.z = z + op2.z; // meaning relative to them.
return temp;
}

// Overload assignment.
three_d three_d::operator=(three_d op2)
{
x = op2.x; // These are integer assignments
y = op2.y; // and the = retains its original
z = op2.z; // meaning relative to them.
return *this;
}

// Overload the prefix version of ++.
three_d three_d::operator++()
{
x++; // increment x, y, and z
y++;
z++;
return *this;
}

// Show X, Y, Z coordinates.
void three_d::show()
{
cout << x << «, «;
cout << y << «, «;
cout << z << «\n»;
}

int main()
{
three_d a(1, 2, 3), b(10, 10, 10), c;
a.show();
b.show();

c = a + b; // add a and b together
c.show();

c = a + b + c; // add a, b and c together
c.show();

c = b = a; // demonstrate multiple assignment
c.show();
b.show();

++c; // increment c
c.show();

return 0;
}

listing 5
++O;

listing 6
O++;

listing 7
three_d three_d::operator++(int notused);

listing 8
// Overload the postfix version of ++.
three_d three_d::operator++(int notused)
{
three_d temp = *this; // save original value

x++; // increment x, y, and z
y++;
z++;
return temp; // return original value
}

listing 9
three_d temp = *this;

listing 10
// Demonstrate prefix and postfix ++.
#include <iostream>
using namespace std;

class three_d {
int x, y, z; // 3-D coordinates
public:
three_d() { x = y = z = 0; }
three_d(int i, int j, int k) {x = i; y = j; z = k; }

three_d operator+(three_d op2); // op1 is implied
three_d operator=(three_d op2); // op1 is implied
three_d operator++(); // prefix version of ++
three_d operator++(int notused); // postfix version of ++

void show() ;
};

// Overload +.
three_d three_d::operator+(three_d op2)
{
three_d temp;

temp.x = x + op2.x; // These are integer additions
temp.y = y + op2.y; // and the + retains its original
temp.z = z + op2.z; // meaning relative to them.
return temp;
}

// Overload assignment.
three_d three_d::operator=(three_d op2)
{
x = op2.x; // These are integer assignments
y = op2.y; // and the = retains its original
z = op2.z; // meaning relative to them.
return *this;
}

// Overload the prefix version of ++.
three_d three_d::operator++()
{
x++; // increment x, y, and z
y++;
z++;
return *this; // return altered value
}

// Overload the postfix version of ++.
three_d three_d::operator++(int notused)
{
three_d temp = *this; // save original value

x++; // increment x, y, and z
y++;
z++;
return temp; // return original value
}

// Show X, Y, Z coordinates.
void three_d::show( )
{
cout << x << «, «;
cout << y << «, «;
cout << z << «\n»;
}

int main()
{
three_d a(1, 2, 3), b(10, 10, 10), c;
a.show();
b.show();

c = a + b; // add a and b together
c.show();

c = a + b + c; // add a, b and c together
c.show();

c = b = a; // demonstrate multiple assignment
c.show();
b.show();

++c; // prefix increment
c.show();

c++; // postfix increment
c.show();

a = ++c; // a receives c’s value after increment
a.show(); // a and c
c.show(); // are the same

a = c++; // a receives c’s value prior to increment
a.show(); // a and c
c.show(); // now differ

return 0;
}

listing 11
// Overload subtraction.
three_d three_d::operator-(three_d op2)
{
three_d temp;

temp.x = x — op2.x;
temp.y = y — op2.y;
temp.z = z — op2.z;
return temp;
}

listing 12
// Overload + using a friend.
#include <iostream>
using namespace std;

class three_d {
int x, y, z; // 3-D coordinates
public:
three_d() { x = y = z = 0; }
three_d(int i, int j, int k) { x = i; y = j; z = k;}

friend three_d operator+(three_d op1, three_d op2);
three_d operator=(three_d op2); // op2 is implied

void show() ;
} ;

// This is now a friend function.
three_d operator+(three_d op1, three_d op2)
{
three_d temp;

temp.x = op1.x + op2.x;
temp.y = op1.y + op2.y;
temp.z = op1.z + op2.z;
return temp;
}

// Overload assignment.
three_d three_d::operator=(three_d op2)
{
x = op2.x;
y = op2.y;
z = op2.z;
return *this;
}

// Show X, Y, Z coordinates.
void three_d::show()
{
cout << x << «, «;
cout << y << «, «;
cout << z << «\n»;
}

int main()
{
three_d a(1, 2, 3), b(10, 10, 10), c;

a.show();
b.show();

c = a + b; // add a and b together
c.show();

c = a + b + c; // add a, b and c together
c.show();

c = b = a; // demonstrate multiple assignment
c.show();
b.show();

return 0;
}

listing 13
O = O + 10; // will work

listing 14
O = 10 + O; // won’t work

listing 15
#include <iostream>
using namespace std;

class CL {
public:
int count;
CL operator=(CL obj);
friend CL operator+(CL ob, int i);
friend CL operator+(int i, CL ob);
};

CL CL::operator=(CL obj)
{
count = obj.count;
return *this;
}

// This handles ob + int.
CL operator+(CL ob, int i)
{
CL temp;

temp.count = ob.count + i;
return temp;
}

// This handles int + ob.
CL operator+(int i, CL ob)
{
CL temp;

temp.count = ob.count + i;
return temp;
}

int main()
{
CL O;

O.count = 10;
cout << O.count << » «; // outputs 10

O = 10 + O; // add object to integer
cout << O.count << » «; // outputs 20

O = O + 12; // add integer to object
cout << O.count; // outputs 32

return 0;
}

listing 16
// Overload the prefix form of ++.
three_d three_d::operator++()
{
x++;
y++;
z++;
return *this;
}

listing 17
// THIS WILL NOT WORK
three_d operator++(three_d op1)
{
op1.x++;
op1.y++;
op1.z++;
return op1;
}

listing 18
// This program uses friend operator++() functions.
#include <iostream>
using namespace std;

class three_d {
int x, y, z; // 3-D coordinates
public:
three_d() { x = y = z = 0; }
three_d(int i, int j, int k) {x = i; y = j; z = k; }

friend three_d operator+(three_d op1, three_d op2);
three_d operator=(three_d op2);

// use a reference to overload the ++
friend three_d operator++(three_d &op1);
friend three_d operator++(three_d &op1, int notused);

void show() ;
} ;

// This is now a friend function.
three_d operator+(three_d op1, three_d op2)
{
three_d temp;

temp.x = op1.x + op2.x;
temp.y = op1.y + op2.y;
temp.z = op1.z + op2.z;
return temp;
}

// Overload the =.
three_d three_d::operator=(three_d op2)
{
x = op2.x;
y = op2.y;
z = op2.z;
return *this;
}

/* Overload prefix ++ using a friend function.
This requires the use of a reference parameter. */
three_d operator++(three_d &op1)
{
op1.x++;
op1.y++;
op1.z++;
return op1;
}

/* Overload postfix ++ using a friend function.
This requires the use of a reference parameter. */
three_d operator++(three_d &op1, int notused)
{
three_d temp = op1;

op1.x++;
op1.y++;
op1.z++;
return temp;
}

// Show X, Y, Z coordinates.
void three_d::show()
{
cout << x << «, «;
cout << y << «, «;
cout << z << «\n»;
}

int main()
{
three_d a(1, 2, 3), b(10, 10, 10), c;

a.show();
b.show();

c = a + b; // add a and b together
c.show();

c = a + b + c; // add a, b and c together
c.show();

c = b = a; // demonstrate multiple assignment
c.show();
b.show();

++c; // prefix increment
c.show();

c++; // postfix increment
c.show();

a = ++c; // a receives c’s value after increment
a.show( ); // a and c
c.show( ); // are the same

a = c++; // a receives c’s value prior to increment
a.show( ); // a and c
c.show( ); // now differ

return 0;
}

listing 19
// Overload ==.
bool three_d::operator==(three_d op2)
{
if((x == op2.x) && (y == op2.y) && (z == op2.z))
return true;
else
return false;
}

listing 20
three_d a, b;

// …

if(a == b) cout << «a equals b\n»;
else cout << «a does not equal b\n»;

listing 21
// An error generated by returning an object.
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;

class sample {
char *s;
public:
sample() { s = 0; }
sample(const sample &ob); // copy constructor
~sample( ) { if(s) delete [] s; cout << «Freeing s\n»; }
void show() { cout << s << «\n»; }
void set(char *str);
};

// Copy constructor.
sample::sample(const sample &ob)
{
s = new char[strlen(ob.s)+1];

strcpy(s, ob.s);
}

// Load a string.
void sample::set(char *str)
{
s = new char[strlen(str)+1];

strcpy(s, str);
}

// Return an object of type sample.
sample input()
{
char instr[80];
sample str;

cout << «Enter a string: «;
cin >> instr;

str.set(instr);
return str;
}

int main()
{
sample ob;

// assign returned object to ob
ob = input(); // This causes an error!!!!
ob.show();

return 0;
}

listing 22
// This program is now fixed.
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;

class sample {
char *s;
public:
sample(); // normal constructor
sample(const sample &ob); // copy constructor
~sample( ) { if(s) delete [] s; cout << «Freeing s\n»; }
void show() { cout << s << «\n»; }
void set(char *str);
sample operator=(sample &ob); // overload assignment
};

// Normal constructor.
sample::sample()
{
s = new char(‘\0’); // s points to a null string.
}

// Copy constructor.
sample::sample(const sample &ob)
{
s = new char[strlen(ob.s)+1];

strcpy(s, ob.s);
}

// Load a string.
void sample::set(char *str)
{
s = new char[strlen(str)+1];

strcpy(s, str);
}

// Overload assignment operator.
sample sample::operator=(sample &ob)
{
/* If the target string is not large enough
then allocate a new string. */
if(strlen(ob.s) > strlen(s)) {
delete [] s;
s = new char[strlen(ob.s)+1];
}
strcpy(s, ob.s);
return *this;
}

// Return an object of type sample.
sample input()
{
char instr[80];
sample str;

cout << «Enter a string: «;
cin >> instr;

str.set(instr);
return str;
}

int main()
{
sample ob;

// assign returned object to ob
ob = input(); // This is now OK
ob.show();

return 0;
}

listing 23
O[3]

listing 24
O.operator[](3)

listing 25
// Overload [].
#include <iostream>
using namespace std;

const int SIZE = 3;

class atype {
int a[SIZE];
public:
atype() {
register int i;

for(i=0; i<SIZE; i++) a[i] = i;
}
int operator[](int i) {return a[i];}
};

int main()
{
atype ob;

cout << ob[2]; // displays 2

return 0;
}

listing 26
// Return a reference from [].
#include <iostream>
using namespace std;

const int SIZE = 3;

class atype {
int a[SIZE];
public:
atype() {
register int i;

for(i=0; i<SIZE; i++) a[i] = i;
}
int &operator[](int i) {return a[i];}
};

int main()
{
atype ob;

cout << ob[2]; // displays 2
cout << » «;

ob[2] = 25; // [] on left of =

cout << ob[2]; // now displays 25

return 0;
}

listing 27
// A safe array example.
#include <iostream>
#include <cstdlib>
using namespace std;

const int SIZE = 3;

class atype {
int a[SIZE];
public:
atype() {
register int i;

for(i=0; i<SIZE; i++) a[i] = i;
}
int &operator[](int i);
};

// Provide range checking for atype.
int &atype::operator[](int i)
{
if(i<0 || i> SIZE-1) {
cout << «\nIndex value of «;
cout << i << » is out-of-bounds.\n»;
exit(1);
}
return a[i];
}

int main()
{
atype ob;

cout << ob[2]; // displays 2
cout << » «;

ob[2] = 25; // [] appears on left

cout << ob[2]; // displays 25

ob[3] = 44; // generates runtime error, 3 out-of-range
return 0;
}

listing 28
ob[3] = 44;

listing 29
int operator()(float f, char *p);

listing 30
O(99.57, «overloading»);

listing 31
operator()(99.57, «overloading»);

listing 32
// Overload ().
#include <iostream>
using namespace std;

class three_d {
int x, y, z; // 3-D coordinates
public:
three_d() { x = y = z = 0; }
three_d(int i, int j, int k) {x = i; y = j; z = k; }
three_d operator()(int a, int b, int c);
void show() ;
};

// Overload ().
three_d three_d::operator()(int a, int b, int c)
{
three_d temp;

temp.x = x + a;
temp.y = y + b;
temp.z = z + c;

return temp;
}

// Show X, Y, Z coordinates.
void three_d::show()
{
cout << x << «, «;
cout << y << «, «;
cout << z << «\n»;
}

int main()
{
three_d ob1(1, 2, 3), ob2;

ob2 = ob1(10, 11, 12); // invoke operator()

cout << «ob1: «;
ob1.show();

cout << «ob2: «;
ob2.show();

return 0;
}

listing 33
#include <iostream>
#include <cstring>
using namespace std;

class str_type {
char string[80];
public:
str_type(char *str = «») { strcpy(string, str); }

str_type operator+(str_type str); // concatenate
str_type operator=(str_type str); // assign

// output the string
void show_str() { cout << string; }
};

listing 34
// Concatenate two strings.
str_type str_type::operator+(str_type str) {
str_type temp;

strcpy(temp.string, string);
strcat(temp.string, str.string);
return temp;
}

// Assign one string to another.
str_type str_type::operator=(str_type str) {
strcpy(string, str.string);
return *this;
}

listing 35
int main()
{
str_type a(«Hello «), b(«There»), c;

c = a + b;

c.show_str();

return 0;
}

listing 36
a = «this is currently wrong»;

listing 37
class str_type {
char string[80];
public:
str_type(char *str = «») { strcpy(string, str); }

str_type operator+(str_type str); // concatenate str_type objects
str_type operator+(char *str); /* concatenate str_type object
with a null-terminated string */

str_type operator=(str_type str); /* assign one str_type object
to another */
char *operator=(char *str); /* assign null-terminated string
to str_type object */

void show_str() { cout << string; }
};

listing 38
// Assign a null-terminated string to an str_type object.
str_type str_type::operator=(char *str)
{
str_type temp;

strcpy(string, str);
strcpy(temp.string, string);
return temp;
}

// Add a null-terminated string to an str_type object.
str_type str_type::operator+(char *str)
{
str_type temp;

strcpy(temp.string, string);
strcat(temp.string, str);
return temp;
}

listing 39
str_type a, b, c;
a = «hi there»; // assign a null-terminated string to an object

c = a + » George»; /* concatenate an object with a
null-terminated string */

listing 40
// Expanding the string type.
#include <iostream>
#include <cstring>
using namespace std;

class str_type {
char string[80];
public:
str_type(char *str = «») { strcpy(string, str); }

str_type operator+(str_type str);
str_type operator+(char *str);

str_type operator=(str_type str);
str_type operator=(char *str);

void show_str() { cout << string; }
} ;

str_type str_type::operator+(str_type str) {
str_type temp;

strcpy(temp.string, string);
strcat(temp.string, str.string);
return temp;
}

str_type str_type::operator=(str_type str) {
strcpy(string, str.string);
return *this;
}

str_type str_type::operator=(char *str)
{
str_type temp;

strcpy(string, str);
strcpy(temp.string, string);
return temp;
}

str_type str_type::operator+(char *str)
{
str_type temp;

strcpy(temp.string, string);
strcat(temp.string, str);
return temp;
}

int main()
{
str_type a(«Hello «), b(«There»), c;

c = a + b;

c.show_str();
cout << «\n»;

a = «to program in because»;
a.show_str();
cout << «\n»;

b = c = «C++ is fun»;

c = c+» «+a+» «+b;
c.show_str();

return 0;
}



listing 1
class road_vehicle {
int wheels;
int passengers;
public:
void set_wheels(int num) { wheels = num; }
int get_wheels() { return wheels; }
void set_pass(int num) { passengers = num; }
int get_pass() { return passengers; }
};

listing 2
class truck : public road_vehicle {
int cargo;
public:
void set_cargo(int size) { cargo = size; }
int get_cargo() { return cargo; }
void show();
};

listing 3
// Demonstrate inheritance.
#include <iostream>
using namespace std;

class road_vehicle {
int wheels;
int passengers;
public:
void set_wheels(int num) { wheels = num; }
int get_wheels() { return wheels; }
void set_pass(int num) { passengers = num; }
int get_pass() { return passengers; }
};

class truck : public road_vehicle {
int cargo;
public:
void set_cargo(int size) { cargo = size; }
int get_cargo() { return cargo; }
void show();
};

enum type {car, van, wagon};

class automobile : public road_vehicle {
enum type car_type;
public:
void set_type(type t) { car_type = t; }
enum type get_type() { return car_type; }
void show();
};

void truck::show()
{
cout << «wheels: » << get_wheels() << «\n»;
cout << «passengers: » << get_pass() << «\n»;
cout << «cargo capacity in cubic feet: » << cargo << «\n»;
}

void automobile::show()
{
cout << «wheels: » << get_wheels() << «\n»;
cout << «passengers: » << get_pass() << «\n»;
cout << «type: «;
switch(get_type()) {
case van: cout << «van\n»;
break;
case car: cout << «car\n»;
break;
case wagon: cout << «wagon\n»;
}
}

int main()
{
truck t1, t2;
automobile c;

t1.set_wheels(18);
t1.set_pass(2);
t1.set_cargo(3200);

t2.set_wheels(6);
t2.set_pass(3);
t2.set_cargo(1200);

t1.show();
cout << «\n»;
t2.show();
cout << «\n»;

c.set_wheels(4);
c.set_pass(6);
c.set_type(van);

c.show();

return 0;
}

listing 4
#include <iostream>
using namespace std;

class base {
int i, j;
public:
void set(int a, int b) { i = a; j = b; }
void show() { cout << i << » » << j << «\n»; }
};

class derived : public base {
int k;
public:
derived(int x) { k = x; }
void showk() { cout << k << «\n»; }
};

int main()
{
derived ob(3);

ob.set(1, 2); // access member of base
ob.show(); // access member of base

ob.showk(); // uses member of derived class

return 0;
}

listing 5
// This program won’t compile.
#include <iostream>
using namespace std;

class base {
int i, j;
public:
void set(int a, int b) { i = a; j = b; }
void show() { cout << i << » » << j << «\n»; }
};

// Public elements of base are private in derived.
class derived : private base {
int k;
public:
derived(int x) { k = x; }
void showk() { cout << k << «\n»; }
};

int main()
{
derived ob(3);

ob.set(1, 2); // Error, can’t access set()
ob.show(); // Error, can’t access show()

return 0;
}

listing 6
#include <iostream>
using namespace std;

class base {
protected:
int i, j; // private to base, but accessible to derived
public:
void set(int a, int b) { i = a; j = b; }
void show() { cout << i << » » << j << «\n»; }
};

class derived : public base {
int k;
public:
// derived may access base’s i and j
void setk() { k = i*j; }

void showk() { cout << k << «\n»; }
};

int main()
{
derived ob;

ob.set(2, 3); // OK, known to derived
ob.show(); // OK, known to derived

ob.setk();
ob.showk();

return 0;
}

listing 7
#include <iostream>
using namespace std;

class base {
protected:
int i, j;
public:
void set(int a, int b) { i = a; j = b; }
void show() { cout << i << » » << j << «\n»; }
};

// i and j inherited as protected.
class derived1 : public base {
int k;
public:
void setk() { k = i*j; } // legal
void showk() { cout << k << «\n»; }
};

// i and j inherited indirectly through derived1.
class derived2 : public derived1 {
int m;
public:
void setm() { m = i-j; } // legal
void showm() { cout << m << «\n»; }
};

int main()
{
derived1 ob1;
derived2 ob2;

ob1.set(2, 3);
ob1.show();
ob1.setk();
ob1.showk();

ob2.set(3, 4);
ob2.show();
ob2.setk();
ob2.setm();
ob2.showk();
ob2.showm();

return 0;
}

listing 8
// This program won’t compile.
#include <iostream>
using namespace std;

class base {
protected:
int i, j;
public:
void set(int a, int b) { i = a; j = b; }
void show() { cout << i << » » << j << «\n»; }
};

// Now, all elements of base are private in derived1.
class derived1 : private base {
int k;
public:
// This is legal because i and j are private to derived1.
void setk() { k = i*j; } // OK
void showk() { cout << k << «\n»; }
};

// Access to i, j, set(), and show() not inherited.
class derived2 : public derived1 {
int m;
public:
// Illegal because i and j are private to derived1.
void setm() { m = i-j; } // error
void showm() { cout << m << «\n»; }
};

int main()
{
derived1 ob1;
derived2 ob2;

ob1.set(1, 2); // Error, can’t use set()
ob1.show(); // Error, can’t use show()

ob2.set(3, 4); // Error, can’t use set()
ob2.show(); // error, can’t use show()

return 0;
}

listing 9
// Demonstrate inheriting a protected base class.
#include <iostream>
using namespace std;

class base {
int i;
protected:
int j;
public:
int k;
void seti(int a) { i = a; }
int geti() { return i; }
};

// Inherit base as protected.
class derived : protected base {
public:
void setj(int a) { j = a; } // j is protected here
void setk(int a) { k = a; } // k is also protected
int getj() { return j; }
int getk() { return k; }
};

int main()
{
derived ob;

/* This next line is illegal because seti() is
a protected member of derived, which makes it
inaccessible outside of derived. */
// ob.seti(10);

// cout << ob.geti(); // illegal — geti() is protected
// ob.k = 10; // also illegal because k is protected

// these next statements are OK
ob.setk(10);
cout << ob.getk() << ‘ ‘;
ob.setj(12);
cout << ob.getj() << ‘ ‘;

return 0;
}

listing 10
// An example of multiple base classes.
#include <iostream>
using namespace std;

class base1 {
protected:
int x;
public:
void showx() { cout << x << «\n»; }
};

class base2 {
protected:
int y;
public:
void showy() { cout << y << «\n»; }
};

// Inherit multiple base classes.
class derived: public base1, public base2 {
public:
void set(int i, int j) { x = i; y = j; }
};

int main()
{
derived ob;

ob.set(10, 20); // provided by derived
ob.showx(); // from base1
ob.showy(); // from base2

return 0;
}

listing 11
#include <iostream>
using namespace std;

class base {
public:
base() { cout << «Constructing base\n»; }
~base() { cout << «Destructing base\n»; }
};

class derived: public base {
public:
derived() { cout << «Constructing derived\n»; }
~derived() { cout << «Destructing derived\n»; }
};

int main()
{
derived ob;

// do nothing but construct and destruct ob

return 0;
}

listing 12
#include <iostream>
using namespace std;

class base {
public:
base() { cout << «Constructing base\n»; }
~base() { cout << «Destructing base\n»; }
};

class derived1 : public base {
public:
derived1() { cout << «Constructing derived1\n»; }
~derived1() { cout << «Destructing derived1\n»; }
};

class derived2: public derived1 {
public:
derived2() { cout << «Constructing derived2\n»; }
~derived2() { cout << «Destructing derived2\n»; }
};

int main()
{
derived2 ob;

// construct and destruct ob

return 0;
}

listing 13
#include <iostream>
using namespace std;

class base1 {
public:
base1() { cout << «Constructing base1\n»; }
~base1() { cout << «Destructing base1\n»; }
};

class base2 {
public:
base2() { cout << «Constructing base2\n»; }
~base2() { cout << «Destructing base2\n»; }
};

class derived: public base1, public base2 {
public:
derived() { cout << «Constructing derived\n»; }
~derived() { cout << «Destructing derived\n»; }
};

int main()
{
derived ob;

// construct and destruct ob

return 0;
}

listing 14
class derived: public base2, public base1 {

listing 15
#include <iostream>
using namespace std;

class base {
protected:
int i;
public:
base(int x) { i = x; cout << «Constructing base\n»; }
~base() { cout << «Destructing base\n»; }
};

class derived: public base {
int j;
public:
// derived uses x; y is passed along to base.
derived(int x, int y): base(y)
{ j = x; cout << «Constructing derived\n»; }

~derived() { cout << «Destructing derived\n»; }
void show() { cout << i << » » << j << «\n»; }
};

int main()
{
derived ob(3, 4);

ob.show(); // displays 4 3

return 0;
}

listing 16
#include <iostream>
using namespace std;

class base1 {
protected:
int i;
public:
base1(int x) { i = x; cout << «Constructing base1\n»; }
~base1() { cout << «Destructing base1\n»; }
};

class base2 {
protected:
int k;
public:
base2(int x) { k = x; cout << «Constructing base2\n»; }
~base2() { cout << «Destructing base2\n»; }
};

class derived: public base1, public base2 {
int j;
public:
derived(int x, int y, int z): base1(y), base2(z)
{ j = x; cout << «Constructing derived\n»; }

~derived() { cout << «Destructing derived\n»; }
void show() { cout << i << » » << j << » » << k << «\n»; }
};

int main()
{
derived ob(3, 4, 5);

ob.show(); // displays 4 3 5

return 0;
}

listing 17
#include <iostream>
using namespace std;

class base1 {
protected:
int i;
public:
base1(int x) { i=x; cout << «Constructing base1\n»; }
~base1() { cout << «Destructing base1\n»; }
};

class base2 {
protected:
int k;
public:
base2(int x) { k = x; cout << «Constructing base2\n»; }
~base2() { cout << «Destructing base2\n»; }
};

class derived: public base1, public base2 {
public:
/* Derived constructor uses no parameters,
but still must be declared as taking them to
pass them along to base classes.
*/
derived(int x, int y): base1(x), base2(y)
{ cout << «Constructing derived\n»; }

~derived() { cout << «Destructing derived\n»; }
void show() { cout << i << » » << k << «\n»; }
};

int main()
{
derived ob(3, 4);

ob.show(); // displays 3 4

return 0;
}

listing 18
class derived: public base {
int j;
public:
// derived uses both x and y and then passes them to base.
derived(int x, int y): base(x, y)
{ j = x*y; cout << «Constructing derived\n»; }
// …

listing 19
class base {
public:
int j; // public in base
};

// Inherit base as private.
class derived: private base {
public:

// here is access declaration
base::j; // make j public again
// …
};

listing 20
base::j;

listing 21
#include <iostream>
using namespace std;

class base {
int i; // private to base
public:
int j, k;
void seti(int x) { i = x; }
int geti() { return i; }
};

// Inherit base as private.
class derived: private base {
public:
/* The next three statements override
base’s inheritance as private
and restore j, seti() and geti() to
public access. */
base::j; // make j public again — but not k
base::seti; // make seti() public
base::geti; // make geti() public

// base::i; // illegal, you cannot elevate access

int a; // public
};

int main()
{
derived ob;

//ob.i = 10; // illegal because i is private in derived

ob.j = 20; // legal because j is made public in derived
//ob.k = 30; // illegal because k is private in derived

ob.a = 40; // legal because a is public in derived
ob.seti(10);

cout << ob.geti() << » » << ob.j << » » << ob.a;

return 0;
}

listing 22
// This program contains an error and will not compile.
#include <iostream>
using namespace std;

class base {
public:
int i;
};

// derived1 inherits base.
class derived1 : public base {
public:
int j;
};

// derived2 inherits base.
class derived2 : public base {
public:
int k;
};

/* derived3 inherits both derived1 and derived2.
This means that there are two copies of base
in derived3! */
class derived3 : public derived1, public derived2 {
public:
int sum;
};

int main()
{
derived3 ob;

ob.i = 10; // this is ambiguous; which i???
ob.j = 20;
ob.k = 30;

// i ambiguous here, too
ob.sum = ob.i + ob.j + ob.k;

// also ambiguous, which i?
cout << ob.i << » «;

cout << ob.j << » » << ob.k << » «;
cout << ob.sum;

return 0;
}

listing 23
ob.i = 20;

listing 24
// This program uses explicit scope resolution to select i.
#include <iostream>
using namespace std;

class base {
public:
int i;
};

// derived1 inherits base.
class derived1 : public base {
public:
int j;
};

// derived2 inherits base.
class derived2 : public base {
public:
int k;
};

/* derived3 inherits both derived1 and derived2.
This means that there are two copies of base
in derived3! */
class derived3 : public derived1, public derived2 {
public:
int sum;
};

int main()
{
derived3 ob;

ob.derived1::i = 10; // scope resolved, use derived1’s i
ob.j = 20;
ob.k = 30;

// scope resolved
ob.sum = ob.derived1::i + ob.j + ob.k;

// also resolved here
cout << ob.derived1::i << » «;

cout << ob.j << » » << ob.k << » «;
cout << ob.sum;

return 0;
}

listing 25
// This program uses virtual base classes.
#include <iostream>
using namespace std;

class base {
public:
int i;
};

// derived1 inherits base as virtual.
class derived1 : virtual public base {
public:
int j;
};

// derived2 inherits base as virtual.
class derived2 : virtual public base {
public:
int k;
};

/* derived3 inherits both derived1 and derived2.
This time, there is only one copy of base class. */
class derived3 : public derived1, public derived2 {
public:
int sum;
};

int main()
{
derived3 ob;

ob.i = 10; // now unambiguous
ob.j = 20;
ob.k = 30;

// unambiguous
ob.sum = ob.i + ob.j + ob.k;

// unambiguous
cout << ob.i << » «;

cout << ob.j << » » << ob.k << » «;
cout << ob.sum;

return 0;
}

listing 26
// Define a class of type derived1.
derived1 myclass;

myclass.i = 88;



listing 1
B_class *p; // pointer to object of type B_class
B_class B_ob; // object of type B_class
D_class D_ob; // object of type D_class

listing 2
p = &B_ob; // p points to object of type B_class
p = &D_ob; /* p points to object of type D_class,
which is an object derived from B_class. */

listing 3
// Using base pointers on derived class objects.
#include <iostream>
#include <cstring> // for older compilers, use <string.h>
using namespace std;

class B_class {
char author[80];
public:
void put_author(char *s) { strcpy(author, s); }
void show_author() { cout << author << «\n»; }
} ;

class D_class : public B_class {
char title[80];
public:
void put_title(char *num) {
strcpy(title, num);
}
void show_title() {
cout << «Title: «;
cout << title << «\n»;
}
};

int main()
{
B_class *p;
B_class B_ob;

D_class *dp;
D_class D_ob;

p = &B_ob; // address of base

// Access B_class via pointer.
p->put_author(«Tom Clancy»);

// Access D_class via base pointer.
p = &D_ob;
p->put_author(«William Shakespeare»);

// Show that each author went into proper object.
B_ob.show_author();
D_ob.show_author();
cout << «\n»;

/* Since put_title() and show_title() are not part
of the base class, they are not accessible via
the base pointer p and must be accessed either
directly, or, as shown here, through a pointer to the
derived type.
*/
dp = &D_ob;
dp->put_title(«The Tempest»);
p->show_author(); // either p or dp can be used here.
dp->show_title( );

return 0;
}

listing 4
((D_class *)p)->show_title();

listing 5
// A short example that uses virtual functions.
#include <iostream>
using namespace std;

class base {
public:
virtual void who() { // specify a virtual
cout << «Base\n»;
}
};

class first_d : public base {
public:
void who() { // redefine who() relative to first_d
cout << «First derivation\n»;
}
};

class second_d : public base {
public:
void who() { // redefine who() relative to second_d
cout << «Second derivation\n»;
}
};

int main()
{
base base_obj;
base *p;
first_d first_obj;
second_d second_obj;

p = &base_obj;
p->who(); // access base’s who

p = &first_obj;
p->who(); // access first_d’s who

p = &second_obj;
p->who(); // access second_d’s who

return 0;
}

listing 6
first_obj.who();

listing 7
// Derive from first_d, not base.
class second_d : public first_d {
public:
void who() { // define who() relative to second_d
cout << «Second derivation\n»;
}
};

listing 8
#include <iostream>
using namespace std;

class base {
public:
virtual void who() {
cout << «Base\n»;
}
};

class first_d : public base {
public:
void who() {
cout << «First derivation\n»;
}
};

class second_d : public base {
// who() not defined
};

int main()
{
base base_obj;
base *p;
first_d first_obj;
second_d second_obj;

p = &base_obj;
p->who(); // access base’s who()

p = &first_obj;
p->who(); // access first_d’s who()

p = &second_obj;
p->who(); /* access base’s who() because
second_d does not redefine it */

return 0;
}

listing 9
#include <iostream>
using namespace std;

class base {
public:
virtual void who() {
cout << «Base\n»;
}
};

class first_d : public base {
public:
void who() {
cout << «First derivation\n»;
}
};

// second_d now inherited first_d — not base.
class second_d : public first_d {
// who() not defined
};

int main()
{
base base_obj;
base *p;
first_d first_obj;
second_d second_obj;

p = &base_obj;
p->who(); // access base’s who()

p = &first_obj;
p->who(); // access first_d’s who()

p = &second_obj;
p->who(); /* access first_d’s who() because
second_d does not redefine it */

return 0;
}

listing 10
#include <iostream>
using namespace std;

class figure {
protected:
double x, y;
public:
void set_dim(double i, double j) {
x = i;
y = j;
}
virtual void show_area() {
cout << «No area computation defined «;
cout << «for this class.\n»;
}
} ;

class triangle : public figure {
public:
void show_area() {
cout << «Triangle with height «;
cout << x << » and base » << y;
cout << » has an area of «;
cout << x * 0.5 * y << «.\n»;
}
};

class rectangle : public figure {
public:
void show_area() {
cout << «Rectangle with dimensions «;
cout << x << «x» << y;
cout << » has an area of «;
cout << x * y << «.\n»;
}
};

int main()
{
figure *p; // create a pointer to base type

triangle t; // create objects of derived types
rectangle s;

p = &t;
p->set_dim(10.0, 5.0);
p->show_area();

p = &s;
p->set_dim(10.0, 5.0);
p->show_area();

return 0;
}

listing 11
class circle : public figure {
public:
void show_area() {
cout << «Circle with radius «;
cout << x;
cout << » has an area of «;
cout << 3.14 * x * x;
}
};

listing 12
#include <iostream>
using namespace std;

class figure {
protected:
double x, y;
public:
void set_dim(double i, double j=0) {
x = i;
y = j;
}
virtual void show_area() {
cout << «No area computation defined «;
cout << «for this class.\n»;
}
} ;

class triangle : public figure {
public:
void show_area() {
cout << «Triangle with height «;
cout << x << » and base » << y;
cout << » has an area of «;
cout << x * 0.5 * y << «.\n»;
}
};

class rectangle : public figure {
public:
void show_area() {
cout << «Rectangle with dimensions «;
cout << x << «x» << y;
cout << » has an area of «;
cout << x * y << «.\n»;
}
};

class circle : public figure {
public:
void show_area() {
cout << «Circle with radius «;
cout << x;
cout << » has an area of «;
cout << 3.14 * x * x << «.\n»;
}
} ;

int main()
{
figure *p; // create a pointer to base type

triangle t; // create objects of derived types
rectangle s;
circle c;

p = &t;
p->set_dim(10.0, 5.0);
p->show_area();

p = &s;
p->set_dim(10.0, 5.0);
p->show_area();

p = &c;
p->set_dim(9.0);
p->show_area();

return 0;
}

listing 13
class figure {
double x, y;
public:
void set_dim(double i, double j=0) {
x = i;
y = j;
}
virtual void show_area() = 0; // pure
};

listing 14
/*
This program will not compile because the class
circle does not override show_area().
*/
#include <iostream>
using namespace std;

class figure {
protected:
double x, y;
public:
void set_dim(double i, double j) {
x = i;
y = j;
}
virtual void show_area() = 0; // pure
} ;

class triangle : public figure {
public:
void show_area() {
cout << «Triangle with height «;
cout << x << » and base » << y;
cout << » has an area of «;
cout << x * 0.5 * y << «.\n»;
}
};

class rectangle : public figure {
public:
void show_area() {
cout << «Rectangle with dimensions «;
cout << x << «x» << y;
cout << » has an area of «;
cout << x * y << «.\n»;
}
};

class circle : public figure {
// no definition of show_area() will cause an error
};

int main()
{
figure *p; // create a pointer to base type

triangle t; // create objects of derived types
rectangle s;

circle c; // Illegal — can’t create!

p = &t;
p->set_dim(10.0, 5.0);
p->show_area();

p = &s;
p->set_dim(10.0, 5.0);
p->show_area();

return 0;
}



listing 1
// Function template example.
#include <iostream>
using namespace std;

// This is a function template.
template <class X> void swapargs(X &a, X &b)
{
X temp;

temp = a;
a = b;
b = temp;
}

int main()
{
int i=10, j=20;
double x=10.1, y=23.3;
char a=’x’, b=’z’;

cout << «Original i, j: » << i << ‘ ‘ << j << ‘\n’;
cout << «Original x, y: » << x << ‘ ‘ << y << ‘\n’;
cout << «Original a, b: » << a << ‘ ‘ << b << ‘\n’;

swapargs(i, j); // swap integers
swapargs(x, y); // swap floats
swapargs(a, b); // swap chars

cout << «Swapped i, j: » << i << ‘ ‘ << j << ‘\n’;
cout << «Swapped x, y: » << x << ‘ ‘ << y << ‘\n’;
cout << «Swapped a, b: » << a << ‘ ‘ << b << ‘\n’;

return 0;
}

listing 2
template <class X> void swapargs(X &a, X &b)

listing 3
template <class X>
void swapargs(X &a, X &b)
{
X temp;

temp = a;
a = b;
b = temp;
}

listing 4
// This will not compile.
template <class X>
int i; // this is an error
void swapargs(X &a, X &b)
{
X temp;

temp = a;
a = b;
b = temp;
}

listing 5
#include <iostream>
using namespace std;

template <class type1, class type2>
void myfunc(type1 x, type2 y)
{
cout << x << ‘ ‘ << y << ‘\n’;
}

int main()
{
myfunc(10, «hi»);

myfunc(0.23, 10L);

return 0;
}

listing 6
// Overriding a template function.
#include <iostream>
using namespace std;

template <class X> void swapargs(X &a, X &b)
{
X temp;

temp = a;
a = b;
b = temp;
cout << «Inside template swapargs.\n»;
}

// This overrides the generic version of swapargs() for ints.
void swapargs(int &a, int &b)
{
int temp;

temp = a;
a = b;
b = temp;
cout << «Inside swapargs int specialization.\n»;
}

int main()
{
int i=10, j=20;
double x=10.1, y=23.3;
char a=’x’, b=’z’;

cout << «Original i, j: » << i << ‘ ‘ << j << ‘\n’;
cout << «Original x, y: » << x << ‘ ‘ << y << ‘\n’;
cout << «Original a, b: » << a << ‘ ‘ << b << ‘\n’;

swapargs(i, j); // calls explicitly overloaded swapargs()
swapargs(x, y); // calls generic swapargs()
swapargs(a, b); // calls generic swapargs()

cout << «Swapped i, j: » << i << ‘ ‘ << j << ‘\n’;
cout << «Swapped x, y: » << x << ‘ ‘ << y << ‘\n’;
cout << «Swapped a, b: » << a << ‘ ‘ << b << ‘\n’;

return 0;
}
listing 7
// Use new-style specialization syntax.
template<> void swapargs<int>(int &a, int &b)
{
int temp;

temp = a;
a = b;
b = temp;
cout << «Inside swapargs int specialization.\n»;

}

listing 8
// Overload a function template declaration.
#include <iostream>
using namespace std;

// First version of f() template.
template <class X> void f(X a)
{
cout << «Inside f(X a)\n»;
}

// Second version of f() template.
template <class X, class Y> void f(X a, Y b)
{
cout << «Inside f(X a, Y b)\n»;
}

int main()
{
f(10); // calls f(X)
f(10, 20); // calls f(X, Y)

return 0;
}
listing 9
// Using standard parameters in a template function.
#include <iostream>
using namespace std;

// Display data specified number of times.
template<class X> void repeat(X data, int times)
{
do {
cout << data << «\n»;
times—;
} while(times);
}

int main()
{
repeat(«This is a test», 3);
repeat(100, 5);
repeat(99.0/2, 4);

return 0;
}

listing 10
void outdata(int i)
{
cout << i;
}

void outdata(double d)
{
cout << d * 3.1416;
}

listing 11
// A generic version of myabs().
#include <iostream>
using namespace std;

template <class X> X myabs(X val)
{
return val < 0 ? -val : val;
}

int main()
{
cout << myabs(-10) << ‘\n’; // integer abs

cout << myabs(-10.0) << ‘\n’; // double abs

cout << myabs(-10L) << ‘\n’; // long abs

cout << myabs(-10.0F) << ‘\n’; // float abs

return 0;
}

listing 12
// Demonstrate a generic queue class.
#include <iostream>
using namespace std;

const int SIZE=100;

// This creates the generic class queue.
template <class QType> class queue {
QType q[SIZE];
int sloc, rloc;
public:
queue() { sloc = rloc = 0; }
void qput(QType i);
QType qget();
};

// Put an object into the queue.
template <class QType> void queue<QType>::qput(QType i)
{
if(sloc==SIZE) {
cout << «Queue is full.\n»;
return;
}
sloc++;
q[sloc] = i;
}

// Get an object from the queue.
template <class QType> QType queue<QType>::qget()
{
if(rloc == sloc) {
cout << «Queue Underflow.\n»;
return 0;
}
rloc++;
return q[rloc];
}

int main()
{
queue<int> a, b; // create two integer queues

a.qput(10);
b.qput(19);

a.qput(20);
b.qput(1);

cout << a.qget() << » «;
cout << a.qget() << » «;
cout << b.qget() << » «;
cout << b.qget() << «\n»;

queue<double> c, d; // create two double queues

c.qput(10.12);
d.qput(19.99);

c.qput(-20.0);
d.qput(0.986);

cout << c.qget() << » «;
cout << c.qget() << » «;
cout << d.qget() << » «;
cout << d.qget() << «\n»;

return 0;
}

listing 13
queue<int> a, b;
queue<double> c, d;

listing 14
queue<char *> chrptrQ;

listing 15
struct addr {
char name[40];
char street[40];
char city[30];
char state[3];
char zip[12];
};

listing 16
queue<addr> obj;

listing 17
/* This example uses two generic data types in a
class definition.
*/
#include <iostream>
using namespace std;

template <class Type1, class Type2> class myclass
{
Type1 i;
Type2 j;
public:
myclass(Type1 a, Type2 b) { i = a; j = b; }
void show() { cout << i << ‘ ‘ << j << ‘\n’; }
};

int main()
{
myclass<int, double> ob1(10, 0.23);
myclass<char, char *> ob2(‘X’, «This is a test»);

ob1.show(); // show int, double
ob2.show(); // show char, char *

return 0;
}

listing 18
// A generic safe array example.
#include <iostream>
#include <cstdlib> // for older compilers, use <stdlib.h>
using namespace std;

const int SIZE = 10;

template <class AType> class atype {
AType a[SIZE];
public:
atype() {
register int i;
for(i=0; i<SIZE; i++) a[i] = i;
}
AType &operator[](int i);
};

// Provide range checking for atype.
template <class AType> AType &atype<AType>::operator[](int i)
{
if(i<0 || i> SIZE-1) {
cout << «\nIndex value of «;
cout << i << » is out-of-bounds.\n»;
exit(1);
}
return a[i];
}

int main()
{
atype<int> intob; // integer array
atype<double> doubleob; // double array

int i;

cout << «Integer array: «;
for(i=0; i<SIZE; i++) intob[i] = i;
for(i=0; i<SIZE; i++) cout << intob[i] << » «;
cout << ‘\n’;

cout << «Double array: «;
for(i=0; i<SIZE; i++) doubleob[i] = (double) i/3;
for(i=0; i<SIZE; i++) cout << doubleob[i] << » «;
cout << ‘\n’;

intob[12] = 100; // generates runtime error

return 0;
}

listing 19
// Demonstrate non-type template arguments.
#include <iostream>
#include <cstdlib> // for older compilers, use <stdlib.h>
using namespace std;

// Here, int size is a non-type agument.
template <class AType, int size> class atype {
AType a[size]; // length of array is passed in size
public:
atype() {
register int i;
for(i=0; i<size; i++) a[i] = i;
}
AType &operator[](int i);
};

// Provide range checking for atype.
template <class AType, int size>
AType &atype<AType, size>::operator[](int i)
{
if(i<0 || i> size-1) {
cout << «\nIndex value of «;
cout << i << » is out-of-bounds.\n»;
exit(1);
}
return a[i];
}

int main()
{
atype<int, 10> intob; // integer array of size 10
atype<double, 15> doubleob; // double array of size 15

int i;

cout << «Integer array: «;
for(i=0; i<10; i++) intob[i] = i;
for(i=0; i<10; i++) cout << intob[i] << » «;
cout << ‘\n’;

cout << «Double array: «;
for(i=0; i<15; i++) doubleob[i] = (double) i/3;
for(i=0; i<15; i++) cout << doubleob[i] << » «;
cout << ‘\n’;

intob[12] = 100; // generates runtime error

return 0;
}

listing 20
size = 10; // Error

listing 21
template <class X=int> class myclass { //…

listing 22
// Demonstrate default template arguments.
#include <iostream>
#include <cstdlib> // for older compilers, use <stdlib.h>
using namespace std;

// Here, AType defaults to int and size defaults to 10.
template <class AType=int, int size=10> class atype {
AType a[size]; // size of array is passed in size
public:
atype() {
register int i;
for(i=0; i<size; i++) a[i] = i;
}
AType &operator[](int i);
};

// Provide range checking for atype.
template <class AType, int size>
AType &atype<AType, size>::operator[](int i)
{
if(i<0 || i> size-1) {
cout << «\nIndex value of «;
cout << i << » is out-of-bounds.\n»;
exit(1);
}
return a[i];
}

int main()
{
atype<int, 100> intarray; // integer array, size 100
atype<double> doublearray; // double array, default size
atype<> defarray; // default to int array of size 10

int i;

cout << «int array: «;
for(i=0; i<100; i++) intarray[i] = i;
for(i=0; i<100; i++) cout << intarray[i] << » «;
cout << ‘\n’;

cout << «double array: «;
for(i=0; i<10; i++) doublearray[i] = (double) i/3;
for(i=0; i<10; i++) cout << doublearray[i] << » «;
cout << ‘\n’;

cout << «defarray array: «;
for(i=0; i<10; i++) defarray[i] = i;
for(i=0; i<10; i++) cout << defarray[i] << » «;
cout << ‘\n’;

return 0;
}
listing 23
template <class AType=int, int size=10> class atype {

listing 24
// Demonstrate class specialization.
#include <iostream>
using namespace std;

template <class T> class myclass {
T x;
public:
myclass(T a) {
cout << «Inside generic myclass\n»;
x = a;
}
T getx() { return x; }
};

// Explicit specialization for int.
template <> class myclass<int> {
int x;
public:
myclass(int a) {
cout << «Inside myclass<int> specialization\n»;
x = a * a;
}
int getx() { return x; }
};

int main()
{
myclass<double> d(10.1);
cout << «double: » << d.getx() << «\n\n»;

myclass<int> i(5);
cout << «int: » << i.getx() << «\n»;

return 0;
}

listing 25
template <> class myclass<int> {


listing 1
// A simple exception handling example.
#include <iostream>
using namespace std;

int main()
{
cout << «start\n»;

try { // start a try block
cout << «Inside try block\n»;
throw 99; // throw an error
cout << «This will not execute»;
}
catch (int i) { // catch an error
cout << «Caught an exception — value is: «;
cout << i << «\n»;
}

cout << «end»;

return 0;
}

listing 2
// This example will not work.
#include <iostream>
using namespace std;

int main()
{
cout << «start\n»;

try { // start a try block
cout << «Inside try block\n»;
throw 99; // throw an error
cout << «This will not execute»;
}
catch (double i) { // won’t work for an int exception
cout << «Caught an exception — value is: «;
cout << i << «\n»;
}

cout << «end»;

return 0;
}

listing 3
/* Throwing an exception from a function called
from within a try block.
*/
#include <iostream>
using namespace std;

void Xtest(int test)
{
cout << «Inside Xtest, test is: » << test << «\n»;
if(test) throw test;
}

int main()
{
cout << «start\n»;

try { // start a try block
cout << «Inside try block\n»;
Xtest(0);
Xtest(1);
Xtest(2);
}
catch (int i) { // catch an error
cout << «Caught an exception — value is: «;
cout << i << «\n»;
}

cout << «end»;

return 0;
}

listing 4
#include <iostream>
using namespace std;

// A try/catch is reset each time a function is entered.
void Xhandler(int test)
{
try{
if(test) throw test;
}
catch(int i) {
cout << «Caught One! Ex. #: » << i << ‘\n’;
}
}

int main()
{
cout << «start\n»;

Xhandler(1);
Xhandler(2);
Xhandler(0);
Xhandler(3);

cout << «end»;

return 0;
}

listing 5
// Use an exception class.
#include <iostream>
#include <cstring>
using namespace std;

class MyException {
public:
char str_what[80];

MyException() { *str_what = 0; }

MyException(char *s) {
strcpy(str_what, s);
}
};

int main()
{
int a, b;

try {
cout << «Enter numerator and denominator: «;
cin >> a >> b;
if(!b)
throw MyException(«Cannot divide by zero!»);
else
cout << «Quotient is » << a/b << «\n»;
}
catch (MyException e) { // catch an error
cout << e.str_what << «\n»;
}

return 0;
}

listing 6
#include <iostream>
using namespace std;

// Different types of exceptions can be caught.
void Xhandler(int test)
{
try{
if(test) throw test;
else throw «Value is zero»;
}
catch(int i) {
cout << «Caught One! Ex. #: » << i << ‘\n’;
}
catch(char *str) {
cout << «Caught a string: «;
cout << str << ‘\n’;
}
}

int main()
{
cout << «start\n»;

Xhandler(1);
Xhandler(2);
Xhandler(0);
Xhandler(3);

cout << «end»;

return 0;
}

listing 7
// Catching derived classes.
#include <iostream>
using namespace std;

class B {
};

class D: public B {
};

int main()
{
D derived;

try {
throw derived;
}
catch(B b) {
cout << «Caught a base class.\n»;
}
catch(D d) {
cout << «This won’t execute.\n»;
}

return 0;
}

listing 8
// This example catches all exceptions.
#include <iostream>
using namespace std;

void Xhandler(int test)
{
try{
if(test==0) throw test; // throw int
if(test==1) throw ‘a’; // throw char
if(test==2) throw 123.23; // throw double
}
catch(…) { // catch all exceptions
cout << «Caught One!\n»;
}
}

int main()
{
cout << «start\n»;

Xhandler(0);
Xhandler(1);
Xhandler(2);

cout << «end»;

return 0;
}

listing 9
// This example uses catch(…) as a default.
#include <iostream>
using namespace std;

void Xhandler(int test)
{
try{
if(test==0) throw test; // throw int
if(test==1) throw ‘a’; // throw char
if(test==2) throw 123.23; // throw double
}
catch(int i) { // catch an int exception
cout << «Caught » << i << ‘\n’;
}
catch(…) { // catch all other exceptions
cout << «Caught One!\n»;
}
}

int main()
{
cout << «start\n»;

Xhandler(0);
Xhandler(1);
Xhandler(2);

cout << «end»;

return 0;
}

listing 10
// Restricting function throw types.
#include <iostream>
using namespace std;

// This function can only throw ints, chars, and doubles.
void Xhandler(int test) throw(int, char, double)
{
if(test==0) throw test; // throw int
if(test==1) throw ‘a’; // throw char
if(test==2) throw 123.23; // throw double
}

int main()
{
cout << «start\n»;

try{
Xhandler(0); // also, try passing 1 and 2 to Xhandler()
}
catch(int i) {
cout << «Caught int\n»;
}
catch(char c) {
cout << «Caught char\n»;
}
catch(double d) {
cout << «Caught double\n»;
}

cout << «end»;

return 0;
}

listing 11
// This function can throw NO exceptions!
void Xhandler(int test) throw()
{
/* The following statements no longer work. Instead,
they will cause an abnormal program termination. */
if(test==0) throw test;
if(test==1) throw ‘a’;
if(test==2) throw 123.23;
}

listing 12
// Example of «rethrowing» an exception.
#include <iostream>
using namespace std;

void Xhandler()
{
try {
throw «hello»; // throw a char *
}
catch(char *) { // catch a char *
cout << «Caught char * inside Xhandler\n»;
throw ; // rethrow char * out of function
}
}

int main()
{
cout << «start\n»;

try{
Xhandler();
}
catch(char *) {
cout << «Caught char * inside main\n»;
}

cout << «end»;

return 0;
}

listing 13
// Handle exceptions thrown by new.
#include <iostream>
#include <new>
using namespace std;

int main()
{
int *p, i;

try {
p = new int[32]; // allocate memory for 32-element int array
} catch (bad_alloc xa) {
cout << «Allocation failure.\n»;
return 1;
}

for(i=0; i<32; i++) p[i] = i;

for(i=0; i<32; i++) cout << p[i] << » «;

delete [] p; // free the memory

return 0;
}

listing 14
// Demonstrate nothrow version of new.
#include <iostream>
#include <new>
using namespace std;

int main()
{
int *p, i;

p = new(nothrow) int[32]; // use nothrow option
if(!p) {
cout << «Allocation failure.\n»;
return 1;
}

for(i=0; i<32; i++) p[i] = i;

for(i=0; i<32; i++) cout << p[i] << » «;

delete [] p; // free the memory

return 0;
}

listing 15
// Allocate an object.
void *operator new(size_t size)
{
/* Perform allocation. Throw bad_alloc on failure.
Constructor called automatically. */
return pointer_to_memory;
}

// Delete an object.
void operator delete(void *p)
{
/* Free memory pointed to by p.
Destructor called automatically. */
}

listing 16
// Allocate an array of objects.
void *operator new[](size_t size)
{
/* Perform allocation. Throw bad_alloc exception on failure.
Each constructor called automatically. */
return pointer_to_memory;
}

// Delete an array of objects.
void operator delete[](void *p)
{
/* Free memory pointed to by p.
Destructor for each element automatically called. */
}

listing 17
// Demonstrate overloaded new and delete.
#include <iostream>
#include <new>
#include <cstdlib>
using namespace std;

class three_d {
int x, y, z; // 3-D coordinates
public:
three_d() {
x = y = z = 0;
cout << «Constructing 0, 0, 0\n»;
}
three_d(int i, int j, int k) {
x = i; y = j; z = k;
cout << «Constructing » << i << «, «;
cout << j << «, » << k;
cout << ‘\n’;
}
~three_d( ) { cout << «Destructing\n»; }
void *operator new(size_t size);
void *operator new[](size_t size);
void operator delete(void *p);
void operator delete[](void *p);
void show() ;
};

// new overloaded relative to three_d.
void *three_d::operator new(size_t size)
{
void *p;

cout << «Allocating three_d object.\n»;
p = malloc(size);

// throw an exception on failure
if(!p) {
bad_alloc ba;
throw ba;
}
return p;
}
// new overloaded relative to arrays of three_d.
void *three_d::operator new[](size_t size)
{
void *p;

cout << «Allocating array of three_d objects.\n»;

// throw an exception on failure
p = malloc(size);
if(!p) {
bad_alloc ba;
throw ba;
}
return p;
}

// delete overloaded relative to three_d.
void three_d::operator delete(void *p)
{
cout << «Deleting three_d object.\n»;
free(p);
}

// delete overloaded relative to arrays of three_d.
void three_d::operator delete[](void *p)
{
cout << «Deleting array of three_d objects.\n»;
free(p);
}

// Show X, Y, Z coordinates.
void three_d::show()
{
cout << x << «, «;
cout << y << «, «;
cout << z << «\n»;
}

int main()
{
three_d *p1, *p2;

try {
p1 = new three_d[3]; // allocate array
p2 = new three_d(5, 6, 7); // allocate object
} catch (bad_alloc ba) {
cout << «Allocation error.\n»;
return 1;
}

p1[1].show();
p2->show();

delete [] p1; // delete array
delete p2; // delete object

return 0;
}

listing 18
int *f = new int; // uses default new

listing 19
// Nothrow version of new.
void *operator new(size_t size, const nothrow_t &n)
{
// Perform allocation.
if(success) return pointer_to_memory;
else return 0;
}

// Nothrow version of new for arrays.
void *operator new[](size_t size, const nothrow_t &n)
{
// Perform allocation.
if(success) return pointer_to_memory;
else return 0;
}

// Nothrow version of delete.
void operator delete(void *p, const nothrow_t &n)
{
// free memory
}

// Nothrow version of delete for arrays.
void operator delete[](void *p, const nothrow_t &n)
{
// free memory
}


listing 1
class three_d {
public:
int x, y, z; // 3-D coordinates
three_d(int a, int b, int c) { x = a; y = b; z = c; }
};

listing 2
// Display X, Y, Z coordinates — three_d inserter.
ostream &operator<<(ostream &stream, three_d obj)
{
stream << obj.x << «, «;
stream << obj.y << «, «;
stream << obj.z << «\n»;
return stream; // return the stream
}

listing 3
// Demonstrate a custom inserter.
#include <iostream>
using namespace std;

class three_d {
public:
int x, y, z; // 3-D coordinates
three_d(int a, int b, int c) { x = a; y = b; z = c; }
} ;

// Display X, Y, Z coordinates — three_d inserter.
ostream &operator<<(ostream &stream, three_d obj)
{
stream << obj.x << «, «;
stream << obj.y << «, «;
stream << obj.z << «\n»;
return stream; // return the stream
}

int main()
{
three_d a(1, 2, 3), b(3, 4, 5), c(5, 6, 7);

cout << a << b << c;

return 0;
}

listing 4
ostream &operator<<(ostream &stream, class_type obj)
{
// class specific code goes here
return stream; // return the stream
}

listing 5
// Limited version — don’t use.
ostream &operator<<(ostream &stream, three_d obj)
{
cout << obj.x << «, «;
cout << obj.y << «, «;
cout << obj.z << «\n»;
return stream; // return the stream
}

listing 6
// Use a friend to overload <<.
#include <iostream>
using namespace std;

class three_d {
int x, y, z; // 3-D coordinates — now private
public:
three_d(int a, int b, int c) { x = a; y = b; z = c; }
friend ostream &operator<<(ostream &stream, three_d obj);
} ;

// Display X, Y, Z coordinates — three_d inserter.
ostream &operator<<(ostream &stream, three_d obj)
{
stream << obj.x << «, «;
stream << obj.y << «, «;
stream << obj.z << «\n»;
return stream; // return the stream
}

int main()
{
three_d a(1, 2, 3), b(3, 4, 5), c(5, 6, 7);

cout << a << b << c;

return 0;
}

listing 7
// Get three-dimensional values — three_d extractor.
istream &operator>>(istream &stream, three_d &obj)
{
cout << «Enter X,Y,Z values: «;
stream >> obj.x >> obj.y >> obj.z;
return stream;
}

listing 8
istream &operator>>(istream &stream, object_type &obj)
{
// put your extractor code here
return stream;
}

listing 9
// Demonstrate a custom extractor.
#include <iostream>
using namespace std;

class three_d {
int x, y, z; // 3-D coordinates
public:
three_d(int a, int b, int c) { x = a; y = b; z = c; }
friend ostream &operator<<(ostream &stream, three_d obj);
friend istream &operator>>(istream &stream, three_d &obj);
} ;

// Display X, Y, Z coordinates — three_d inserter.
ostream &operator<<(ostream &stream, three_d obj)
{
stream << obj.x << «, «;
stream << obj.y << «, «;
stream << obj.z << «\n»;
return stream; // return the stream
}

// Get three dimensional values — three_d extractor.
istream &operator>>(istream &stream, three_d &obj)
{
cout << «Enter X,Y,Z values: «;
stream >> obj.x >> obj.y >> obj.z;
return stream;
}

int main()
{
three_d a(1, 2, 3);

cout << a;

cin >> a;
cout << a;

return 0;
}

listing 10
struct my_struct {
int count;
char s[80];
double balance;
} cust;

listing 11
stream.setf(ios::showbase);

listing 12
#include <iostream>
using namespace std;

int main()
{
cout.setf(ios::showpos);
cout.setf(ios::scientific);
cout << 123 << » » << 123.23 << » «;

return 0;
}

listing 13
cout.setf(ios::scientific | ios::showpos);

listing 14
#include <iostream>
using namespace std;

void showflags(ios::fmtflags f);

int main()
{
ios::fmtflags f;

f = cout.flags();

showflags(f);
cout.setf(ios::showpos);
cout.setf(ios::scientific);

f = cout.flags();
showflags(f);

cout.unsetf(ios::scientific);

f = cout.flags();
showflags(f);

return 0;
}

void showflags(ios::fmtflags f)
{
long i;

for(i=0x4000; i; i = i >> 1)
if(i & f) cout << «1 «;
else cout << «0 «;

cout << «\n»;
}

listing 15
#include <iostream>
using namespace std;

int main()
{
cout.setf(ios::showpos);
cout.setf(ios::scientific);
cout << 123 << » » << 123.23 << «\n»;

cout.precision(2); // two digits after decimal point
cout.width(10); // in a field of 10 characters
cout << 123 << » «;
cout.width(10); // set width to 10
cout << 123.23 << «\n»;

cout.fill(‘#’); // fill using #
cout.width(10); // in a field of 10 characters
cout << 123 << » «;
cout.width(10); // set width to 10
cout << 123.23;

return 0;
}

listing 16
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
cout << setprecision(2) << 1000.243 << endl;
cout << setw(20) << «Hello there.»;

return 0;
}

listing 17
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
cout << setiosflags(ios::showpos);
cout << setiosflags(ios::scientific);
cout << 123 << » » << 123.23;

return 0;
}

listing 18
#include <iostream>
using namespace std;

int main()
{
char s[80];

cin >> ws >> s;
cout << s;

return 0;
}

listing 19
#include <iostream>
#include <iomanip>
using namespace std;

ostream &setup(ostream &stream)
{
stream.setf(ios::left);
stream << setw(10) << setfill(‘$’);
return stream;
}

int main()
{
cout << 10 << » » << setup << 10;

return 0;
}

listing 20
istream &manip_name(istream &stream)
{
// your code here

return stream;
}

listing 21
#include <iostream>
#include <iomanip>
using namespace std;

istream &prompt(istream &stream)
{
cin >> hex;
cout << «Enter number using hex format: «;

return stream;
}

int main()
{
int i;

cin >> prompt >> i;
cout << i;

return 0;
}

listing 22
ifstream in; // input
ofstream out; // output
fstream both; // input and output

listing 23
ofstream out;
out.open(«test»);

listing 24
if(!mystream) {
cout << «Cannot open file.\n»;
// handle error
}

listing 25
if(!mystream.is_open()) {
cout << «File is not open.\n»;
// …

listing 26
ifstream mystream(«myfile»); // open file for input

listing 27
mystream.close();

listing 28
// Write to file.
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
ofstream out(«test»);
if(!out) {
cout << «Cannot open file.\n»;
return 1;
}

out << 10 << » » << 123.23 << «\n»;
out << «This is a short text file.»;

out.close();

return 0;
}

listing 29
// Read from file.
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
char ch;
int i;
float f;
char str[80];

ifstream in(«test»);
if(!in) {
cout << «Cannot open file.\n»;
return 1;
}

in >> i;
in >> f;
in >> ch;
in >> str;

cout << i << » » << f << » » << ch << «\n»;
cout << str;

in.close();
return 0;
}

listing 30
// Display a file using get().
#include <iostream>
#include <fstream>
using namespace std;

int main(int argc, char *argv[])
{
char ch;

if(argc!=2) {
cout << «Usage: PR <filename>\n»;
return 1;
}

ifstream in(argv[1], ios::in | ios::binary);
if(!in) {
cout << «Cannot open file.\n»;
return 1;
}

while(in) { // in will be false when eof is reached
in.get(ch);
if(in) cout << ch;
}

in.close();

return 0;
}

listing 31
while(in.get(ch))
cout << ch;

listing 32
// Use put() to write to a file.
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
char *p = «hello there»;

ofstream out(«test», ios::out | ios::binary);
if(!out) {
cout << «Cannot open file.\n»;
return 1;
}

while(*p) out.put(*p++);

out.close();

return 0;
}

listing 33
// Use read() and write().
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
int n[5] = {1, 2, 3, 4, 5};
register int i;

ofstream out(«test», ios::out | ios::binary);
if(!out) {
cout << «Cannot open file.\n»;
return 1;
}

out.write((char *) &n, sizeof n);

out.close();

for(i=0; i<5; i++) // clear array
n[i] = 0;

ifstream in(«test», ios::in | ios::binary);
if(!in) {
cout << «Cannot open file.\n»;
return 1;
}

in.read((char *) &n, sizeof n);

for(i=0; i<5; i++) // show values read from file
cout << n[i] << » «;

in.close();

return 0;
}

listing 34
// Detect end-of-file using eof().
#include <iostream>
#include <fstream>
using namespace std;

int main(int argc, char *argv[])
{
char ch;

if(argc!=2) {
cout << «Usage: PR <filename>\n»;
return 1;
}

ifstream in(argv[1], ios::in | ios::binary);
if(!in) {
cout << «Cannot open file.\n»;
return 1;
}

while(!in.eof()) { // use eof()
in.get(ch);
if(!in.eof()) cout << ch;
}

in.close();

return 0;
}

listing 35
// Compare files.
#include <iostream>
#include <fstream>
using namespace std;

int main(int argc, char *argv[])
{
register int i;

unsigned char buf1[1024], buf2[1024];

if(argc!=3) {
cout << «Usage: compfiles <file1> <file2>\n»;
return 1;
}

ifstream f1(argv[1], ios::in | ios::binary);
if(!f1) {
cout << «Cannot open first file.\n»;
return 1;
}
ifstream f2(argv[2], ios::in | ios::binary);
if(!f2) {
cout << «Cannot open second file.\n»;
return 1;
}

cout << «Comparing files…\n»;

do {
f1.read((char *) buf1, sizeof buf1);
f2.read((char *) buf2, sizeof buf2);

if(f1.gcount() != f2.gcount()) {
cout << «Files are of differing sizes.\n»;
f1.close();
f2.close();
return 0;
}

// compare contents of buffers
for(i=0; i<f1.gcount(); i++)
if(buf1[i] != buf2[i]) {
cout << «Files differ.\n»;
f1.close();
f2.close();
return 0;
}

} while(!f1.eof() && !f2.eof());

cout << «Files are the same.\n»;

f1.close();
f2.close();

return 0;
}

listing 36
// Use getline() to read a string that contains spaces.
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
char str[80];

cout << «Enter your name: «;
cin.get(str, 79);

cout << str << ‘\n’;

return 0;
}

listing 37
// Demonstrate random access.
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;

int main(int argc, char *argv[])
{
if(argc!=3) {
cout << «Usage: CHANGE <filename> <byte>\n»;
return 1;
}

fstream out(argv[1], ios::in | ios::out | ios::binary);
if(!out) {
cout << «Cannot open file.\n»;
return 1;
}

out.seekp(atoi(argv[2]), ios::beg);

out.put(‘X’);
out.close();

return 0;
}

listing 38
// Display a file from a given starting point.
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;

int main(int argc, char *argv[])
{
char ch;

if(argc!=3) {
cout << «Usage: NAME <filename> <starting location>\n»;
return 1;
}

ifstream in(argv[1], ios::in | ios::binary);
if(!in) {
cout << «Cannot open file.\n»;
return 1;
}

in.seekg(atoi(argv[2]), ios::beg);

while(in.get(ch))
cout << ch;

return 0;
}

listing 39
/* Use overloaded inserter to write three_d
objects to a file. */
#include <iostream>
#include <fstream>
using namespace std;

class three_d {
int x, y, z; // 3-D coordinates — now private
public:
three_d(int a, int b, int c) { x = a; y = b; z = c; }
friend ostream &operator<<(ostream &stream, three_d obj);
};

// Display X, Y, Z coordinates — three_d inserter.
ostream &operator<<(ostream &stream, three_d obj)
{
stream << obj.x << «, «;
stream << obj.y << «, «;
stream << obj.z << «\n»;
return stream; // return the stream
}

int main()
{
three_d a(1, 2, 3), b(3, 4, 5), c(5, 6, 7);
ofstream out(«threed»);

if(!out) {
cout << «Cannot open file.»;
return 1;
}

out << a << b << c;

out.close();

return 0;
}



listing 1
// A simple example that uses typeid.
#include <iostream>
#include <typeinfo>
using namespace std;

class myclass {
// …
};

int main()
{
int i, j;
float f;
myclass ob;

cout << «The type of i is: » << typeid(i).name();
cout << endl;
cout << «The type of f is: » << typeid(f).name();
cout << endl;
cout << «The type of ob is: » << typeid(ob).name();
cout << «\n\n»;

if(typeid(i) == typeid(j))
cout << «The types of i and j are the same\n»;

if(typeid(i) != typeid(f))
cout << «The types of i and f are not the same\n»;

return 0;
}
listing 2
// An example that uses typeid on a polymorphic class heirarchy.
#include <iostream>
#include <typeinfo>
using namespace std;

class Base {
virtual void f() {}; // make Base polymorphic
// …
};

class Derived1: public Base {
// …
};

class Derived2: public Base {
// …
};

int main()
{
Base *p, baseob;
Derived1 ob1;
Derived2 ob2;

p = &baseob;
cout << «p is pointing to an object of type «;
cout << typeid(*p).name() << endl;

p = &ob1;
cout << «p is pointing to an object of type «;
cout << typeid(*p).name() << endl;

p = &ob2;
cout << «p is pointing to an object of type «;
cout << typeid(*p).name() << endl;

return 0;
}

listing 3
// Use a reference with typeid.
#include <iostream>
#include <typeinfo>
using namespace std;

class Base {
virtual void f() {}; // make Base polymorphic
// …
};

class Derived1: public Base {
// …
};

class Derived2: public Base {
// …
};

// Demonstrate typeid with a reference parameter.
void WhatType(Base &ob)
{
cout << «ob is referencing an object of type «;
cout << typeid(ob).name() << endl;
}
int main()
{
int i;
Base baseob;
Derived1 ob1;
Derived2 ob2;

WhatType(baseob);
WhatType(ob1);
WhatType(ob2);

return 0;
}

listing 4
cout << typeid(int).name();

listing 5
// Demonstrating run-time type id.
#include <iostream>
using namespace std;

class figure {
protected:
double x, y;
public:
figure(double i, double j) {
x = i;
y = j;
}
virtual double area() = 0;
} ;

class triangle : public figure {
public:
triangle(double i, double j) : figure(i, j) {}
double area() {
return x * 0.5 * y;
}
};

class rectangle : public figure {
public:
rectangle(double i, double j) : figure(i, j) {}
double area() {
return x * y;
}
};

class circle : public figure {
public:
circle(double i, double j=0) : figure(i, j) {}
double area() {
return 3.14 * x * x;
}
} ;

// A factory for objects derived from figure.
figure *factory()
{
switch(rand() % 3 ) {
case 0: return new circle(10.0);
case 1: return new triangle(10.1, 5.3);
case 2: return new rectangle(4.3, 5.7);
}
return 0;
}

int main()
{
figure *p; // pointer to base class
int i;

int t=0, r=0, c=0;

// generate and count objects
for(i=0; i<10; i++) {
p = factory(); // generate an object

cout << «Object is » << typeid(*p).name();
cout << «. «;

// count it
if(typeid(*p) == typeid(triangle)) t++;
if(typeid(*p) == typeid(rectangle)) r++;
if(typeid(*p) == typeid(circle)) c++;

// display its area
cout << «Area is » << p->area() << endl;
}

cout << endl;
cout << «Objects generated:\n»;
cout << » Triangles: » << t << endl;
cout << » Rectangles: » << r << endl;
cout << » Circles: » << c << endl;

return 0;
}

listing 6
// Using typeid with templates.
#include <iostream>
using namespace std;

template <class T> class myclass {
T a;
public:
myclass(T i) { a = i; }
// …
};

int main()
{
myclass<int> o1(10), o2(9);
myclass<double> o3(7.2);

cout << «Type of o1 is «;
cout << typeid(o1).name() << endl;

cout << «Type of o2 is «;
cout << typeid(o2).name() << endl;

cout << «Type of o3 is «;
cout << typeid(o3).name() << endl;

cout << endl;

if(typeid(o1) == typeid(o2))
cout << «o1 and o2 are the same type\n»;

if(typeid(o1) == typeid(o3))
cout << «Error\n»;
else
cout << «o1 and o3 are different types\n»;

return 0;
}

listing 7
// Template version of the figure heirarchy.
#include <iostream>
using namespace std;

template <class T> class figure {
protected:
T x, y;
public:
figure(T i, T j) {
x = i;
y = j;
}
virtual T area() = 0;
} ;

template <class T> class triangle : public figure<T> {
public:
triangle(T i, T j) : figure<T>(i, j) {}
T area() {
return x * 0.5 * y;
}
};

template <class T> class rectangle : public figure<T> {
public:
rectangle(T i, T j) : figure<T>(i, j) {}
T area() {
return x * y;
}
};

template <class T> class circle : public figure<T> {
public:
circle(T i, T j=0) : figure<T>(i, j) {}
T area() {
return 3.14 * x * x;
}
} ;

// A factory for objects derived from figure.
figure<double> *generator()
{
switch(rand() % 3 ) {
case 0: return new circle<double>(10.0);
case 1: return new triangle<double>(10.1, 5.3);
case 2: return new rectangle<double>(4.3, 5.7);
}
return 0;
}

int main()
{
figure<double> *p;
int i;
int t=0, c=0, r=0;

// generate and count objects
for(i=0; i<10; i++) {
p = generator();

cout << «Object is » << typeid(*p).name();
cout << «. «;

// count it
if(typeid(*p) == typeid(triangle<double>)) t++;
if(typeid(*p) == typeid(rectangle<double>)) r++;
if(typeid(*p) == typeid(circle<double>)) c++;

cout << «Area is » << p->area() << endl;
}

cout << endl;
cout << «Objects generated:\n»;
cout << » Triangles: » << t << endl;
cout << » Rectangles: » << r << endl;
cout << » Circles: » << c << endl;

return 0;
}
listing 8
Base *bp, b_ob;
Derived *dp, d_ob;

bp = &d_ob; // base pointer points to Derived object
dp = dynamic_cast<Derived *> (bp); // cast to derived pointer OK
if(dp) cout << «Cast OK»;

listing 9
bp = &b_ob; // base pointer points to Base object
dp = dynamic_cast<Derived *> (bp); // error
if(!dp) cout << «Cast Fails»;

listing 10
// Demonstrate dynamic_cast.
#include <iostream>
using namespace std;

class Base {
public:
virtual void f() { cout << «Inside Base\n»; }
// …
};

class Derived : public Base {
public:
void f() { cout << «Inside Derived\n»; }
};

int main()
{
Base *bp, b_ob;
Derived *dp, d_ob;

dp = dynamic_cast<Derived *> (&d_ob);
if(dp) {
cout << «Cast from Derived * to Derived * OK.\n»;
dp->f();
} else
cout << «Error\n»;

cout << endl;

bp = dynamic_cast<Base *> (&d_ob);
if(bp) {
cout << «Cast from Derived * to Base * OK.\n»;
bp->f();
} else
cout << «Error\n»;

cout << endl;

bp = dynamic_cast<Base *> (&b_ob);
if(bp) {
cout << «Cast from Base * to Base * OK.\n»;
bp->f();
} else
cout << «Error\n»;

cout << endl;

dp = dynamic_cast<Derived *> (&b_ob);
if(dp)
cout << «Error\n»;
else
cout << «Cast from Base * to Derived * not OK.\n»;

cout << endl;

bp = &d_ob; // bp points to Derived object
dp = dynamic_cast<Derived *> (bp);
if(dp) {
cout << «Casting bp to a Derived * OK\n» <<
«because bp is really pointing\n» <<
«to a Derived object.\n»;
dp->f();
} else
cout << «Error\n»;

cout << endl;

bp = &b_ob; // bp points to Base object
dp = dynamic_cast<Derived *> (bp);
if(dp)
cout << «Error»;
else {
cout << «Now casting bp to a Derived *\n» <<
«is not OK because bp is really \n» <<
«pointing to a Base object.\n»;
}

cout << endl;

dp = &d_ob; // dp points to Derived object
bp = dynamic_cast<Base *> (dp);
if(bp) {
cout << «Casting dp to a Base * is OK.\n»;
bp->f();
} else
cout << «Error\n»;

return 0;
}

listing 11
Base *bp;
Derived *dp;
// …
if(typeid(*bp) == typeid(Derived)) dp = (Derived *) bp;

listing 12
dp = dynamic_cast<Derived *> (bp);

listing 13
// Use dynamic_cast to replace typeid.
#include <iostream>
#include <typeinfo>
using namespace std;

class Base {
public:
virtual void f() {}
};

class Derived : public Base {
public:
void derivedOnly() {
cout << «Is a Derived Object\n»;
}
};

int main()
{
Base *bp, b_ob;
Derived *dp, d_ob;

// ************************************
// use typeid
// ************************************
bp = &b_ob;
if(typeid(*bp) == typeid(Derived)) {
dp = (Derived *) bp;
dp->derivedOnly();
}
else
cout << «Cast from Base to Derived failed.\n»;

bp = &d_ob;
if(typeid(*bp) == typeid(Derived)) {
dp = (Derived *) bp;
dp->derivedOnly();
}
else
cout << «Error, cast should work!\n»;

// ************************************
// use dynamic_cast
// ************************************
bp = &b_ob;
dp = dynamic_cast<Derived *> (bp);
if(dp) dp->derivedOnly();
else
cout << «Cast from Base to Derived failed.\n»;

bp = &d_ob;
dp = dynamic_cast<Derived *> (bp);
if(dp) dp->derivedOnly();
else
cout << «Error, cast should work!\n»;

return 0;
}

listing 14
// Demonstrate const_cast.
#include <iostream>
using namespace std;

void f(const int *p)
{
int *v;

// cast away const-ness.
v = const_cast<int *> (p);

*v = 100; // now, modify object through v
}

int main()
{
int x = 99;

cout << «x before call: » << x << endl;
f(&x);
cout << «x after call: » << x << endl;

return 0;
}

listing 15
// Use static_cast.
#include <iostream>
using namespace std;

int main()
{
int i;
float f;

f = 199.22F;

i = static_cast<int> (f);

cout << i;

return 0;
}

listing 16
// An example that uses reinterpret_cast.
#include <iostream>
using namespace std;

int main()
{
int i;
char *p = «This is a string»;

i = reinterpret_cast<int> (p); // cast pointer to integer

cout << i;

return 0;
}



listing 1
namespace CounterNameSpace {
int upperbound;
int lowerbound;

class counter {
int count;
public:
counter(int n) {
if(n <= upperbound) count = n;
else count = upperbound;
}

void reset(int n) {
if(n <= upperbound) count = n;
}

int run() {
if(count > lowerbound) return count—;
else return lowerbound;
}
};
}

listing 2
if(count > lowerbound) return count—;

listing 3
CounterNameSpace::upperbound = 10;

listing 4
CounterNameSpace::counter ob;

listing 5
// Demonstrate a namespace.
#include <iostream>
using namespace std;

namespace CounterNameSpace {
int upperbound;
int lowerbound;

class counter {
int count;
public:
counter(int n) {
if(n <= upperbound) count = n;
else count = upperbound;
}

void reset(int n) {
if(n <= upperbound) count = n;
}

int run() {
if(count > lowerbound) return count—;
else return lowerbound;
}
};
}

int main()
{
CounterNameSpace::upperbound = 100;
CounterNameSpace::lowerbound = 0;

CounterNameSpace::counter ob1(10);
int i;

do {
i = ob1.run();
cout << i << » «;
} while(i > CounterNameSpace::lowerbound);
cout << endl;

CounterNameSpace::counter ob2(20);

do {
i = ob2.run();
cout << i << » «;
} while(i > CounterNameSpace::lowerbound);
cout << endl;

ob2.reset(100);
CounterNameSpace::lowerbound = 90;
do {
i = ob2.run();
cout << i << » «;
} while(i > CounterNameSpace::lowerbound);

return 0;
}

listing 6
namespace NS {
int i;
}

// …

namespace NS {
int j;
}

listing 7
using CounterNameSpace::lowerbound; // only lowerbound is visible
lowerbound = 10; // OK because lowerbound is visible

using namespace CounterNameSpace; // all members are visible
upperbound = 100; // OK because all members are now visible

listing 8
// Demonstrate using.
#include <iostream>
using namespace std;

namespace CounterNameSpace {
int upperbound;
int lowerbound;

class counter {
int count;
public:
counter(int n) {
if(n <= upperbound) count = n;
else count = upperbound;
}

void reset(int n) {
if(n <= upperbound) count = n;
}

int run() {
if(count > lowerbound) return count—;
else return lowerbound;
}
};
}

int main()
{
// use only upperbound from CounterNameSpace
using CounterNameSpace::upperbound;

// now, no qualification needed to set upperbound
upperbound = 100;

// qualification still needed for lowerbound, etc.
CounterNameSpace::lowerbound = 0;

CounterNameSpace::counter ob1(10);
int i;

do {
i = ob1.run();
cout << i << » «;
} while(i > CounterNameSpace::lowerbound);
cout << endl;

// Now, use entire CounterNameSpace
using namespace CounterNameSpace;

counter ob2(20);

do {
i = ob2.run();
cout << i << » «;
} while(i > lowerbound);
cout << endl;

ob2.reset(100);
lowerbound = 90;
do {
i = ob2.run();
cout << i << » «;
} while(i > lowerbound);

return 0;
}

listing 9
using namespace std;

listing 10
// Use explicit std:: qualification.
#include <iostream>

int main()
{
double val;

std::cout << «Enter a number: «;

std::cin >> val;

std::cout << «This is your number: «;
std::cout << val;

return 0;
}

listing 11
// Bring only a few names into the global namespace.
#include <iostream>

// gain access to cout and cin
using std::cout;
using std::cin;

int main()
{
double val;

cout << «Enter a number: «;

cin >> val;
cout << «This is your number: «;
cout << val;

return 0;
}

listing 12
#include <iostream>
using namespace std;

void vline(int i), hline(int i);

int main()
{
void (*p)(int i);

p = vline; // point to vline()

(*p)(4); // call vline()

p = hline; // point to hline()

(*p)(3); // call hline()

return 0;
}

void hline(int i)
{
for( ;i; i—) cout << «-«;
cout << «\n»;
}

void vline(int i)
{
for( ; i; i—) cout << «|\n»;
}

listing 13
(*p)(4);

listing 14
p(4);
listing 15
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;

int comp(const void *a, const void *b);

int main()
{
char str[] = «Function pointers provide flexibility.»;

qsort(str, strlen(str), 1, comp);
cout << «sorted string: » << str;

return 0;
}

int comp(const void *a, const void *b)
{
return * (char *) a — * (char *) b;
}

listing 16
#include <iostream>
#include <cstdlib>
using namespace std;

int comp(const void *a, const void *b);

int main()
{
int num[] = {10, 4, 3, 6, 5 ,7 ,8};
int i;

qsort(num, 7, sizeof(int), comp);

for(i=0; i<7; i++)
cout << num[i] << ‘ ‘;

return 0;
}

int comp(const void *a, const void *b)
{
return * (int *) a — * (int *) b;
}

listing 17
/* Illustrate assigning function pointers to
overloaded functions. */
#include <iostream>
using namespace std;

// Output count number of spaces.
void space(int count)
{
for( ; count; count—) cout << ‘ ‘;
}

// Output count number of chs.
void space(int count, char ch)
{
for( ; count; count—) cout << ch;
}

int main()
{
/* Create a pointer to void function with
one int parameter. */
void (*fp1)(int);

/* Create a pointer to void function with
one int parameter and one character parameter. */
void (*fp2)(int, char);

fp1 = space; // gets address of space(int)

fp2 = space; // gets address of space(int, char)

fp1(22); // output 22 spaces — same as (*fp1)(22)
cout << «|\n»;

fp2(30, ‘x’); // output 30 xs — same as (*fp2)(30, ‘x’)
cout << «|\n»;

return 0;
}

listing 18
#include <iostream>
using namespace std;

class ShareVar {
static int num;
public:
void setnum(int i) { num = i; };
void shownum() { cout << num << » «; }
};

int ShareVar::num; // define num

int main()
{
ShareVar a, b;

a.shownum(); // prints 0
b.shownum(); // prints 0

a.setnum(10); // set static num to 10

a.shownum(); // prints 10
b.shownum(); // also prints 10

return 0;
}

listing 19
class X {
int some_var;
public:
int f1() const; // const member function
};

listing 20
/*
Demonstrate const member functions.
This program won’t compile.
*/
#include <iostream>
using namespace std;

class Demo {
int i;
public:
int geti() const {
return i; // ok
}

void seti(int x) const {
i = x; // error!
}
};

int main()
{
Demo ob;

ob.seti(1900);
cout << ob.geti();

return 0;
}

listing 21
// Demonstrate mutable.
#include <iostream>
using namespace std;

class Demo {
mutable int i;
int j;
public:
int geti() const {
return i; // ok
}

void seti(int x) const {
i = x; // now, OK.
}

/* The following function won’t compile.
void setj(int x) const {
j = x; // Still Wrong!
}
*/
};

int main()
{
Demo ob;

ob.seti(1900);
cout << ob.geti();

return 0;
}

listing 22
#include <iostream>
using namespace std;

class myclass {
int a;
public:
myclass(int x) { a = x; }
int geta() { return a; }
};

int main()
{
myclass ob(4);

cout << ob.geta();

return 0;
}

listing 23
myclass ob = 4; // automatically converts into myclass(4)

listing 24
myclass ob(4);

listing 25
#include <iostream>
using namespace std;

class myclass {
int a;
public:
explicit myclass(int x) { a = x; }
int geta() { return a; }
};

listing 26
myclass ob(110);

listing 27
#include <iostream>
using namespace std;

class myclass {
int num;
public:
myclass(int i) { num = i; }
int getnum() { return num; }
};

int main()
{
myclass o(10);

cout << o.getnum() << endl; // displays 10

// now, use implicit conversion to assign new value
o = 1000;

cout << o.getnum() << endl; // displays 1000

return 0;
}

listing 28
o = 1000;

listing 29
#include <iostream>
using namespace std;

class myclass {
int numA;
int numB;
public:
/* Initialize numA and numB inside the myclass constructor
using normal syntax. */
myclass(int x, int y) {
numA = x;
numB = y;
}

int getNumA() { return numA; }
int getNumB() { return numB; }
};

int main()
{
myclass ob1(7, 9), ob2(5, 2);

cout << «Values in ob1 are » << ob1.getNumB() <<
» and » << ob1.getNumA() << endl;

cout << «Values in ob2 are » << ob2.getNumB() <<
» and » << ob2.getNumA() << endl;

return 0;
}

listing 30
#include <iostream>
using namespace std;

class myclass {
const int numA; // const member
const int numB; // const member
public:
// Initialize numA and numB using initialization syntax.
myclass(int x, int y) : numA(x), numB(y) { }

int getNumA() { return numA; }
int getNumB() { return numB; }
};

int main()
{
myclass ob1(7, 9), ob2(5, 2);

cout << «Values in ob1 are » << ob1.getNumB() <<
» and » << ob1.getNumA() << endl;

cout << «Values in ob2 are » << ob2.getNumB() <<
» and » << ob2.getNumA() << endl;

return 0;
}

listing 31
#include <iostream>
using namespace std;

extern «C» void myCfunc();

int main()
{
myCfunc();

return 0;
}

// This will link as a C function.
void myCfunc()
{
cout << «This links as a C function.\n»;
}

listing 32
// Pointer-to-member example.
#include <iostream>
using namespace std;

class myclass {
public:
int sum;
void myclass::sum_it(int x);
};

void myclass::sum_it(int x) {
int i;

sum = 0;
for(i=x; i; i—) sum += i;
}

int main()
{
int myclass::*dp; // pointer to an integer class member
void (myclass::*fp)(int x); // pointer to member function
myclass c;

dp = &myclass::sum; // get address of data
fp = &myclass::sum_it; // get address of function

(c.*fp)(7); // compute summation of 7
cout << «summation of 7 is » << c.*dp;

return 0;
}

listing 33
#include <iostream>
using namespace std;

class myclass {
public:
int sum;
void myclass::sum_it(int x);
};

void myclass::sum_it(int x) {
int i;

sum = 0;
for(i=x; i; i—) sum += i;
}

int main()
{
int myclass::*dp; // pointer to an integer class member
void (myclass::*fp)(int x); // pointer to member function
myclass *c, d; // c is now a pointer to an object

c = &d; // give c the address of an object

dp = &myclass::sum; // get address of data
fp = &myclass::sum_it; // get address of function

(c->*fp)(7); // now, use ->* to call function
cout << «summation of 7 is » << c->*dp; // use ->*

return 0;
}

listing 34
operator int() { return x * y * z; }

listing 35
#include <iostream>
using namespace std;

class three_d {
int x, y, z; // 3-D coordinates
public:
three_d(int a, int b, int c) { x = a; y = b; z = c; }

three_d operator+(three_d op2) ;
friend ostream &operator<<(ostream &stream, three_d &obj);

operator int() {return x * y * z; }
} ;

// Display X, Y, Z coordinates — three_d inserter.
ostream &operator<<(ostream &stream, three_d &obj)
{
stream << obj.x << «, «;
stream << obj.y << «, «;
stream << obj.z << «\n»;
return stream; // return the stream
}

three_d three_d::operator+(three_d op2)
{
three_d temp(0, 0, 0);

temp.x = x+op2.x;
temp.y = y+op2.y;
temp.z = z+op2.z;
return temp;
}

int main()
{
three_d a(1, 2, 3), b(2, 3, 4);

cout << a << b;

cout << b+100; // displays 124 because of conversion to int
cout << «\n»;

a = a + b; // add two three_d objects — no conversion

cout << a; // displays 3, 5, 7

return 0;
}


listing 1
vector<int> iv; // create zero-length int vector
vector<char> cv(5); // create 5-element char vector
vector<char> cv(5, ‘x’); // initialize a 5-element char vector
vector<int> iv2(iv); // create int vector from an int vector

listing 2
// Vector basics.
#include <iostream>
#include <vector>
using namespace std;

int main()
{
vector<int> v; // create zero-length vector
unsigned int i;

// display original size of v
cout << «Size = » << v.size() << endl;

/* put values onto end of vector —
vector will grow as needed */
for(i=0; i<10; i++) v.push_back(i);

// display current size of v
cout << «Current contents:\n»;
cout << «Size now = » << v.size() << endl;

// display contents of vector
for(i=0; i<v.size(); i++) cout << v[i] << » «;
cout << endl;

/* put more values onto end of vector —
again, vector will grow as needed */
for(i=0; i<10; i++) v.push_back(i+10);

// display current size of v
cout << «Size now = » << v.size() << endl;

// display contents of vector
cout << «Current contents:\n»;
for(i=0; i<v.size(); i++) cout << v[i] << » «;
cout << endl;

// change contents of vector
for(i=0; i<v.size(); i++) v[i] = v[i] + v[i];

// display contents of vector
cout << «Contents doubled:\n»;
for(i=0; i<v.size(); i++) cout << v[i] << » «;
cout << endl;

return 0;
}

listing 3
// Access a vector using an iterator.
#include <iostream>
#include <vector>
using namespace std;

int main()
{
vector<char> v; // create zero-length vector
int i;

// put values into a vector
for(i=0; i<10; i++) v.push_back(‘A’ + i);

// can access vector contents using subscripting
for(i=0; i<10; i++) cout << v[i] << » «;
cout << endl;

// access via iterator
vector<char>::iterator p = v.begin();
while(p != v.end()) {
cout << *p << » «;
p++;
}

return 0;
}

listing 4
// Demonstrate insert and erase.
#include <iostream>
#include <vector>
using namespace std;

int main()
{
vector<char> v;
unsigned int i;

for(i=0; i<10; i++) v.push_back(‘A’ + i);

// display original contents of vector
cout << «Size = » << v.size() << endl;
cout << «Original contents:\n»;
for(i=0; i<v.size(); i++) cout << v[i] << » «;
cout << endl << endl;

vector<char>::iterator p = v.begin();
p += 2; // point to 3rd element

// insert 10 X’s into v
v.insert(p, 10, ‘X’);

// display contents after insertion
cout << «Size after insert = » << v.size() << endl;
cout << «Contents after insert:\n»;
for(i=0; i<v.size(); i++) cout << v[i] << » «;
cout << endl << endl;

// remove those elements
p = v.begin();
p += 2; // point to 3rd element
v.erase(p, p+10); // remove next 10 elements

// display contents after deletion
cout << «Size after erase = » << v.size() << endl;
cout << «Contents after erase:\n»;
for(i=0; i<v.size(); i++) cout << v[i] << » «;
cout << endl;

return 0;
}
listing 5
// Store a class object in a vector.
#include <iostream>
#include <vector>
using namespace std;

class three_d {
int x, y, z;
public:
three_d() { x = y = z = 0; }
three_d(int a, int b, int c) { x = a; y = b; z = c; }

three_d &operator+(int a) {
x += a;
y += a;
z += a;
return *this;
}

friend ostream &operator<<(ostream &stream, three_d obj);
friend bool operator<(three_d a, three_d b);
friend bool operator==(three_d a, three_d b);
} ;

// Display X, Y, Z coordinates — three_d inserter.
ostream &operator<<(ostream &stream, three_d obj)
{
stream << obj.x << «, «;
stream << obj.y << «, «;
stream << obj.z << «\n»;
return stream; // return the stream
}

bool operator<(three_d a, three_d b)
{
return (a.x + a.y + a.z) < (b.x + b.y + b.z);
}

bool operator==(three_d a, three_d b)
{
return (a.x + a.y + a.z) == (b.x + b.y + b.z);
}

int main()
{
vector<three_d> v;
unsigned int i;

// add objects to a vector
for(i=0; i<10; i++)
v.push_back(three_d(i, i+2, i-3));

// display contents of vector
for(i=0; i<v.size(); i++)
cout << v[i];

cout << endl;

// modify objects in a vector
for(i=0; i<v.size(); i++)
v[i] = v[i] + 10;

// display modified vector
for(i=0; i<v.size(); i++)
cout << v[i];

return 0;
}

listing 6
// Insert one vector into another.
#include <iostream>
#include <vector>
using namespace std;

int main()
{
vector<char> v, v2;
unsigned int i;

for(i=0; i<10; i++) v.push_back(‘A’ + i);

// display original contents of vector
cout << «Original contents:\n»;
for(i=0; i<v.size(); i++) cout << v[i] << » «;
cout << endl << endl;

// initialize second vector
char str[] = «-STL Power-«;
for(i = 0; str[i]; i++) v2.push_back(str[i]);

/* get iterators to the middle of v and
the start and end of v2 */
vector<char>::iterator p = v.begin()+5;
vector<char>::iterator p2start = v2.begin();
vector<char>::iterator p2end = v2.end();

// insert v2 into v
v.insert(p, p2start, p2end);

// display result
cout << «Contents of v after insertion:\n»;
for(i=0; i<v.size(); i++) cout << v[i] << » «;

return 0;
}

listing 7
// List basics.
#include <iostream>
#include <list>
using namespace std;

int main()
{
list<char> lst; // create an empty list
int i;

for(i=0; i<10; i++) lst.push_back(‘A’+i);

cout << «Size = » << lst.size() << endl;

cout << «Contents: «;
list<char>::iterator p = lst.begin();
while(p != lst.end()) {
cout << *p;
p++;
}

return 0;
}

listing 8
list<char>::iterator p = lst.begin();
while(p != lst.end()) {
cout << *p;
p++;
}

listing 9
// Elements can be put on the front or end of a list.
#include <iostream>
#include <list>
using namespace std;

int main()
{
list<char> lst;
list<char> revlst;
int i;

for(i=0; i<10; i++) lst.push_back(‘A’+i);

cout << «Size of lst = » << lst.size() << endl;
cout << «Original contents: «;

list<char>::iterator p;

/* Remove elements from lst and put them
into revlst in reverse order. */
while(!lst.empty()) {
p = lst.begin();
cout << *p;
lst.pop_front();
revlst.push_front(*p);
}
cout << endl << endl;

cout << «Size of revlst = «;
cout << revlst.size() << endl;
cout << «Reversed contents: «;
p = revlst.begin();
while(p != revlst.end()) {
cout << *p;
p++;
}

return 0;
}

listing 10
// Sort a list.
#include <iostream>
#include <list>
#include <cstdlib>
using namespace std;

int main()
{
list<int> lst;
int i;

// create a list of random integers
for(i=0; i<10; i++)
lst.push_back(rand());

cout << «Original contents:\n»;
list<int>::iterator p = lst.begin();
while(p != lst.end()) {
cout << *p << » «;
p++;
}
cout << endl << endl;

// sort the list
lst.sort();

cout << «Sorted contents:\n»;
p = lst.begin();
while(p != lst.end()) {
cout << *p << » «;
p++;
}

return 0;
}

listing 11
// Merge two lists.
#include <iostream>
#include <list>
using namespace std;

int main()
{
list<char> lst1, lst2;
int i;

for(i=0; i<10; i+=2) lst1.push_back(‘A’+i);
for(i=1; i<11; i+=2) lst2.push_back(‘A’+i);

cout << «Contents of lst1: «;
list<char>::iterator p = lst1.begin();
while(p != lst1.end()) {
cout << *p;
p++;
}
cout << endl << endl;

cout << «Contents of lst2: «;
p = lst2.begin();
while(p != lst2.end()) {
cout << *p;
p++;
}
cout << endl << endl;

// now, merge the two lists
lst1.merge(lst2);
if(lst2.empty())
cout << «lst2 is now empty\n»;

cout << «Contents of lst1 after merge:\n»;
p = lst1.begin();
while(p != lst1.end()) {
cout << *p;
p++;
}

return 0;
}

listing 12
// Store class objects in a list.
#include <iostream>
#include <list>
#include <cstring>
using namespace std;

class myclass {
int a, b;
int sum;
public:
myclass() { a = b = 0; }
myclass(int i, int j) {
a = i;
b = j;
sum = a + b;
}
int getsum() { return sum; }

friend bool operator<(const myclass &o1,
const myclass &o2);
friend bool operator>(const myclass &o1,
const myclass &o2);
friend bool operator==(const myclass &o1,
const myclass &o2);
friend bool operator!=(const myclass &o1,
const myclass &o2);
};

bool operator<(const myclass &o1, const myclass &o2)
{
return o1.sum < o2.sum;
}

bool operator>(const myclass &o1, const myclass &o2)
{
return o1.sum > o2.sum;
}

bool operator==(const myclass &o1, const myclass &o2)
{
return o1.sum == o2.sum;
}

bool operator!=(const myclass &o1, const myclass &o2)
{
return o1.sum != o2.sum;
}

int main()
{
int i;

// create first list
list<myclass> lst1;
for(i=0; i<10; i++) lst1.push_back(myclass(i, i));

cout << «First list: «;
list<myclass>::iterator p = lst1.begin();
while(p != lst1.end()) {
cout << p->getsum() << » «;
p++;
}
cout << endl;

// create a second list
list<myclass> lst2;
for(i=0; i<10; i++) lst2.push_back(myclass(i*2, i*3));

cout << «Second list: «;
p = lst2.begin();
while(p != lst2.end()) {
cout << p->getsum() << » «;
p++;
}
cout << endl;

// now, merget lst1 and lst2
lst1.merge(lst2);

// display merged list
cout << «Merged list: «;
p = lst1.begin();
while(p != lst1.end()) {
cout << p->getsum() << » «;
p++;
}

return 0;
}
listing 13
// A simple map demonstration.
#include <iostream>
#include <map>
using namespace std;

int main()
{
map<char, int> m;
int i;

// put pairs into map
for(i=0; i<10; i++) {
m.insert(pair<char, int>(‘A’+i, i));
}

char ch;
cout << «Enter key: «;
cin >> ch;

map<char, int>::iterator p;

// find value given key
p = m.find(ch);
if(p != m.end())
cout << p->second;
else
cout << «Key not in map.\n»;

return 0;
}

listing 14
m.insert(make_pair((char)(‘A’+i), i));

listing 15
// Use a map to create a dictionary.
#include <iostream>
#include <map>
#include <cstring>
using namespace std;

class word {
char str[20];
public:
word() { strcpy(str, «»); }
word(char *s) { strcpy(str, s); }
char *get() { return str; }

};

// must define less than relative to word objects
bool operator<(word a, word b)
{
return strcmp(a.get(), b.get()) < 0;
}

class meaning {
char str[80];
public:
meaning() { strcmp(str, «»); }
meaning(char *s) { strcpy(str, s); }
char *get() { return str; }
};
int main()
{
map<word, meaning> dictionary;

// put words and meanings into map
dictionary.insert(pair<word, meaning>(word(«house»),
meaning(«A place of dwelling.»)));
dictionary.insert(pair<word, meaning>(word(«keyboard»),
meaning(«An input device.»)));
dictionary.insert(pair<word, meaning>(word(«programming»),
meaning(«The act of writing a program.»)));
dictionary.insert(pair<word, meaning>(word(«STL»),
meaning(«Standard Template Library»)));

// given a word, find meaning
char str[80];
cout << «Enter word: «;
cin >> str;

map<word, meaning>::iterator p;

p = dictionary.find(word(str));
if(p != dictionary.end())
cout << «Definition: » << p->second.get();
else
cout << «Word not in dictionary.\n»;

return 0;
}

listing 16
// Demonstrate count and count_if.
#include <iostream>
#include <vector>
#include <algorithm>
#include <cctype>
using namespace std;

/* This is a unary predicate that determines
if character is isvowel. */
bool isvowel(char ch)
{
ch = tolower(ch);
if(ch==’a’ || ch==’e’ || ch==’i’
|| ch==’o’ || ch==’u’ || ch==’y’) return true;

return false;
}

int main()
{
char str[] = «STL programming is powerful.»;
vector<char> v;
unsigned int i;

for(i=0; str[i]; i++) v.push_back(str[i]);

cout << «Sequence: «;
for(i=0; i<v.size(); i++) cout << v[i];
cout << endl;

int n;
n = count(v.begin(), v.end(), ‘p’);
cout << n << » characters are p\n»;

n = count_if(v.begin(), v.end(), isvowel);
cout << n << » characters are vowels.\n»;

return 0;
}

listing 17
// Demonstrate remove_copy and replace_copy.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
char str[] = «This is a test.»;
vector<char> v, v2(20);
unsigned int i;

for(i=0; str[i]; i++) v.push_back(str[i]);

// **** demonstrate remove_copy ****

cout << «Input sequence: «;
for(i=0; i<v.size(); i++) cout << v[i];
cout << endl;

// Remove all i’s
remove_copy(v.begin(), v.end(), v2.begin(), ‘i’);

cout << «Result after removing i’s: «;
for(i=0; i<v2.size(); i++) cout << v2[i];
cout << endl << endl;

// **** now, demonstrate replace_copy ****

cout << «Input sequence: «;
for(i=0; i<v.size(); i++) cout << v[i];
cout << endl;

// Remove replace s’s with X’s
replace_copy(v.begin(), v.end(), v2.begin(), ‘s’, ‘X’);

cout << «Result after repacing s’s with X’s: «;
for(i=0; i<v2.size(); i++) cout << v2[i];
cout << endl << endl;

return 0;
}
listing 18
// Demonstrate reverse.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
vector<int> v;
unsigned int i;

for(i=0; i<10; i++) v.push_back(i);

cout << «Initial: «;
for(i=0; i<v.size(); i++) cout << v[i] << » «;
cout << endl;

reverse(v.begin(), v.end());

cout << «Reversed: «;
for(i=0; i<v.size(); i++) cout << v[i] << » «;

return 0;
}

listing 19
// An example of the transform algorithm.
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;

// A simple transformation function.
int xform(int i) {
return i * i; // square original value
}

int main()
{
list<int> xl;
int i;

// put values into list
for(i=0; i<10; i++) xl.push_back(i);

cout << «Original contents of xl: «;
list<int>::iterator p = xl.begin();
while(p != xl.end()) {
cout << *p << » «;
p++;
}

cout << endl;

// transform xl
p = transform(xl.begin(), xl.end(), xl.begin(), xform);

cout << «Transformed contents of xl: «;
p = xl.begin();
while(p != xl.end()) {
cout << *p << » «;
p++;
}

return 0;
}

listing 20
char s1[80], s2[80], s3[80];

s1 = «one»; // can’t do
s2 = «two»; // can’t do
s3 = s1 + s2; // error, not allowed

listing 21
strcpy(s1, «one»);
strcpy(s2, «two»);
strcpy(s3, s1);
strcat(s3, s2);

listing 22
// A short string demonstration.
#include <iostream>
#include <string>
using namespace std;

int main()
{
string str1(«The string class gives «);
string str2(«C++ high-powered string handling.»);
string str3;

// assign a string
str3 = str1;
cout << str1 << «\n» << str3 << «\n»;

// concatenate two strings
str3 = str1 + str2;
cout << str3 << «\n»;

// compare strings
if(str3 > str1) cout << «str3 > str1\n»;
if(str3 == str1+str2)
cout << «str3 == str1+str2\n»;

/* A string object can also be
assigned a normal string. */
str1 = «This is a null-terminated string.\n»;
cout << str1;

// create a string object using another string object
string str4(str1);
cout << str4;

// input a string
cout << «Enter a string: «;
cin >> str4;
cout << str4;

return 0;
}

listing 23
// Demonstrate insert(), erase(), and replace().
#include <iostream>
#include <string>
using namespace std;

int main()
{
string str1(«This is a test»);
string str2(«ABCDEFG»);

cout << «Initial strings:\n»;
cout << «str1: » << str1 << endl;
cout << «str2: » << str2 << «\n\n»;

// demonstrate insert()
cout << «Insert str2 into str1:\n»;
str1.insert(5, str2);
cout << str1 << «\n\n»;

// demonstrate erase()
cout << «Remove 7 characters from str1:\n»;
str1.erase(5, 7);
cout << str1 <<«\n\n»;

// demonstrate replace
cout << «Replace 2 characters in str1 with str2:\n»;
str1.replace(5, 2, str2);
cout << str1 << endl;

return 0;
}

listing 24
#include <iostream>
#include <string>
using namespace std;

int main()
{
int i;
string s1 =
«The string class makes string handling easy.»;
string s2;

i = s1.find(«class»);
if(i!=string::npos) {
cout << «Match found at » << i << endl;
cout << «Remaining string is: «;
s2.assign(s1, i, s1.size());
cout << s2;
}

return 0;
}

listing 25
// Use a map of strings to create a dictionary.
#include <iostream>
#include <map>
#include <string>
using namespace std;

int main()
{
map<string, string> dictionary;

dictionary.insert(pair<string, string>(«house»,
«A place of dwelling.»));
dictionary.insert(pair<string, string>(«keyboard»,
«An input device.»));
dictionary.insert(pair<string, string>(«programming»,
«The act of writing a program.»));
dictionary.insert(pair<string, string>(«STL»,
«Standard Template Library»));

string s;
cout << «Enter word: «;
cin >> s;

map<string, string>::iterator p;

p = dictionary.find(s);
if(p != dictionary.end())
cout << «Definition: » << p->second;
else
cout << «Word not in dictionary.\n»;

return 0;
}



listing 1
#define UP 1
#define DOWN 0

listing 2
cout << UP << ‘ ‘ << DOWN << ‘ ‘ << UP + UP;

listing 3
#define ONE 1
#define TWO ONE+ONE
#define THREE ONE+TWO

listing 4
#define GETFILE «Enter File Name»

.
.
.

cout << GETFILE;

listing 5
cout << «Enter File Name»;

listing 6
#define GETFILE «Enter File Name»
.
.
.
cout << «GETFILE is a macro name\n»;

listing 7
#define LONG_STRING «this is a very long \
string that is used as an example»

listing 8
#define MAX_SIZE 100
// …
float balance[MAX_SIZE];
double indexMAX_SIZE;
int num_emp[MAX_SIZE];

listing 9
// Use a function-like macro.
#include <iostream>
using namespace std;

#define MIN(a,b) (((a)<(b)) ? a : b)

int main()
{
int x, y;

x = 10;
y = 20;
cout << «The minimum is » << MIN(x, y);

return 0;
}

listing 10
cout << «The minimum is: » << ((x)<(y)) ? x : y);

listing 11
// This program will give the wrong answer.
#include <iostream>
using namespace std;

#define EVEN(a) a%2==0 ? 1 : 0

int main()
{
if(EVEN(9+1)) cout << «is even»;
else cout << «is odd»;

return 0;
}

listing 12
9+1%2==0 ? 1 : 0

listing 13
// This program is now fixed.
#include <iostream>
using namespace std;

#define EVEN(a) (a)%2==0 ? 1 : 0

int main()
{
if(EVEN(9+1)) cout << «is even»;
else cout << «is odd»;

return 0;
}

listing 14
#include <vector>

listing 15
#include <sample.h>
#include «sample.h»

listing 16
// A simple #if example.
#include <iostream>
using namespace std;

#define MAX 100
int main()
{
#if MAX>10
cout << «Extra memory required.\n»;
#endif

// …
return 0;
}

listing 17
// A simple #if/#else example.
#include <iostream>
using namespace std;

#define MAX 6
int main()
{
#if MAX>10
cout << «Extra memory required.\n»);
#else
cout << «Current memory OK.\n»;
#endif

// …

return 0;
}

listing 18
#define JOHN 0
#define BOB 1
#define TOM 2

#define COMPILED_BY JOHN

#if COMPILED_BY == JOHN
char who[] = «John»;
#elif COMPILED_BY == BOB
char who[] = «Bob»;
#else
char who[] = «Tom»;
#endif

listing 19
#if COMPILED_BY == BOB
#if DEBUG == FULL
int port = 198;
#elif DEBUG == PARTIAL
int port = 200;
#endif
#else
cout << «Bob must compile for debug output.\n»;
#endif

listing 20
#include <iostream>
using namespace std;

#define TOM

int main()
{
#ifdef TOM
cout << «Programmer is Tom.\n»;
#else
cout << «Programmer is unknown.\n»;
#endif
#ifndef RALPH
cout << «RALPH not defined.\n»;
#endif
return 0;
}

listing 21
#define TIMEOUT 100
#define WAIT 0

// …

#undef TIMEOUT
#undef WAIT

listing 22
#if defined MYFILE

listing 24
#if !defined DEBUG
cout << «Final version!\n»;
#endif

listing 25
#include <iostream>
using namespace std;

#line 200 // set line counter to 200
int main() // now this is line 200
{ // this is line 201
cout << __LINE__; // prints 202

return 0;
}

listing 26
#include <iostream>
using namespace std;

#define mkstr(s) # s

int main()
{
cout << mkstr(I like C++);

return 0;
}

listing 27
cout << mkstr(I like C++);

listing 28
cout << «I like C++»;

listing 29
#include <iostream>
using namespace std;

#define concat(a, b) a ## b

int main()
{
int xy = 10;

cout << concat(x, y);

return 0;
}

listing 30
cout << concat(x, y);

listing 31
cout << xy;