C++ Programming

Reading map

Previous: Programming Paradigms Reading map Next: Functional and Logic Programming

Volume III: Paradigms (Chapter 10)Code & tests Chapter diagrams Download editable SVGs

C++ mechanisms support several paradigms: objects, abstract data types, generic programming, and exceptions. Classes and access control provide useful machinery, but an object-oriented design also depends on how cooperating objects and their messages are understood.

Chapter Map

Detailed notes - 10: C++, OOP, and abstract data types

1

C++: introduced by Bjarne Stroustrup as an extension of C

  • supports objects and messages
  • also supports abstract data types, generic programming, exceptions and other ways of organizing a program

2

OOP and abstract data types: two related but distinct paradigms

  • the preceding chapter introduced both

3

C++ uses the same mechanisms for several purposes:

  • access control hides both object state and ADT representation
  • classes and inheritance also participate in exceptions
  • the underlying imperative model remains visible

using these mechanisms does not by itself establish an OOP design

4

ADTs are useful independently of OOP

OOP also requires thinking in terms of objects and their messages

  • practise that way of describing large cooperating systems

5

language features provide technical support for paradigms

  • the programmer chooses how to interpret and organize a program
  • the chapter returns to this distinction after the mechanisms

10.1 From C to C++

C++ shares much of C while changing declarations, conversions, and type rules. The examples use an older language subset, so comparisons involving comments, declaration placement, or implicit C declarations need their historical context.

Each row comes from a small test program compiled both ways, with gcc -std=c89 -pedantic and g++ -std=c++98 -pedantic.

Code C89 C++98
int try = 1; valid error: try is a keyword
struct mystruct { int a, b; }; mystruct s1; error: needs struct mystruct s1 valid: the tag is also a type name
typedef struct mystruct { ... } mystruct; valid valid, but redundant
typedef struct other { ... } *other; valid error: conflicting declaration
func(3, 5); with no declaration of func valid: implicit int func() error: func was not declared
void *x; int *p = x; valid error: invalid conversion from void*
int x; double *p = &x; warning: incompatible pointers error: cannot convert int*
bool b = false; error: unknown type bool valid
declaration after a statement warning: mixed declarations valid
sizeof('a') 4, the size of int 1, the size of char

The void* rule matters most in practice. C code that relies on the implicit conversion needs a cast in C++:

int *p = (int *) malloc(10 * sizeof(*p));
int *q = malloc(10 * sizeof(*q));   // error in C++: void* to int*
Show the complete program
#include <stdio.h>

int main()
{
    bool b = true;
    int n = b;                          // true converts to 1

    printf("%d %d\n", n, (int) sizeof('a'));
    for (int i = 0; i < 3; i++)         // declaration in the for header
        printf("%d", i);
    printf("\n");
    return 0;
}
1 1
012
Detailed notes - 10.1: From C to C++

1

C++ extends C, but is not a strict superset

  • extra keywords can invalidate former identifiers: e.g. try
  • a struct declaration introduces a usable type name
  • mystruct s1 is sufficient; struct mystruct s1 also works

correction to the example:

  • typedef struct mystruct { ... } mystruct is valid C++
  • repeating the same type name this way is redundant, not an error

2

C++ requires declarations before function calls

  • the comparison with implicit function declarations concerns old C
  • incompatible pointer conversions require attention
  • void* does not implicitly convert to an arbitrary object pointer

C's permission to convert void* does not extend to all pointer types

3

the book uses 0 as a null pointer constant

  • conversion produces the null value of the required pointer type
  • its machine representation need not be an all-zero address
  • NULL is also available; this is the book's older C++ convention

4

several C++ additions are useful before introducing classes or ADTs

5

bool: false and true

  • conversion to an integer gives 0 and 1 respectively
  • integer expressions can still be used as conditions

6

ordinary character literals: type char in C++, type int in C

  • this difference matters when a function is selected by argument type

7

declarations can occur among statements and in a for initializer

  • e.g. declare the loop counter in the loop header

// introduces a comment extending to the end of the line

  • /* ... */ comments remain available

these comparisons describe older C; later C also has these facilities

Tests & experiments (13 files) - 10.1: From C to C++
Section test01 (10)In catalog
bool.cC / 10 lines
#include <stdio.h>

int main()
{
    bool b = false;
    int b2 = b;
    printf("%d\n", b2);

    return 0;
}
constants.cC / 7 lines
#include <stdio.h>

int main()
{
    printf("%ld\n", sizeof('a'));
    return 0;
}
declarations.cC / 8 lines
int main()
{
    int a = 0, b = 1, c;
    c = a + b;
    int d;

    return 0;
}
functions.cC / 5 lines
int main()
{
    func(3, 5);
    return 0;
}
null.cC / 8 lines
#include <stdlib.h>

int main()
{
    int *p = NULL;
    int *q = 0;
    return 0;
}
struct.cC / 9 lines
struct mystruct {
    int a, b;
};

int main()
{
    mystruct s1;
    return 0;
}
struct2.cC / 15 lines
#include <cstdio>

typedef struct mystruct {
    int a, b;
} mystruct;

int main()
{
    mystruct s1;
    s1.a = 1;
    s1.b = 2;
    printf("%d %d\n", s1.a, s1.b);
    return 0;
}

struct2.cppC++ / 15 lines
#include <cstdio>

typedef struct mystruct {
    int a, b;
} mystruct;

int main()
{
    mystruct s1;
    s1.a = 1;
    s1.b = 2;
    printf("%d %d\n", s1.a, s1.b);
    return 0;
}

struct3.cppC++ / 15 lines
#include <cstdio>

typedef struct mystruct {
    int a, b;
} *mystruct;

int main()
{
    mystruct s1;
    s1.a = 1;
    s1.b = 2;
    printf("%d %d\n", s1.a, s1.b);
    return 0;
}

try.cC / 5 lines
int main()
{
    int try = 1;
    return 0;
}
types.cC / 6 lines
int main()
{
    int x;
    double *p = &x;
    return 0;
}
void.cC / 6 lines
int main()
{
    void *x;
    int *p = x;
    return 0;
}
void2.cC / 12 lines
#include <stdlib.h>

int main(void)
{
    int *p = malloc(10 * sizeof(*p));
    void *v = p;
    int *q = v;

    q[0] = 1;
    free(p);
    return 0;
}

10.2 Choosing a subset of C++

The chapter teaches a selected historical subset by explaining mechanisms before large libraries. Its preference for limited dependencies and visible abstraction costs explains the selection; the author's criticism of later C++ remains a design opinion.

Building without a supplied runtime, one of the author's requirements, can be tried directly. This C program needs no C library at all: _start is written in assembly and output goes straight to write. It targets x86-64 Linux.

Show the complete program
__asm__(
    ".globl _start\n"
    "_start:\n"
    "    xor  %rbp, %rbp\n"         /* end of stack frames */
    "    mov  (%rsp), %rdi\n"       /* argc */
    "    lea  8(%rsp), %rsi\n"      /* argv */
    "    and  $-16, %rsp\n"         /* align the stack for C */
    "    call main\n"
    "    mov  %rax, %rdi\n"         /* exit code */
    "    mov  $60, %rax\n"          /* sys_exit */
    "    syscall\n"
);

static long sys_write(int fd, const char *buf, long len)
{
    long ret;

    __asm__ volatile ("syscall"
                      : "=a" (ret)
                      : "a" (1L), "D" ((long)fd), "S" (buf), "d" (len)
                      : "rcx", "r11", "memory");
    return ret;
}

static long str_len(const char *s)
{
    long n = 0;

    while (s[n])
        n++;
    return n;
}

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

    for (i = 0; i < argc; i++) {
        sys_write(1, argv[i], str_len(argv[i]));
        sys_write(1, "\n", 1);
    }
    return argc - 1;
}
gcc -ansi -pedantic -O2 -ffreestanding -fno-stack-protector \
    -fno-pie -no-pie -nostdlib -static zero-runtime.c -o zero-runtime
$ ./zero-runtime one two; echo $?
./zero-runtime
one
two
2
Detailed notes - 10.2: Choosing a subset of C++

1

author's concern: teaching library use before language mechanisms

  • can hide how containers and other abstractions work
  • can blur the distinction between language and library
  • a large feature catalogue can crowd out conceptual understanding

2

the author associates this teaching approach with Stroustrup's third edition, which uses container templates before explaining templates

  • his experience led him to prefer learning the machinery first
  • using existing templates and designing templates are different skills

3

the chapter grew from a separately published C++ booklet

  • its treatment deliberately follows an older language subset
  • its attacks on C++ standards are the author's opinions
  • they are not technical proof that later C++ is unusable

4

the author considers alternatives inadequate for his low-level needs

  • this is his assessment of language design and industrial practice

5

two properties especially important to the author:

  • a clear distinction between language and library
  • ability to build without a supplied runtime where the target needs it

these motivate his interest in kernels and microcontroller firmware

6

the author argues for understanding what abstractions cost and require

  • cites restricted C++ usage in GUI libraries as examples
  • their choices illustrate selective use of language features
  • the book's claims about particular projects reflect its time

7

the book deliberately omits STL and newer language additions

  • its examples teach a selected subset, not the whole current language
Tests & experiments (2 files) - 10.2: Choosing a subset of C++
Section test02 (10)In catalog
MakefileMake / 14 lines
PROGRAMS = zero-runtime

CFLAGS = -ansi -pedantic -O2 -ffreestanding -fno-stack-protector \
         -fno-pie -no-pie -nostdlib -static

all: $(PROGRAMS)

$(PROGRAMS): %: %.c
    $(CC) $(CFLAGS) $^ -o $@

clean:
    rm -f *.o $(PROGRAMS)

.PHONY: clean
zero-runtime.cC / 43 lines
__asm__(
    ".globl _start\n"
    "_start:\n"
    "    xor  %rbp, %rbp\n"         /* end of stack frames */
    "    mov  (%rsp), %rdi\n"       /* argc */
    "    lea  8(%rsp), %rsi\n"      /* argv */
    "    and  $-16, %rsp\n"         /* align the stack for C */
    "    call main\n"
    "    mov  %rax, %rdi\n"         /* exit code */
    "    mov  $60, %rax\n"          /* sys_exit */
    "    syscall\n"
);

static long sys_write(int fd, const char *buf, long len)
{
    long ret;

    __asm__ volatile ("syscall"
                      : "=a" (ret)
                      : "a" (1L), "D" ((long)fd), "S" (buf), "d" (len)
                      : "rcx", "r11", "memory");
    return ret;
}

static long str_len(const char *s)
{
    long n = 0;

    while (s[n])
        n++;
    return n;
}

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

    for (i = 0; i < argc; i++) {
        sys_write(1, argv[i], str_len(argv[i]));
        sys_write(1, "\n", 1);
    }
    return argc - 1;
}

10.3 Methods, objects, and access control

Starting from C structures, member functions associate behavior with objects, access control hides representation, and constructors and destructors govern lifetime. Together these mechanisms provide the foundation for classes and abstract data types.

Detailed notes - 10.3: Methods, objects, and access control

1

start from familiar C structures and functions

  • add member functions, hidden state and controlled lifetime
  • arrive at classes with methods, constructors and destructors

10.3.1 Member functions: methods

A method runs for a particular object and can directly use that object's fields. The complex-number magnitude example turns a function receiving a structure pointer into a request sent through the object's interface.

In C, the operation is a separate function that receives the structure:

struct str_complex {
    double re, im;
};

double magnitude(struct str_complex *z)
{
    return sqrt(z->re * z->re + z->im * z->im);
}

In C++, it becomes a member of the structure and uses the fields directly:

struct str_complex {
    double re, im;
    double magnitude() { return sqrt(re*re + im*im); }
};
str_complex z;
double mod;

z.re = 2.7;
z.im = 3.8;
mod = z.magnitude();    // C: mod = magnitude(&z);
Show the complete program
#include <math.h>
#include <stdio.h>

struct str_complex {
    double re, im;
    double magnitude() { return sqrt(re*re + im*im); }
};

int main()
{
    str_complex z;
    double mod;

    z.re = 2.7;
    z.im = 3.8;
    mod = z.magnitude();

    printf("%f\n", mod);

    return 0;
}
4.661545
Detailed notes - 10.3.1: Member functions: methods

1

member functions and classes support object-oriented programming

  • first examine a method inside a structure

2

complex number: re and im store its Cartesian components C version: magnitude receives a pointer to the structure C++ version: magnitude belongs to the structure

  • accesses re and im directly
  • z.magnitude() uses z.re and z.im
  • result = sqrt(re*re + im*im)

method: a function called for a particular object

3

calling a method corresponds to sending an object a message

  • z receives magnitude: calculate your magnitude
  • its double result is the reply, then assigned to mod
Two objects share method code; the implicit object pointer chooses which state the method sees.
A member call passes an object as well as arguments. Open full size - Editable SVG
Tests & experiments (2 files) - 10.3.1: Member functions: methods
Section test01 (10-03)In catalog
MakefileMake / 9 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
methods.cppC++ / 21 lines
#include <math.h>
#include <stdio.h>

struct str_complex {
    double re, im;
    double magnitude() { return sqrt(re*re + im*im); }
};

int main()
{
    str_complex z;
    double mod;

    z.re = 2.7;
    z.im = 3.8;
    mod = z.magnitude();

    printf("%f\n", mod);

    return 0;
}

10.3.2 The implicit object pointer

A non-static member call implicitly supplies its receiving object through this. This resembles passing an object pointer to a C function and does not inherently require extra runtime work.

Writing this makes the implicit object pointer visible:

struct str_complex {
    double re, im;
    double magnitude() { return sqrt(this->re*this->re + this->im*this->im); }
};

The pointer itself cannot be changed:

struct str_complex {
    double re, im;
    void reset() { this = 0; }    // error: this is not assignable
};
Detailed notes - 10.3.2: The implicit object pointer

1

a non-static member call supplies the object implicitly

  • conceptually like passing its address to an ordinary C function
  • moving the function into the structure need not add runtime cost

2

this: pointer to the object receiving the call

  • this->re makes the otherwise implicit member access explicit
  • useful when another function needs the current object's address
  • the pointer itself cannot be reassigned
Tests & experiments (2 files) - 10.3.2: The implicit object pointer
Section test02 (10-03)In catalog
MakefileMake / 9 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
methods.cppC++ / 21 lines
#include <math.h>
#include <stdio.h>

struct str_complex {
    double re, im;
    double magnitude() { return sqrt(this->re*this->re + this->im*this->im); }
};

int main()
{
    str_complex z;
    double mod;

    z.re = 2.7;
    z.im = 3.8;
    mod = z.magnitude();

    printf("%f\n", mod);

    return 0;
}

10.3.3 Access control and constructors

Private state needs a public way to establish valid objects, and constructors make that initialization part of creation. Construction differs from assignment, while access rights belong to the class rather than individual instances.

With private fields and a set method, nothing forces a client to call set:

struct str_complex {
private:
    double re, im;
public:
    void set(double a_re, double a_im)
        { re = a_re; im = a_im; }
    double magnitude()
        { return sqrt(re*re + im*im); }
};
str_complex z;
double mod;

z.set(2.7, 3.8);        // forgetting this leaves re and im undefined
mod = z.magnitude();

A constructor makes initialization part of creation:

struct str_complex {
private:
    double re, im;
public:
    str_complex(double a_re, double a_im)
        { re = a_re; im = a_im; }
    double magnitude()
        { return sqrt(re*re + im*im); }
};
str_complex z(2.7, 3.8);
double mod = z.magnitude();

double mod2 = str_complex(2.7, 3.8).magnitude();   // temporary object

Once a constructor with parameters exists, there is no implicit no-argument one:

str_complex z;      // error: no matching constructor

Parenthesized initialization also works for built-in types:

int v(7);           // same as int v = 7;

Access control belongs to the class, so a method can read another object's private fields:

struct str_complex {
private:
    double re, im;
public:
    str_complex(double a_re, double a_im) { re = a_re; im = a_im; }
    double distance(const str_complex *other)
    {
        double dre = re - other->re;
        double dim = im - other->im;
        return sqrt(dre * dre + dim * dim);
    }
    void add(const str_complex *other) { re += other->re; im += other->im; }
    void print() { printf("%g%+gi\n", re, im); }
};
Show the complete program
#include <math.h>
#include <stdio.h>

struct str_complex {
private:
    double re, im;
public:
    str_complex(double a_re, double a_im) { re = a_re; im = a_im; }
    double distance(const str_complex *other)
    {
        double dre = re - other->re;
        double dim = im - other->im;
        return sqrt(dre * dre + dim * dim);
    }
    void add(const str_complex *other) { re += other->re; im += other->im; }
    void print() { printf("%g%+gi\n", re, im); }
};

int main()
{
    str_complex a(1, 2), b(4, 6);

    printf("%f\n", a.distance(&b));
    a.add(&b);
    a.print();
    return 0;
}
5.000000
5+8i
Detailed notes - 10.3.3: Access control and constructors

1

hiding implementation requires restricting direct access to members

  • clients should use the operations the type exposes

2

public: accessible to clients

private: accessible to the class's own member functions

  • simply hiding re and im leaves no way to initialize them
  • adding set allows values to be supplied later

problem: a client can forget set or call magnitude first

  • the object then has no established valid state
  • initialization should be part of creation itself

3

constructor: instructions for initializing each new object

  • may require arguments
  • specifies how those arguments establish its initial state

4

constructor name matches the class or structure name

  • has no declared return type, not even void
  • the result of construction is the initialized object

5

str_complex(double a_re, double a_im): requires both components

  • constructor stores them before ordinary use of the object

6

constructors may be supplied implicitly in cases the language permits

  • a programmer need not write every special member explicitly
  • aggregate initialization is a separate case in C++

7

str_complex z(2.7, 3.8): construction with the two arguments

  • z.magnitude() then reads initialized components

a temporary can also receive the message immediately:

  • str_complex(2.7, 3.8).magnitude()

8

declaring a parameterized constructor suppresses an implicit no-argument

constructor

  • str_complex z is then invalid unless a suitable constructor exists

9

parenthesized initialization also works for built-in types

  • int v(7) initializes v to 7

initialization and assignment are different operations

  • array initialization does not imply array assignment is possible
  • some initialization is encoded in the loaded program image
  • global C++ objects can also require runtime initialization

10

constructors initialize new objects

  • assignment changes an object that already exists
  • C++ provides separate control over assignment

11

access control belongs to the type, not to each individual instance

  • a method can access private members of another object of its class
Tests & experiments (6 files) - 10.3.3: Access control and constructors
Section test03 (10-03)In catalog
MakefileMake / 9 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
init.cppC++ / 7 lines
#include <stdio.h>

int main()
{
    int v(7);
    printf("%d\n", v);
}
methods.cppC++ / 25 lines
#include <math.h>
#include <stdio.h>

struct str_complex {
private:
    double re, im;
public:
    void set(double a_re, double a_im)
        { re = a_re; im = a_im; }
    double magnitude()
        { return sqrt(re*re + im*im); }
};

int main()
{
    str_complex z;
    double mod;

    z.set(2.7, 3.8);
    mod = z.magnitude();

    printf("%f\n", mod);

    return 0;
}
methods02.cppC++ / 24 lines
#include <math.h>
#include <stdio.h>

struct str_complex {
private:
    double re, im;
public:
    str_complex(double a_re, double a_im)
        { re = a_re; im = a_im; }
    double magnitude()
        { return sqrt(re*re + im*im); }
};

int main()
{
    str_complex z(2.7, 3.8);
    double mod;

    mod = z.magnitude();

    printf("%f\n", mod);

    return 0;
}
methods03.cppC++ / 21 lines
#include <math.h>
#include <stdio.h>

struct str_complex {
private:
    double re, im;
public:
    str_complex(double a_re, double a_im)
        { re = a_re; im = a_im; }
    double magnitude()
        { return sqrt(re*re + im*im); }
};

int main()
{
    double mod = str_complex(2.7, 3.8).magnitude();

    printf("%f\n", mod);

    return 0;
}
protection.cppC++ / 27 lines
#include <math.h>
#include <stdio.h>

struct str_complex {
private:
    double re, im;
public:
    str_complex(double a_re, double a_im) { re = a_re; im = a_im; }
    double distance(const str_complex *other)
    {
        double dre = re - other->re;
        double dim = im - other->im;
        return sqrt(dre * dre + dim * dim);
    }
    void add(const str_complex *other) { re += other->re; im += other->im; }
    void print() { printf("%g%+gi\n", re, im); }
};

int main()
{
    str_complex a(1, 2), b(4, 6);

    printf("%f\n", a.distance(&b));
    a.add(&b);
    a.print();
    return 0;
}

10.3.4 Why restrict access?

Hiding representation limits client dependencies and confines responsibility for invariants. A complex number can switch between Cartesian and polar storage behind the same operations, or cache both while keeping them consistent.

Cartesian storage computes magnitude and argument on request:

struct str_complex {
private:
    double re, im;
public:
    str_complex(double a_re, double a_im) { re = a_re; im = a_im; }
    double get_re() { return re; }
    double get_im() { return im; }
    double magnitude() { return sqrt(re * re + im * im); }
    double argument() { return atan2(im, re); }
};

Polar storage keeps the same public operations:

struct str_complex {
private:
    double mod, arg;
public:
    str_complex(double re, double im) {
        mod = sqrt(re*re + im*im);
        arg = atan2(im, re);
    }
    double get_re() { return mod * cos(arg); }
    double get_im() { return mod * sin(arg); }
    double magnitude() { return mod; }
    double argument() { return arg; }
};

The client code is identical for both versions and prints 3 +4i = 5:

str_complex a(3, 4);

printf("%g %+gi = %g\n", a.get_re(), a.get_im(), a.magnitude());

Storing both pairs creates an invariant: they must describe the same number. Access control is not a security boundary, though. Casting the object's address bypasses it and breaks the invariant:

Show the complete program
#include <math.h>
#include <stdio.h>

struct str_complex {
private:
    double re, im, mod, arg;
public:
    str_complex(double a_re, double a_im) {
        re = a_re; im = a_im;
        mod = sqrt(re*re + im*im);
        arg = atan2(im, re);
    }
    double get_re() { return re; }
    double get_im() { return im; }
    double magnitude() { return mod; }
    double argument() { return arg; }
};

/* same layout, but everything public */
struct open_complex {
    double re, im, mod, arg;
};

int main()
{
    str_complex a(3, 4);
    double *p;
    open_complex *q;

    p = (double *) &a;
    p[0] = 6;
    p[1] = 8;
    printf("%g %+gi = %g\n", a.get_re(), a.get_im(), a.magnitude());

    q = (open_complex *) &a;
    q->mod = 10;
    printf("%g %+gi = %g\n", a.get_re(), a.get_im(), a.magnitude());

    return 0;
}
6 +8i = 5
6 +8i = 10
Detailed notes - 10.3.4: Why restrict access?

1

access control is useful because it limits dependencies on representation

2

complex numbers: repeated magnitude calculation can become expensive

  • storing magnitude and argument may suit a workload better

3

public re and im tie every client to Cartesian storage

  • changing the representation then requires changing client modules
  • widespread edits cost time and introduce opportunities for mistakes

4

private fields plus GetRe, GetIm, Magnitude and Argument:

  • preserve the external operations while changing internal storage

Cartesian storage:

  • components are returned directly
  • magnitude and argument are calculated

polar storage:

  • magnitude and argument are returned directly
  • re = mod*cos(arg); im = mod*sin(arg)
  • constructor converts supplied Cartesian values to polar form

implementations can be switched and measured without rewriting clients

5

another representation: store both coordinate pairs

  • trades extra storage for simpler repeated queries

invariant: both pairs must describe the same complex number

  • changing only one pair would break consistency
  • private fields confine responsibility to the class implementation
  • checking one module is easier than checking every user of the type

6

access control prevents accidental misuse by cooperating programmers

  • it is not a security boundary against hostile machine-level access
  • deliberately circumventing it defeats its engineering purpose
Example: a buffer must always satisfy 0 <= size <= capacity.
An abstract data type protects a representation invariant. Open full size - Editable SVG
Tests & experiments (5 files) - 10.3.4: Why restrict access?
Section test04 (10-03)In catalog
MakefileMake / 9 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
protection.cppC++ / 21 lines
#include <math.h>
#include <stdio.h>

struct str_complex {
private:
    double re, im;
public:
    str_complex(double a_re, double a_im) { re = a_re; im = a_im; }
    double get_re() { return re; }
    double get_im() { return im; }
    double magnitude() { return sqrt(re * re + im * im); }
    double argument() { return atan2(im, re); }
};

int main()
{
    str_complex a(3, 4);

    printf("%g %+gi = %g\n", a.get_re(), a.get_im(), a.magnitude());
    return 0;
}
protection02.cppC++ / 24 lines
#include <math.h>
#include <stdio.h>

struct str_complex {
private:
    double mod, arg;
public:
    str_complex(double re, double im) {
        mod = sqrt(re*re + im*im);
        arg = atan2(im, re);
    }
    double get_re() { return mod * cos(arg); }
    double get_im() { return mod * sin(arg); }
    double magnitude() { return mod; }
    double argument() { return arg; }
};

int main()
{
    str_complex a(3, 4);

    printf("%g %+gi = %g\n", a.get_re(), a.get_im(), a.magnitude());
    return 0;
}
protection03.cppC++ / 25 lines
#include <math.h>
#include <stdio.h>

struct str_complex {
private:
    double re, im, mod, arg;
public:
    str_complex(double a_re, double a_im) {
        re = a_re; im = a_im;
        mod = sqrt(re*re + im*im);
        arg = atan2(im, re);
    }
    double get_re() { return re; }
    double get_im() { return im; }
    double magnitude() { return mod; }
    double argument() { return arg; }
};

int main()
{
    str_complex a(3, 4);

    printf("%g %+gi = %g\n", a.get_re(), a.get_im(), a.magnitude());
    return 0;
}
protection04.cppC++ / 40 lines
#include <math.h>
#include <stdio.h>

struct str_complex {
private:
    double re, im, mod, arg;
public:
    str_complex(double a_re, double a_im) {
        re = a_re; im = a_im;
        mod = sqrt(re*re + im*im);
        arg = atan2(im, re);
    }
    double get_re() { return re; }
    double get_im() { return im; }
    double magnitude() { return mod; }
    double argument() { return arg; }
};

/* same layout, but everything public */
struct open_complex {
    double re, im, mod, arg;
};

int main()
{
    str_complex a(3, 4);
    double *p;
    open_complex *q;

    p = (double *) &a;
    p[0] = 6;
    p[1] = 8;
    printf("%g %+gi = %g\n", a.get_re(), a.get_im(), a.magnitude());

    q = (open_complex *) &a;
    q->mod = 10;
    printf("%g %+gi = %g\n", a.get_re(), a.get_im(), a.magnitude());

    return 0;
}

10.3.5 Classes

Classes and structures have the same capabilities but different default access rules. The book uses structures for open records and classes for hidden representations exposed through constructors and public operations.

class Complex {
    double re, im;
public:
    Complex(double a_re, double a_im)
        { re = a_re; im = a_im; }
    double GetRe() { return re; }
    double GetIm() { return im; }
    double Magnitude() { return sqrt(re*re + im*im); }
    double Argument() { return atan2(im, re); }
};

The only difference from struct is the default access:

struct S { int x; };    // x is public
class C { int x; };     // x is private
C c;
c.x = 1;                // error: x is private within this context
Detailed notes - 10.3.5: Classes

1

class: a structure whose members are private by default

  • suits types whose representation is normally hidden

2

Complex stores re and im privately

  • public constructor and query methods form its usable interface
  • public: changes access for following declarations

3

class and struct have the same underlying capabilities

  • default member and base-class access differ

usual convention in this book:

  • struct for open records
  • class for objects and abstract data types
Tests & experiments (2 files) - 10.3.5: Classes
Section test05 (10-03)In catalog
MakefileMake / 9 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
classes.cppC++ / 21 lines
#include <math.h>
#include <stdio.h>

class Complex {
    double re, im;
public:
    Complex(double a_re, double a_im)
        { re = a_re; im = a_im; }
    double GetRe() { return re; }
    double GetIm() { return im; }
    double Magnitude() { return sqrt(re*re + im*im); }
    double Argument() { return atan2(im, re); }
};

int main()
{
    Complex a(3, 4);

    printf("%g %+gi = %g\n", a.GetRe(), a.GetIm(), a.Magnitude());
    return 0;
}

10.3.6 Destructors

A destructor releases resources when an object's lifetime ends, including normal scope exit. A file-owning object illustrates automatic cleanup, while repeated acquisition and copying still need explicit ownership policies.

class File {
    int fd;
public:
    File() { fd = -1; }
    bool OpenRO(const char *name) {
        fd = open(name, O_RDONLY);
        return fd != -1;
    }
    int Read(char *buf, int size) { return read(fd, buf, size); }
    ~File() { if (fd != -1) close(fd); }
};

The destructor runs on every normal exit from the object's scope, so the caller never calls close. A tracing class shows the order:

#include <stdio.h>

class Tracer {
    const char *name;
public:
    Tracer(const char *a_name) { name = a_name; printf("construct %s\n", name); }
    ~Tracer() { printf("destroy %s\n", name); }
};

int main()
{
    Tracer a("a");
    {
        Tracer b("b");
    }
    Tracer c("c");
    return 0;
}
construct a
construct b
destroy b
construct c
destroy c
destroy a
Show the complete program
#include <unistd.h>
#include <fcntl.h>

enum {
    buf_size = 4096
};

class File {
    int fd;
public:
    File() { fd = -1; }
    bool OpenRO(const char *name) {
        fd = open(name, O_RDONLY);
        return fd != -1;
    }
    int Read(char *buf, int size) { return read(fd, buf, size); }
    ~File() { if (fd != -1) close(fd); }
};

int main()
{
    int rc;
    char buf[buf_size];
    File f;

    f.OpenRO("Makefile");

    for (;;) {
        rc = f.Read(buf, sizeof(buf));
        if (rc <= 0)
            break;
        write(1, buf, rc);
    }

    return 0;
}
Detailed notes - 10.3.6: Destructors

1

destructor: controls cleanup when an object's lifetime ends

2

an object may own resources that clients cannot see

  • dynamically allocated storage, an open file, or another resource
  • the object knows how to release them
  • cleanup must accompany the relevant end of its lifetime

3

~A(): destructor for class A

  • no parameters and no declared return type
  • invoked automatically during normal object destruction

4

File example:

  • fd starts at -1: no open file
  • OpenRO stores open's result and reports whether it succeeded
  • destructor closes fd when it is valid

local objects are destroyed on normal scope exit, including return

  • one completed lifetime has one construction and one destruction
  • abrupt process termination does not guarantee destructor calls

a production owner must also handle repeated OpenRO calls and copying

  • the short example does not yet solve these ownership cases
Tests & experiments (2 files) - 10.3.6: Destructors
Section test06 (10-03)In catalog
MakefileMake / 9 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
destructors.cppC++ / 36 lines
#include <unistd.h>
#include <fcntl.h>

enum {
    buf_size = 4096
};

class File {
    int fd;
public:
    File() { fd = -1; }
    bool OpenRO(const char *name) {
        fd = open(name, O_RDONLY);
        return fd != -1;
    }
    int Read(char *buf, int size) { return read(fd, buf, buf_size); }
    ~File() { if (fd != -1) close(fd); }
};

int main()
{
    int rc;
    char buf[buf_size];
    File f;

    f.OpenRO("Makefile");

    for (;;) {
        rc = f.Read(buf, sizeof(buf));
        if (rc <= 0)
            break;
        write(1, buf, rc);
    }

    return 0;
}

10.4 Abstract data types in C++

Abstract data types combine hidden representation with controlled creation, copying, assignment, and destruction. References and overloaded operations let user-defined values fit ordinary expressions without requiring an object-message interpretation of the whole design.

The goal of this section, in one program: a Complex that reads like a built-in number. The following subsections introduce each feature it uses.

Show the complete program
#include <math.h>
#include <stdio.h>

class Complex {
    double re, im;
public:
    Complex(double a_re = 0, double a_im = 0) : re(a_re), im(a_im) {}
    double GetRe() const { return re; }
    double GetIm() const { return im; }
    double Magnitude() const { return sqrt(re*re + im*im); }
    Complex& operator+=(const Complex &op2)
        { re += op2.re; im += op2.im; return *this; }
    friend Complex operator+(const Complex &a, const Complex &b);
    friend Complex operator*(const Complex &a, const Complex &b);
    friend Complex operator/(const Complex &a, const Complex &b);
};

Complex operator+(const Complex &a, const Complex &b)
{
    return Complex(a.re + b.re, a.im + b.im);
}

Complex operator*(const Complex &a, const Complex &b)
{
    return Complex(a.re*b.re - a.im*b.im, a.re*b.im + a.im*b.re);
}

Complex operator/(const Complex &a, const Complex &b)
{
    double dem = b.re*b.re + b.im*b.im;
    return Complex((a.re*b.re + a.im*b.im) / dem,
                   (a.im*b.re - a.re*b.im) / dem);
}

int main()
{
    Complex a(1, 2), b(3, 4);
    Complex c = a * b + 1.5;        // (-5+10i) + 1.5
    Complex d = 1.5 + a / b;        // 1.5 converts on the left, too
    c += a;
    printf("c = %g%+gi\n", c.GetRe(), c.GetIm());
    printf("d = %g%+gi\n", d.GetRe(), d.GetIm());
    printf("|b| = %g\n", b.Magnitude());
    return 0;
}
c = -2.5+12i
d = 1.94+0.08i
|b| = 5
Detailed notes - 10.4: Abstract data types in C++

1

access control and lifetime operations support both OOP and ADTs

  • methods are central to the object/message interpretation
  • ADT operations can also be expressed as non-member functions

2

this section adds user-defined operations and lifetime control

  • creation, copying, assignment and destruction
  • references connect expression properties with the type system
  • these facilities are not restricted to OOP

3

goal: use a complicated abstraction as naturally as a built-in value

  • implementation details stay inside its definition

4

author's assessment: effective ADTs can greatly reduce work relative to C

  • the gain depends on how the program and its types are organized

10.4.1 Function overloading and name mangling

Overloading selects functions from argument types and counts; return type alone cannot distinguish them. Name mangling encodes C++ identities for linking, while extern "C" supplies compatible language linkage for C interfaces.

void print(int n);
void print(const char *s);
void print();
print(42);          // print(int)
print("hello");     // print(const char*)
print();            // print()

The return type alone cannot distinguish two overloads:

int get_value();
double get_value();     // error: differs only in return type

An added overload can make an existing call ambiguous:

void f(float x);
void f(const char *s);
f(1);               // f(float): an int converts to float
f("string");        // f(const char*)
f(0);               // error: 0 converts to float and to a null pointer

The linker sees mangled names that encode the parameter types:

double foo(double x, int n) { return x * n; }
$ g++ -c foo.cpp && nm foo.o
0000000000000000 T _Z3foodi

A header shared by C and C++ modules gives its functions C linkage, so a C++ caller asks for foo instead of _Z3foodi:

#ifndef MYLIB_H_SENTRY
#define MYLIB_H_SENTRY

#ifdef __cplusplus
extern "C" {
#endif

double foo(double x, int n);

#ifdef __cplusplus
}
#endif

#endif
Detailed notes - 10.4.1: Function overloading and name mangling

1

overloading: a language mechanism used by several later features

  • not in itself an OOP or ADT design

2

functions can share a name when their parameter lists distinguish them

  • print(int), print(const char*) and print() are separate functions
  • argument number and types determine the selected overload

function signature includes its name and relevant parameter types

  • return type alone cannot distinguish two overloads
  • overloads may return different types if parameters distinguish them
  • int* and const int* differ; top-level const on a value parameter does not create a distinct overload

3

adding an overload can make an existing call ambiguous

  • f(float) and f(const char*) both accept conversion from literal 0
  • f(1) selects the numeric possibility; f("string") the pointer one
  • f(0) gives neither candidate a sufficient advantage

4

overloading is static polymorphism

  • the compiler chooses the operation before the program runs

5

the author prefers distinct names for ordinary functions

  • e.g. print_int and print_str make intent explicit

constructors need overloading because their names match their class

  • different parameter lists provide different ways to create a value

6

operator functions also share prescribed names

  • argument types distinguish implementations for different types

7

author's recommendation: avoid ordinary-function overloading

  • this is his style preference, not a language restriction
  • constructors and operator functions use it throughout the chapter

8

mixed-language projects expose an additional issue

  • C, C++ and assembler modules must agree on linker symbols

9

a linker resolves labels and addresses, not high-level function overloads

  • one plain function name cannot distinguish all C++ overloads

10

name mangling: encoding C++ naming information into linker symbols

11

a mangled name can encode the function and its parameter types

  • the example foo(double, int) becomes _Z3foodi with its toolchain
  • user-defined types and templates require more elaborate encodings

12

binary compatibility depends on the compiler's ABI

  • matching mangling is necessary but not the whole ABI contract
  • source distribution allows rebuilding for a chosen toolchain

13

C and C++ declarations can look alike but produce different symbols

  • a C definition named foo will not satisfy a request for _Z3foodi
  • compilation may succeed while linking fails

14

extern "C": gives declarations C language linkage

  • allows a C++ caller and a C implementation to agree
  • the usual overload-based C++ symbol encoding is not applied

15

two ways to expose a C header to C++:

  • place its #include inside extern "C" { ... }
  • put the linkage wrapper inside the header itself

shared header:

  • protect the wrapper with #ifdef __cplusplus
  • retain ordinary include guards
  • the C compiler sees declarations without C++ linkage syntax

nested scopes also require distinguishable linker names

  • class members are not identified solely by their short names

16

author's language-design criticism:

  • constructors could hypothetically have distinct names
  • operators could hypothetically use a different special mechanism

these are proposed alternatives, not facilities offered by C++

17

the author treats these costs as lessons for future language design

  • his judgment of C++ alternatives remains an opinion
Tests & experiments (16 files) - 10.4.1: Function overloading and name mangling
Section test01 (10-04)In catalog
MakefileMake / 9 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
const.cppC++ / 12 lines
#include <cstdio>

void func(int *p) { printf("%d\n", *p); }
void func(const int *p) { printf("const %d\n", *p); }

int main()
{
    int x = 20, y = 30;
    func(&x);
    func((const int *) &y);
    return 0;
}
foo.cC / 10 lines
double foo(double a, int b)
{
    return a * b;
}

int main()
{
    foo(3, 1);
    return 0;
}
foo.cppC++ / 10 lines
double foo(double a, int b)
{
    return a * b;
}

int main()
{
    foo(3, 1);
    return 0;
}
hello.asmAssembly / 14 lines
global _start
extern putstr, quit

section .data

hello   db 'Hello', 10, 0

section .text

_start:
    push dword hello
    call putstr
        add esp, 4
        call quit
kernel.incAssembly / 39 lines
%macro kernel 1-*
  %if %0 > 1
    push ebx
  %endif
  %rep %0
    %rotate -1
    push dword %1
  %endrep
    pop eax
  %if %0 > 1
    pop ebx
    %if %0 > 2
    pop ecx
      %if %0 > 3
    pop edx
        %if %0 > 4
        %error "Can't do syscall with more than 4 parameters"
        %endif
      %endif
    %endif

  %endif
    int 80h

    mov ecx, eax
    and ecx, 0xfffff000
    cmp ecx, 0xfffff000
    jne %%ok
    mov ecx, eax
    neg ecx
    mov eax, -1
    jmp short %%end
%%ok:
    xor ecx, ecx
%%end:
  %if %0 > 1
    pop ebx
  %endif
%endmacro
module.cC / 4 lines
double foo(double a, int b)
{
    return a * b;
}
module.hC / 14 lines
#ifndef MODULE_H
#define MODULE_H

#ifdef __cplusplus
extern "C" {
#endif

double foo(double a, int b);

#ifdef __cplusplus
}
#endif

#endif
overloading.cppC++ / 19 lines
#include <cstdio>

void f(const char *str)
{
    printf("This is a string: %s\n", str ? str : "(null)");
}

void f(float f)
{
    printf("This is a floating pointer number: %f\n", f);
}

int main()
{
    f("string");
    f(2.5);
    // f(0);
    return 0;
}
plus5.cppC++ / 15 lines
#include <cstdio>

void print(int n) { printf("%d\n", n); }
int plus5(int x) { return x + 5; }
void plus5(int *x) { *x += 5; }

int main()
{
    int x = 20, y = 30;
    x = plus5(x);
    plus5(&y);
    print(x);
    print(y);
    return 0;
}
print.cppC++ / 13 lines
#include <cstdio>

void print(int n) { printf("%d\n", n); }
void print(const char *s) { printf("%s\n", s); }
void print() { printf("Hello world\n"); }

int main()
{
    print(50);
    print("Have a nice day");
    print();
    return 0;
}
print02.cppC++ / 13 lines
#include <cstdio>

void print_int(int n) { printf("%d\n", n); }
void print_str(const char *s) { printf("%s\n", s); }
void print_hello() { printf("Hello world\n"); }

int main()
{
    print_int(50);
    print_str("Have a nice day");
    print_hello();
    return 0;
}
putstr.asmAssembly / 23 lines
;; putstr.asm ;;
%include "kernel.inc"
global putstr
extern strlen

section .text
putstr: ; < (string address)
    push ebp
    mov ebp, esp
    push esi

    mov esi, [ebp+8]

    push esi
    call strlen
    add esp, 4

    kernel 4, 1, esi, eax

    pop esi
    mov esp, ebp
    pop ebp
    ret
quit.asmAssembly / 6 lines
;; quit.asm ;;
%include "kernel.inc"
global quit

section .text
quit:   kernel 1, 0
strlen.asmAssembly / 21 lines
;; strlen.asm ;;
global strlen

section .text
strlen: ; < (string address) > (string length)
    push ebp
    mov ebp, esp

    mov eax, [ebp+8]
    xor ecx, ecx
.lp:
    cmp byte [eax+ecx], 0
    je .quit
    inc ecx
    jmp short .lp

.quit:
    mov eax, ecx
    mov esp, ebp
    pop ebp
    ret
usec.cppC++ / 10 lines
#include <cstdio>

#include "module.h"

int main()
{
    double res = foo(2, 3);
    printf("%g\n", res);
    return 0;
}

10.4.2 Overloading operator symbols

Operator functions give user-defined types familiar expression syntax, as complex arithmetic demonstrates. Overloading preserves an operator's precedence and arity, and some language operations, including member selection and the conditional operator, cannot be overloaded.

The left operand becomes this; the right one is the parameter:

class Complex {
    double re, im;
public:
    Complex(double a_re, double a_im) { re = a_re; im = a_im; }
    double Magnitude() { return sqrt(re*re + im*im); }
    Complex operator+(Complex op2)
        { return Complex(re + op2.re, im + op2.im); }
    Complex operator-(Complex op2)
        { return Complex(re - op2.re, im - op2.im); }
    Complex operator*(Complex op2)
        { return Complex(re*op2.re - im*op2.im, re*op2.im + im*op2.re); }
    Complex operator/(Complex op2) {
        double dem = op2.re*op2.re + op2.im*op2.im;
        return Complex((re*op2.re + im*op2.im) / dem,
                       (im*op2.re - re*op2.im) / dem);
    }
};
Complex c1(1, 2), c2(3, 4);
Complex c3 = c1 + c2;               // c1.operator+(c2)
double m = (c1 + c2).Magnitude();   // a method called on the sum
Detailed notes - 10.4.2: Overloading operator symbols

1

a useful Complex type needs arithmetic as well as component queries

2

operator+: a member function implementing addition for the type

  • b.operator+(c) can be written b + c
  • the left operand supplies this; the right is the explicit argument
  • class access permits reading the other Complex object's private data

complex arithmetic:

  • addition/subtraction operate on corresponding components
  • multiplication: (ac-bd, ad+bc)
  • division: ((ac+bd)/(c*c+d*d), (bc-ad)/(c*c+d*d)) for numerator (a,b) and denominator (c,d)
  • each operation constructs and returns its result

(c1+c2).Magnitude(): call a method on the sum

many operator symbols can be overloaded, but not every language operation

  • conditional ?: and member selection . cannot be overloaded
  • neither can scope resolution :: or sizeof
  • overloading does not change operator precedence or arity

3

operator selection by operand type is static polymorphism

  • operator functions may also be non-members
  • familiar notation makes user-defined values easier to use as ADTs

4

terminology matters: a statement is a structural unit of program text

  • if, loops and expression statements are examples
  • an expression followed by ; becomes an expression statement

5

an operator belongs inside an expression

  • arithmetic, comparison, assignment, logical and pointer operations

6

the English term operator follows mathematical usage

  • a transformation or operation applied to its operands

7

Russian terminology uses a misleadingly similar word for statement

  • keep statement and operator distinct when reading English C++
Tests & experiments (2 files) - 10.4.2: Overloading operator symbols
Section test02 (10-04)In catalog
MakefileMake / 9 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
complex.cppC++ / 46 lines
#include <math.h>
#include <cstdio>

class Complex {
    double re, im;
public:
    Complex(double a_re, double a_im)
        { re = a_re; im = a_im; }
    double Magnitude() { return sqrt(re*re + im*im); }
    double Argument() { return atan2(im, re); }
    double GetRe() { return re; }
    double GetIm() { return im; }
    Complex operator+(Complex op2) {
        Complex res(re + op2.re, im + op2.im);
        return res;
    }
    Complex operator-(Complex op2) {
        Complex res(re - op2.re, im - op2.im);
        return res;
    }
    Complex operator*(Complex op2) {
        Complex res(re * op2.re - im * op2.im,
                    re * op2.im + im * op2.re);
        return res;
    }
    Complex operator/(Complex op2) {
        double dvs = op2.re * op2.re + op2.im+op2.im;
        Complex res((re * op2.re + im * op2.im) / dvs,
                    (re * op2.im + im * op2.re) / dvs);
        return res;
    }
    void Print() { printf("%g%+gi\n", re, im); }
};

int main()
{
    Complex a(3, 4), b(2, 3);
    // Complex c = a + b;
    // Complex c = a.operator+(b);
    // c.Print();

    double m = (a + b).Magnitude();
    printf("%g\n", m);

    return 0;
}

10.4.3 Default constructors and arrays of objects

A default constructor can be called without arguments and initializes each element in an ordinarily default-constructed object array. Adding a zero-valued Complex constructor makes both single declarations and arrays usable.

class Complex {
    double re, im;
public:
    Complex(double a_re, double a_im) { re = a_re; im = a_im; }
    Complex() { re = 0; im = 0; }
};
Complex z3;         // Complex()
Complex v[50];      // Complex() for each of the 50 elements
Detailed notes - 10.4.3: Default constructors and arrays of objects

1

Complex's two-argument constructor cannot initialize Complex sum

  • it needs both components
  • arrays also need a way to initialize their elements
  • the simple uninitialized-array syntax requires default construction

2

add Complex() alongside Complex(double, double)

  • overloading distinguishes the two constructors
  • the no-argument version sets both components to zero

default constructor: callable without arguments

  • Complex z3 uses it once
  • Complex v[50] uses it for each of the 50 elements
Tests & experiments (2 files) - 10.4.3: Default constructors and arrays of objects
Section test03 (10-04)In catalog
MakefileMake / 9 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
complex.cppC++ / 50 lines
#include <math.h>
#include <cstdio>

class Complex {
    double re, im;
public:
    Complex() { re = 0; im = 0; }
    Complex(double a_re, double a_im)
        { re = a_re; im = a_im; }
    Complex(double a)
        { re = a; im = 0; }
    double Magnitude() { return sqrt(re*re + im*im); }
    double Argument() { return atan2(im, re); }
    double GetRe() { return re; }
    double GetIm() { return im; }
    Complex operator+(Complex op2) {
        Complex res(re + op2.re, im + op2.im);
        return res;
    }
    Complex operator-(Complex op2) {
        Complex res(re - op2.re, im - op2.im);
        return res;
    }
    Complex operator*(Complex op2) {
        Complex res(re * op2.re - im * op2.im,
                    re * op2.im + im * op2.re);
        return res;
    }
    Complex operator/(Complex op2) {
        double dvs = op2.re * op2.re + op2.im+op2.im;
        Complex res((re * op2.re + im * op2.im) / dvs,
                    (re * op2.im + im * op2.re) / dvs);
        return res;
    }
    void Print() { printf("%g%+gi\n", re, im); }
};

void print_complex(Complex a)
{
    printf("%g%+gi\n", a.GetRe(), a.GetIm());
}

int main()
{
    Complex a(9.7);
    a.Print();
    print_complex(3.4);

    return 0;
}

10.4.4 Converting constructors

A converting constructor builds a destination-class value from a source value, such as a real number becoming a complex number. Marking it explicit prevents implicit conversion while retaining direct construction.

class Complex {
    double re, im;
public:
    Complex(double a) { re = a; im = 0; }
    Complex(double a_re, double a_im) { re = a_re; im = a_im; }
};

void f(Complex z);
Complex c(9.7);     // direct construction
f(2.7);             // implicit conversion: f(Complex(2.7))

With explicit, only the direct form remains:

class Complex {
    double re, im;
public:
    explicit Complex(double a) { re = a; im = 0; }
    Complex(double a_re, double a_im) { re = a_re; im = a_im; }
};

void f(Complex z);
f(2.7);             // error: the constructor is explicit
f(Complex(2.7));    // still allowed
Detailed notes - 10.4.4: Converting constructors

1

implicit conversions allow a value where another type is expected

  • e.g. an integer argument passed to a float parameter
  • C++ can also define conversions involving user-defined types

2

converting A to B means constructing a B from the supplied A

  • a B constructor taking A provides the required instructions

3

Complex(double a): store a as the real part and zero as the imaginary part

  • Complex c(9.7) requests that construction directly
  • f(2.7), with a Complex parameter, can perform it implicitly
  • the resulting Complex value is passed to f

explicit can disallow this implicit use of a constructor

  • direct construction remains available

10.4.5 References

A reference aliases an existing object, so assignment through it changes that object rather than reseating the reference. Reference parameters expose caller-owned results, and returned references require their referents to outlive the call.

int i = 5;
int &r = i;         // r and i name the same integer
r++;                // i is now 6
int *p = &r;        // the address of i
int &bad;           // error: a reference needs an initializer

In C, results come back through pointers:

void max_min(const float *a, int n, float *min, float *max)
{
    int i;

    *min = *max = a[0];
    for (i = 1; i < n; i++) {
        if (a[i] < *min)
            *min = a[i];
        if (a[i] > *max)
            *max = a[i];
    }
}
float a[500], min, max;
/* ... fill a ... */
max_min(a, 500, &min, &max);

In C++, reference parameters name the caller's variables directly:

void max_min(const float *a, int n, float &min, float &max)
{
    min = max = a[0];
    for (int i = 1; i < n; i++) {
        if (a[i] < min)
            min = a[i];
        if (a[i] > max)
            max = a[i];
    }
}
float a[500], min, max;
// ... fill a ...
max_min(a, 500, min, max);

A function that returns a reference can be used as a variable:

struct var {
    const char *name;
    int value;
};

var vars[] = { { "x", 1 }, { "y", 2 } };

int &find_var(const char *name)
{
    int i = 0;

    while (strcmp(vars[i].name, name) != 0)
        i++;                    // precondition: the name exists
    return vars[i].value;
}
find_var("x") = 10;
find_var("y") *= 3;
find_var("x")++;                // x is 11, y is 6
Detailed notes - 10.4.5: References

1

references are central to the following ADT mechanisms

  • understand their semantics before treating them as pointer shorthand

2

a reference aliases an object

  • operations through it act on that object
  • assignment changes the referred-to value, not the reference's binding
  • taking its address obtains the address of the referred-to object
  • address passing is a usual implementation, not its full meaning

3

int &r = i: r and i designate the same integer

  • r++ changes i just as i++ does
  • unlike *p, no explicit dereference is written at each use
  • initialize i before any operation that reads its value

4

a reference definition needs an initializer

  • there is no later assignment that can establish its binding
  • initialization and assignment therefore have visibly different roles

5

reference parameters let a function work on the caller's objects

C max_min example:

  • results min and max must be returned through pointer parameters
  • caller supplies &min and &max
  • function dereferences the pointers when reading or writing them

6

C++ max_min uses float& for the two result parameters

  • call max_min(a, 500, min, max)
  • initialize both results from a[0]
  • scan the remaining elements and update the smaller/larger bound
  • assignments to parameter names update the caller's variables

preconditions: nonempty valid array and suitable distinct result variables

7

a function can return a reference to a located object

  • int &find_var(...) makes the call usable as a variable
  • can read, assign, multiply-assign or increment the selected integer
  • the referenced object must still exist after the function returns
Tests & experiments (6 files) - 10.4.5: References
Section test05 (10-04)In catalog
MakefileMake / 9 lines
CFLAGS   = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.c *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
find_var.cppC++ / 61 lines
#include <stdio.h>
#include <string.h>

enum { shelves = 2, per_shelf = 3 };

struct item {
    const char *name;
    int count;
};

struct shelf {
    const char *label;
    item items[per_shelf];
};

shelf store[shelves] = {
    { "fruit", { { "apple", 10 }, { "pear", 4 }, { "plum", 7 } } },
    { "veg", { { "carrot", 20 }, { "onion", 15 }, { "leek", 2 } } }
};

/* the count field of the item with this name, wherever it is */
int &find_var(const char *name)
{
    static int dummy;           /* returned when nothing is found */
    int i, j;

    for (i = 0; i < shelves; i++)
        for (j = 0; j < per_shelf; j++)
            if (strcmp(store[i].items[j].name, name) == 0)
                return store[i].items[j].count;
    dummy = 0;
    return dummy;
}

void print_store()
{
    int i, j;

    for (i = 0; i < shelves; i++) {
        printf("%-6s", store[i].label);
        for (j = 0; j < per_shelf; j++)
            printf("  %s=%d", store[i].items[j].name,
                   store[i].items[j].count);
        printf("\n");
    }
}

int main()
{
    print_store();

    int x = find_var("pear") + 5;       /* read:   x = 4 + 5 */
    find_var("plum") = 3;               /* assign: plum = 3 */
    find_var("carrot") *= 10;           /* carrot = 20 * 10 */
    find_var("leek")++;                 /* leek = 2 + 1 */
    int y = ++find_var("onion");        /* onion = 16, y = 16 */

    printf("\nx = %d, y = %d\n\n", x, y);
    print_store();
    return 0;
}
max_min.cC / 45 lines
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

enum { len = 500 };

double random_number(double limit)
{
    return (limit * rand() / (RAND_MAX + 1.0));
}

void init_array(float *arr, int len)
{
    int i;

    for (i = 0; i < len; i++)
        arr[i] = random_number(100.0);
}

void max_min(float *arr, int len, float *min, float *max)
{
    int i;

    *min = arr[0];
    *max = arr[0];
    for (i = 1; i < len; i++) {
        if (arr[i] < *min)
            *min = arr[i];
        if (arr[i] > *max)
            *max = arr[i];
    }
}

int main()
{
    float a[len], min, max;

    srand(time(NULL));

    init_array(a, len);
    max_min(a, len, &min, &max);
    printf("%g %g\n", min, max);

    return 0;
}
max_min_cpp.cppC++ / 45 lines
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

enum { len = 500 };

double random_number(double limit)
{
    return (limit * rand() / (RAND_MAX + 1.0));
}

void init_array(float *arr, int len)
{
    int i;

    for (i = 0; i < len; i++)
        arr[i] = random_number(100.0);
}

void max_min(float *arr, int len, float &min, float &max)
{
    int i;

    min = arr[0];
    max = arr[0];
    for (i = 1; i < len; i++) {
        if (arr[i] < min)
            min = arr[i];
        if (arr[i] > max)
            max = arr[i];
    }
}

int main()
{
    float a[len], min, max;

    srand(time(NULL));

    init_array(a, len);
    max_min(a, len, min, max);
    printf("%g %g\n", min, max);

    return 0;
}
reference.cppC++ / 16 lines
#include <cstdio>

int main()
{
    int i = 0;
    int *p = &i;
    int &r = i;

    i++;
    (*p)++;
    r++;

    printf("%d\n", r);

    return 0;
}
reference02.cppC++ / 9 lines
#include <cstdio>

int main()
{
    // int &r;
    // printf("%d\n", r);

    return 0;
}

10.4.6 References to const

A const reference permits reading an object without copying or modifying it through that access path. The object may still change through another permitted alias; const does not make every reference to it immutable.

const char *p;          // p can change; the characters cannot, through p
char * const q = 0;     // q cannot change; the characters can
int i = 5;
const int &r = i;       // read-only access to i
i++;                    // allowed: r now reads 6
r++;                    // error: r is a reference to const
const int k = 1;
int &rk = k;            // error: would allow changing k

A const reference parameter avoids the copy and still protects the argument:

class Complex {
    double re, im;
public:
    Complex(double a_re, double a_im) { re = a_re; im = a_im; }
    Complex operator+(const Complex &op2)
        { return Complex(re + op2.re, im + op2.im); }
};
Detailed notes - 10.4.6: References to const

1

const char *p: p can change, but cannot modify characters through p char * const p: p cannot change, but its pointed-to characters may change

const int &r = i:

  • prevents modification through r
  • i may still be changed through another permitted access
  • an ordinary int& cannot bind to a const int

a reference is never reseated; const qualifies the referred-to access

2

const-reference parameters avoid copying while preventing direct changes

through that parameter

  • particularly useful for larger objects
  • Complex operator+(const Complex &op2) reads the existing operand
  • the operation still returns a new Complex result
Tests & experiments (3 files) - 10.4.6: References to const
Section test06 (10-04)In catalog
MakefileMake / 9 lines
CFLAGS   = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.c *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
complex.cppC++ / 50 lines
#include <math.h>
#include <cstdio>

class Complex {
    double re, im;
public:
    Complex() { re = 0; im = 0; }
    Complex(double a_re, double a_im)
        { re = a_re; im = a_im; }
    Complex(double a)
        { re = a; im = 0; }
    double Magnitude() { return sqrt(re*re + im*im); }
    double Argument() { return atan2(im, re); }
    double GetRe() { return re; }
    double GetIm() { return im; }
    Complex operator+(const Complex &op2) {
        Complex res(re + op2.re, im + op2.im);
        return res;
    }
    Complex operator-(const Complex &op2) {
        Complex res(re - op2.re, im - op2.im);
        return res;
    }
    Complex operator*(const Complex &op2) {
        Complex res(re * op2.re - im * op2.im,
                    re * op2.im + im * op2.re);
        return res;
    }
    Complex operator/(const Complex &op2) {
        double dvs = op2.re * op2.re + op2.im+op2.im;
        Complex res((re * op2.re + im * op2.im) / dvs,
                    (re * op2.im + im * op2.re) / dvs);
        return res;
    }
    void Print() { printf("%g%+gi\n", re, im); }
};

void print_complex(Complex a)
{
    printf("%g%+gi\n", a.GetRe(), a.GetIm());
}

int main()
{
    Complex a(9.7);
    a.Print();
    print_complex(3.4);

    return 0;
}
const.cppC++ / 30 lines
#include <cstdio>

int main()
{
    const char *p;
    p = "A string";
    // *p = 'a';
    // p[5] = 'b';
    printf("%s\n", p);

    char buf[20];
    char * const q = buf + 5;
    // q++;
    *q = 'a';
    q[5] = 'b';

    int i;
    const int &r = i;
    int x = r + 5;
    i = 7;
    // r = 12;
    printf("%d\n", x);

    const int j = 5;
    // int &jr = j;
    const int &jcr = j;
    printf("%d\n", jcr);

    return 0;
}

10.4.7 References as a semantic idea

Expressions such as indexing and dereferencing designate objects as well as provide values. The author's reference-based teaching model explains this identity, while standard C++ separately defines reference types and expression value categories.

A conditional expression can select the object to assign to:

int x = 1, y = 2, z = 7;
(x < y ? x : y) = z;        // assigns 7 to x

C needs addresses for the same effect:

int x = 1, y = 2, z = 7;
*(x < y ? &x : &y) = z;
(x < y ? x : y) = z;        /* error in C: not an lvalue */
Detailed notes - 10.4.7: References as a semantic idea

1

the author considers references an especially important C++ innovation

2

lvalue: an expression that identifies an object or other identity

  • examples: a variable name, *p, v[i], q->f
  • reading obtains a value from the designated object
  • assignment selects the destination object
  • += and ++ both read and modify it

3

author's explanatory model: treat such expressions as references

  • *p behaves like access through int& when p points to int
  • member and indexing expressions similarly designate their objects

4

in this model, value use reads the referenced object

  • modifying use keeps its identity as the destination

5

const references illustrate access that identifies an object but cannot modify it

  • the author prefers this account to a catalogue of value categories
  • this is a teaching model; standard C++ distinguishes expression types, reference types and value categories

6

(x < y ? x : y) = z selects an integer object and assigns to it

  • works when the conditional expression has the required lvalue form
  • the corresponding C technique selects addresses, then dereferences: *(x < y ? &x : &y) = z
Tests & experiments (4 files) - 10.4.7: References as a semantic idea
Section test07 (10-04)In catalog
MakefileMake / 9 lines
CFLAGS   = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.c *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
gcc.cppC++ / 23 lines
void f(const char *s);          /* two overloads, */
void f(double *p);              /* neither takes an int */

int g();                        /* returns a plain int */
int &h();                       /* returns a reference */

int main()
{
    int x = 1;
    const int c = 2;
    int a[3];
    int *p = &x;

    // f(x);                       /* variable */
    // f(c);                       /* const variable */
    // f(a[1]);                    /* array element */
    // f(*p);                      /* through a pointer */
    // f(h());                     /* function returning int & */
    // f(x + 1);                   /* arithmetic */
    // f(5);                       /* literal */
    // f(g());                     /* function returning int */
    return 0;
}
lvalue.cppC++ / 8 lines
#include <cstdio>

int main()
{
    int x = 1, y = 2, z = 3;
    (x < y ? x : y) = z;
    return 0;
}
lvalue_c.cC / 6 lines
int main()
{
    int x = 1, y = 2, z = 3;
    *(x < y ? &x : &y) = z;
    return 0;
}

10.4.8 Const member functions

A const member function provides a read-only interface through its receiver and can be called on const objects. It restricts changes through this, but does not guarantee the absence of every observable side effect.

class Complex {
    double re, im;
public:
    Complex(double a_re, double a_im) { re = a_re; im = a_im; }
    double GetRe() const { return re; }
    double GetIm() const { return im; }
    double Magnitude() const { return sqrt(re*re + im*im); }
    void Set(double a_re, double a_im) { re = a_re; im = a_im; }
};
void print(const Complex &c)
{
    printf("%g%+gi\n", c.GetRe(), c.GetIm());   // const methods: allowed
}
void reset(const Complex &c)
{
    c.Set(0, 0);        // error: Set is not a const method
}

A const method cannot change fields through this:

class Counter {
    int n;
public:
    int Next() const { return ++n; }    // error: n is read-only here
};
Detailed notes - 10.4.8: Const member functions

1

const A* permits access to A without modification through that pointer

  • calling an arbitrary method would undermine that guarantee

2

the same issue arises for const references and const objects

  • hidden fields make a usable read-only method interface essential

3

put const after a member function's parameter list

  • the method cannot change ordinary members through this
  • cannot pass those members as modifiable references or pointers
  • can be called on a const object
  • this is not a guarantee against all externally observable side effects

4

mark query operations const when their meaning permits it

  • Complex's component queries, magnitude and arithmetic are examples
  • a const method cannot call a non-const method on the same object
  • this has type const C* within a const member of C
Tests & experiments (2 files) - 10.4.8: Const member functions
Section test08 (10-04)In catalog
MakefileMake / 9 lines
CFLAGS   = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.c *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
complex.cppC++ / 46 lines
#include <math.h>
#include <cstdio>

class Complex {
    double re, im;
public:
    Complex() { re = 0; im = 0; }
    Complex(double a_re, double a_im) { re = a_re; im = a_im; }
    Complex(double a) { re = a; im = 0; }
    double Magnitude() const { return sqrt(re*re + im*im); }
    double Argument() const { return atan2(im, re); }
    double GetRe() const { return re; }
    double GetIm() const { return im; }
    Complex operator+(const Complex &op2) const
        { return Complex(re + op2.re, im + op2.im); }
    Complex operator-(const Complex &op2) const
        { return Complex(re - op2.re, im - op2.im); }
    Complex operator*(const Complex &op2) const {
        return Complex(re * op2.re - im * op2.im,
                       re * op2.im + im * op2.re);
    }
    Complex operator/(const Complex &op2) const {
        double dvs = op2.re * op2.re + op2.im+op2.im;
        return Complex((re * op2.re + im * op2.im) / dvs,
                       (re * op2.im + im * op2.re) / dvs);
    }
    void Print() const { printf("%g%+gi\n", re, im); }
};

void print_complex(Complex a)
{
    printf("%g%+gi\n", a.GetRe(), a.GetIm());
}

void f(const Complex &p)
{
    printf("%g\n", p.Magnitude());
}

int main()
{
    Complex a(3, 4);
    f(a);

    return 0;
}

10.4.9 Dynamic allocation operations

new and delete combine storage management with object construction and destruction; malloc and free do not perform those lifetime operations. Single-object, array, and C allocation forms must each use their matching release operation.

class Complex {
    double re, im;
public:
    Complex(double a_re, double a_im) { re = a_re; im = a_im; }
    Complex() { re = 0; im = 0; }
};
Complex *p = new Complex(2.4, 7.12);    // storage plus constructor
delete p;                               // destructor plus release

int n = 100;
int *arr = new int[n];                  // values are not initialized
Complex *v = new Complex[n];            // Complex() for each element
delete [] arr;
delete [] v;

Each allocation form has exactly one matching release:

Allocation Release
new T, new T(args) delete p
new T[n] delete [] p
malloc, calloc, realloc free(p)
Detailed notes - 10.4.9: Dynamic allocation operations

1

C allocation functions supply and release storage

  • C++ object creation/destruction may additionally require constructors and destructors, with constructor arguments

2

malloc and free do not by themselves perform those object operations

  • object lifetime needs language-aware handling

3

new T: obtain storage and create a T

  • new Complex(2.4, 7.12) passes arguments to its constructor

delete p: destroy that object and release its allocated storage array forms: new T[n] and delete[] p

  • construction and destruction apply to each class-type element
  • the book's new T[n] form uses default construction
  • new int alone does not initialize the integer's value

4

match allocation and release forms exactly

  • new with delete
  • new[] with delete[]
  • malloc-family storage with free

mismatching them has undefined behavior, regardless of apparent success

5

an implementation seeming to tolerate a mismatch proves nothing

  • a different build or allocator can expose the error
Tests & experiments (3 files) - 10.4.9: Dynamic allocation operations
Section test09 (10-04)In catalog
MakefileMake / 9 lines
CFLAGS   = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.c *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
complex.cppC++ / 40 lines
#include <math.h>
#include <cstdio>

class Complex {
    double re, im;
public:
    Complex() { re = 0; im = 0; }
    Complex(double a_re, double a_im) { re = a_re; im = a_im; }
    Complex(double a) { re = a; im = 0; }
    double Magnitude() const { return sqrt(re*re + im*im); }
    double Argument() const { return atan2(im, re); }
    double GetRe() const { return re; }
    double GetIm() const { return im; }
    Complex operator+(const Complex &op2) const
        { return Complex(re + op2.re, im + op2.im); }
    Complex operator-(const Complex &op2) const
        { return Complex(re - op2.re, im - op2.im); }
    Complex operator*(const Complex &op2) const {
        return Complex(re * op2.re - im * op2.im,
                       re * op2.im + im * op2.re);
    }
    Complex operator/(const Complex &op2) const {
        double dvs = op2.re * op2.re + op2.im+op2.im;
        return Complex((re * op2.re + im * op2.im) / dvs,
                       (re * op2.im + im * op2.re) / dvs);
    }
    void Print() const { printf("%g%+gi\n", re, im); }
};

int main()
{
    Complex *p;
    p = new Complex(2.4, 7.12);

    p->Print();

    delete p;

    return 0;
}
new.cppC++ / 6 lines
int main()
{
    int *p = new int[200];
    delete[] p;
    return 0;
}

10.4.10 The copy constructor

Memberwise copying an owning pointer duplicates the address rather than its allocation, risking dangling access and double deletion. A copy constructor can allocate independent storage and copy initialized elements to preserve separate ownership.

With only the implicit copy constructor, a copy shares the original's array:

class Cls1 {
    int *p;
public:
    Cls1() { p = new int[20]; }
    ~Cls1() { delete [] p; }
};

void f(Cls1 x);     // x is a copy: both objects hold the same p,
                    // and both destructors call delete [] on it

A copy constructor gives each object its own array:

class Cls1 {
    int *p;
public:
    Cls1() {
        p = new int[20];
        for (int i = 0; i < 20; i++)
            p[i] = 0;
    }
    Cls1(const Cls1 &a) {
        p = new int[20];
        for (int i = 0; i < 20; i++)
            p[i] = a.p[i];
    }
    ~Cls1() { delete [] p; }
    void Set(int i, int x) { p[i] = x; }
    int Get(int i) const { return p[i]; }
};
Cls1 a;
a.Set(0, 5);
Cls1 b(a);          // copy constructor
b.Set(0, 7);        // a.Get(0) is still 5

The parameter must be a reference; passing by value would itself need a copy:

class Cls2 {
public:
    Cls2(Cls2 a);       // error: invalid constructor
};
Detailed notes - 10.4.10: The copy constructor

1

Cls1 owns an array through an int* member

  • constructor allocates 20 integers; destructor uses delete[]

passing a Cls1 by value creates another object

  • implicit memberwise copying copies the pointer value
  • both objects then refer to the same allocation

2

unplanned sharing breaks ownership

  • changes through the copy affect the original's array
  • destruction of the copy frees storage still used by the original
  • later access dangles; later destruction attempts a second release

3

copy constructor: define how a new object is made from an existing one

  • usual form: Cls1(const Cls1 &a)
  • allocate a separate array and copy its initialized elements
  • each object then owns and destroys its own allocation
  • a class member of class type is itself copied by its copy operation

4

a copy constructor cannot take its own type by value

  • preparing that argument would already require another copy
  • a reference avoids the impossible recursive requirement
The syntax looks similar, but only assignment replaces the value of an existing object.
Initialization and assignment start from different states. Open full size - Editable SVG
A raw owning pointer needs an explicit copy policy; this example uses independent deep copies.
Copying a pointer is not copying its owned storage. Open full size - Editable SVG
Tests & experiments (2 files) - 10.4.10: The copy constructor
Section test10 (10-04)In catalog
MakefileMake / 9 lines
CFLAGS   = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.c *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
copy.cppC++ / 23 lines
class Cls1 {
    int *p;
public:
    Cls1() { p = new int[20]; }
    Cls1(const Cls1 &a) {
        p = new int[20];
        for (int i = 0; i < 20; i++)
            p[i] = a.p[i];
    }
    ~Cls1() { delete[] p; }
};

void f(Cls1 x)
{
}

int main()
{
    Cls1 c;
    f(c);

    return 0;
}

10.4.11 Temporary and unnamed objects

Conversions and value-returning operations can create unnamed temporary objects, normally destroyed at the full expression's end. Suitable const-reference bindings can extend lifetimes under specific rules, whereas ordinary modifiable references cannot bind to temporaries.

class Complex {
    double re, im;
public:
    Complex(double a_re = 0, double a_im = 0) { re = a_re; im = a_im; }
    Complex operator+(const Complex &op2) const
        { return Complex(re + op2.re, im + op2.im); }
    Complex operator*(const Complex &op2) const
        { return Complex(re*op2.re - im*op2.im, re*op2.im + im*op2.re); }
};

Complex z(1, 2), a(1, 1), b(2, 2), c(3, 3);

void show(const Complex &c);
void scale(Complex &c);
Complex t = z * Complex(0, 1);  // multiply by i: an anonymous object
Complex s = a + b + c;          // (a + b) + c: the sum is a temporary
show(a + b);                    // a const reference accepts a temporary
scale(a + b);       // error: a temporary cannot bind to Complex&

A temporary lives until the end of its full expression, unless a local const reference extends its lifetime:

#include <stdio.h>

class T {
    int n;
public:
    T(int a_n) { n = a_n; printf("create %d\n", n); }
    ~T() { printf("destroy %d\n", n); }
    int Get() const { return n; }
};

int main()
{
    printf("value %d\n", T(1).Get());
    printf("next statement\n");
    const T &r = T(2);
    printf("r still refers to %d\n", r.Get());
    return 0;
}
create 1
value 1
destroy 1
next statement
create 2
r still refers to 2
destroy 2
Detailed notes - 10.4.11: Temporary and unnamed objects

1

an explicitly written unnamed object is convenient for a single use

  • t = z * Complex(0, 1) multiplies z by the imaginary unit

implicit conversions can also create temporary objects

  • passing a double where Complex is needed constructs the operand

2

a + b + c groups as (a + b) + c

  • the first addition produces a Complex result
  • that result becomes the next addition's left operand
  • returning class values can therefore supply temporary intermediates

3

the book calls explicitly written temporaries anonymous objects

  • ordinarily temporaries are destroyed at the end of the full expression
  • their destructors run then

binding a suitable local const reference can extend a temporary's lifetime

  • lifetime extension has specific rules; it is not inherited by every later reference or by a reference returned from a function

4

an ordinary non-const lvalue reference cannot bind to a temporary

  • by-value and const-reference parameters can accept it
  • treating a disposable temporary as an output parameter is unhelpful

5

use const references when modification through a parameter is unnecessary

  • reserve modifiable references for operations that need to change the caller's object
Tests & experiments (3 files) - 10.4.11: Temporary and unnamed objects
Section test11 (10-04)In catalog
MakefileMake / 9 lines
CFLAGS   = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.c *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
complex.cppC++ / 43 lines
#include <math.h>
#include <cstdio>

class Complex {
    double re, im;
public:
    Complex() { re = 0; im = 0; }
    Complex(double a_re, double a_im) { re = a_re; im = a_im; }
    Complex(double a) { re = a; im = 0; }
    double Magnitude() const { return sqrt(re*re + im*im); }
    double Argument() const { return atan2(im, re); }
    double GetRe() const { return re; }
    double GetIm() const { return im; }
    Complex operator+(const Complex &op2) const
        { return Complex(re + op2.re, im + op2.im); }
    Complex operator-(const Complex &op2) const
        { return Complex(re - op2.re, im - op2.im); }
    Complex operator*(const Complex &op2) const {
        return Complex(re * op2.re - im * op2.im,
                       re * op2.im + im * op2.re);
    }
    Complex operator/(const Complex &op2) const {
        double dvs = op2.re * op2.re + op2.im+op2.im;
        return Complex((re * op2.re + im * op2.im) / dvs,
                       (re * op2.im + im * op2.re) / dvs);
    }
    void Print() const { printf("%g%+gi\n", re, im); }
};

int main()
{
    Complex t, z(3, 4), a(1, 1), b(2, 3), c(1, -1);

    // Complex imag_1(0, 1);
    // t = z * imag_1;
    t = z * Complex(0, 1); // Anonymous
    t.Print();

    t = a + b + c; // Temporary
    t.Print();

    return 0;
}
destruction.cppC++ / 37 lines
#include <stdio.h>

class Noisy {
    const char *name;
public:
    Noisy(const char *n) { name = n; printf("  create  %s\n", name); }
    ~Noisy() { printf("  destroy %s\n", name); }
    const char *Name() const { return name; }
};

Noisy make(const char *n)       /* returns an object by value */
{
    return Noisy(n);
}

int main()
{
    printf("1: anonymous object, no reference\n");
    printf("  using %s\n", Noisy("anon").Name());
    printf("  next statement\n");

    printf("2: anonymous object bound to a reference\n");
    {
        const Noisy &r = Noisy("bound");
        printf("  next statement, r is %s\n", r.Name());
        printf("  end of block\n");
    }

    printf("3: function result bound to a reference\n");
    {
        const Noisy &r = make("returned");
        printf("  next statement, r is %s\n", r.Name());
        printf("  end of block\n");
    }
    printf("main returns\n");
    return 0;
}

10.4.12 Default argument values

Default arguments fill omitted trailing positions, without allowing callers to skip arbitrary middle arguments. One Complex constructor with two defaults can support zero initialization, real conversion, and fully specified complex values.

void f(int a, const char *s = "string", int n = 5);
f(5);               // f(5, "string", 5)
f(5, "other");      // f(5, "other", 5)
f(5, "other", 7);
void g(int a = 1, int b);   // error: defaults must be trailing

One constructor with defaults serves three purposes:

class Complex {
    double re, im;
public:
    Complex(double a_re = 0, double a_im = 0) { re = a_re; im = a_im; }
};
Complex z;          // 0 + 0i: default constructor
Complex x = 2.5;    // 2.5 + 0i: converting constructor
Complex y(1, 2);    // 1 + 2i
Detailed notes - 10.4.12: Default argument values

1

a function declaration can supply defaults for omitted trailing arguments

  • f(5) can mean f(5, "string", 5) for the example declaration
  • defaults must be available for all omitted positions at the end
  • supplied arguments always match positions from the left
  • cannot skip a middle string argument by supplying a later pointer

2

default expressions have their own lookup and evaluation rules

  • the author recommends simple constants to avoid surprises

3

the author questions calling default arguments static polymorphism

  • the mechanism itself does not select behavior by differing types

4

special constructor categories depend on how they can be called

  • a default constructor is callable without arguments
  • a converting constructor can accept the source value
  • a copy constructor can take the appropriate reference to its class

Complex(double re = 0, double im = 0) serves three purposes

  • no arguments: zero value
  • one double: real-to-complex conversion
  • two doubles: specified real and imaginary components
Tests & experiments (3 files) - 10.4.12: Default argument values
Section test12 (10-04)In catalog
MakefileMake / 9 lines
CFLAGS   = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.c *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
complex.cppC++ / 41 lines
#include <math.h>
#include <cstdio>

class Complex {
    double re, im;
public:
    Complex(double a_re = 0, double a_im = 0) { re = a_re; im = a_im; }
    double Magnitude() const { return sqrt(re*re + im*im); }
    double Argument() const { return atan2(im, re); }
    double GetRe() const { return re; }
    double GetIm() const { return im; }
    Complex operator+(const Complex &op2) const
        { return Complex(re + op2.re, im + op2.im); }
    Complex operator-(const Complex &op2) const
        { return Complex(re - op2.re, im - op2.im); }
    Complex operator*(const Complex &op2) const {
        return Complex(re * op2.re - im * op2.im,
                       re * op2.im + im * op2.re);
    }
    Complex operator/(const Complex &op2) const {
        double dvs = op2.re * op2.re + op2.im+op2.im;
        return Complex((re * op2.re + im * op2.im) / dvs,
                       (re * op2.im + im * op2.re) / dvs);
    }
    void Print() const { printf("%g%+gi\n", re, im); }
};

int main()
{
    Complex t, z(3, 4), a(1, 1), b(2, 3), c(1, -1);

    // Complex imag_1(0, 1);
    // t = z * imag_1;
    t = z * Complex(0, 1); // Anonymous
    t.Print();

    t = a + b + c; // Temporary
    t.Print();

    return 0;
}
default.cppC++ / 12 lines
#include <cstdio>

void f(int a, const char *b = "string", int c = 5)
{
    printf("%d, %s, %d\n", a, b, c);
}

int main()
{
    f(5, "hello");
    return 0;
}

10.4.13 Defining methods outside the class and qualifying names

Keeping longer method definitions outside the class makes its interface easier to scan. ClassName::MethodName identifies the defining scope, and declarations and definitions must agree on parameters and qualifiers such as const.

The class shows only declarations; the bodies follow separately:

class Complex {
    double re, im;
public:
    Complex(double a_re, double a_im);
    double Magnitude() const;
};

Complex::Complex(double a_re, double a_im)
{
    re = a_re;
    im = a_im;
}

double Complex::Magnitude() const
{
    return sqrt(re*re + im*im);
}

::name selects a global name hidden by a member:

void print(const char *s) { printf("%s\n", s); }

class Logger {
public:
    void print(const char *s) { ::print(s); }   // not a recursive call
};
Detailed notes - 10.4.13: Defining methods outside the class and qualifying names

1

method bodies can be as large as ordinary function bodies

  • the author still recommends small, understandable subroutines

2

long bodies inside a class obscure its interface

  • readers need to see the available methods together

3

classes shared by modules normally have definitions in headers

  • method bodies there are seen by every including translation unit
  • inline definitions have special rules; duplicated final machine code is not an inevitable consequence

4

keep declarations in the class and place longer definitions separately

  • retain return type, name, parameters and any trailing const
  • end the declaration with ;
  • usually put definitions in the module's implementation file

5

ClassName::MethodName identifies an out-of-class member definition

  • constructors use ClassName::ClassName
  • const must agree between declaration and definition
  • a short member name is otherwise local to its class scope

6

class scope separates its member names from unrelated names

  • f inside C1 and C1::f outside designate the same member
  • qualification identifies the scope; access control still applies

7

::func selects func in global scope

  • useful when a member with the same name hides it
  • qualification also applies to static members

8

:: qualifies names rather than computing a scope from an expression

  • the author discusses whether to call it an operator
  • operationally, names on its sides must satisfy qualification syntax
Tests & experiments (5 files) - 10.4.13: Defining methods outside the class and qualifying names
Section test13 (10-04)In catalog
MakefileMake / 21 lines
CFLAGS   = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS   = -lm

SRCS  = $(wildcard *.c *.cpp)
OBJS  = $(addsuffix .o, $(basename $(SRCS)))
PROGS = $(basename $(shell grep -l "^int main" $(SRCS) /dev/null))
MODS  = $(filter-out $(PROGS:=.o), $(OBJS))

all: $(PROGS)

libmods.a: $(MODS)
    ar crs $@ $^

$(PROGS): %: %.o libmods.a
    $(CXX) $^ $(LDLIBS) -o $@

$(OBJS): $(wildcard *.h *.hpp)

clean:
    rm -f *.o libmods.a $(PROGS)
complex.cppC++ / 56 lines
#include <math.h>
#include <cstdio>
#include "complex.hpp"

Complex::Complex(double a_re, double a_im)
{
    re = a_re; im = a_im;
}

double Complex::Magnitude() const
{
    return sqrt(re*re + im*im);
}

double Complex::Argument() const
{
    return atan2(im, re);
}

double Complex::GetRe() const
{
    return re;
}

double Complex::GetIm() const
{
    return im;
}

Complex Complex::operator+(const Complex &op2) const
{
    return Complex(re + op2.re, im + op2.im);
}

Complex Complex::operator-(const Complex &op2) const
{
    return Complex(re - op2.re, im - op2.im);
}

Complex Complex::operator*(const Complex &op2) const
{
    return Complex(re * op2.re - im * op2.im,
                   re * op2.im + im * op2.re);
}

Complex Complex::operator/(const Complex &op2) const
{
    double dvs = op2.re * op2.re + op2.im+op2.im;
    return Complex((re * op2.re + im * op2.im) / dvs,
                   (re * op2.im + im * op2.re) / dvs);
}

void Complex::Print() const
{
    printf("%g%+gi\n", re, im);
}
complex.hppC++ / 14 lines
class Complex {
    double re, im;
public:
    Complex(double a_re = 0, double a_im = 0);
    double Magnitude() const;
    double Argument() const;
    double GetRe() const;
    double GetIm() const;
    Complex operator+(const Complex &op2) const;
    Complex operator-(const Complex &op2) const;
    Complex operator*(const Complex &op2) const;
    Complex operator/(const Complex &op2) const;
    void Print() const;
};
double_dot.cppC++ / 12 lines
#include <cstdio>

void func()
{
    printf("hello there\n");
}

int main()
{
    ::func();
    return 0;
}
main.cppC++ / 16 lines
#include "complex.hpp"

int main()
{
    Complex t, z(3, 4), a(1, 1), b(2, 3), c(1, -1);

    // Complex imag_1(0, 1);
    // t = z * imag_1;
    t = z * Complex(0, 1); // Anonymous
    t.Print();

    t = a + b + c; // Temporary
    t.Print();

    return 0;
}

10.4.14 Inline functions

Inlining can remove call overhead and expose further optimizations for short accessors. The inline keyword also affects definition rules across translation units; it neither forces substitution nor prevents other functions from being inlined.

inline double sqr(double x) { return x * x; }

class Complex {
    double re, im;
public:
    double GetRe() const { return re; }     // defined in the class: inline
    double Magnitude() const;
};

inline double Complex::Magnitude() const    // explicitly inline
{
    return sqrt(sqr(re) + sqr(im));
}

An inline function used by several modules goes in the header, because each translation unit needs its definition.

Detailed notes - 10.4.14: Inline functions

1

very short accessors might appear expensive if each required a full call

  • call setup can outweigh simply loading one field

2

inlining substitutes the function's operations at a call site

  • subsequent optimization can remove unnecessary intermediate work
  • encapsulation need not imply an extra machine-level call

3

methods defined inside the class are implicitly inline in the book's model

  • this suits the suggested convention of keeping only short bodies there

4

inline may also be written on an ordinary or out-of-class function

5

inline does not force machine-code substitution

  • optimization decisions belong to the compiler
  • functions without inline can also be inlined

6

an inline function used across translation units needs its definition available where required, conventionally in a header

  • separate compilation otherwise sees only the declaration
  • inline also permits corresponding identical definitions in multiple translation units under the language's definition rules

7

a function may have both inlined call sites and callable emitted code

  • taking its address can require a callable implementation
  • these implementation choices must preserve program semantics

8

short methods can therefore expose a clean interface without necessarily

adding call overhead

Tests & experiments (4 files) - 10.4.14: Inline functions
Section test14 (10-04)In catalog
MakefileMake / 21 lines
CFLAGS   = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS   = -lm

SRCS  = $(wildcard *.c *.cpp)
OBJS  = $(addsuffix .o, $(basename $(SRCS)))
PROGS = $(basename $(shell grep -l "^int main" $(SRCS) /dev/null))
MODS  = $(filter-out $(PROGS:=.o), $(OBJS))

all: $(PROGS)

libmods.a: $(MODS)
    ar crs $@ $^

$(PROGS): %: %.o libmods.a
    $(CXX) $^ $(LDLIBS) -o $@

$(OBJS): $(wildcard *.h *.hpp)

clean:
    rm -f *.o libmods.a $(PROGS)
complex.cppC++ / 13 lines
#include <math.h>
#include <cstdio>
#include "complex.hpp"

Complex::Complex(double a_re, double a_im)
{
    re = a_re; im = a_im;
}

void Complex::Print() const
{
    printf("%g%+gi\n", re, im);
}
complex.hppC++ / 39 lines
#include <math.h>

class Complex {
    double re, im;
public:
    Complex(double a_re = 0, double a_im = 0);
    double Magnitude() const { return sqrt(re*re + im*im); }
    double Argument() const { return atan2(im, re); }
    double GetRe() const { return re; }
    double GetIm() const { return im; }
    Complex operator+(const Complex &op2) const;
    Complex operator-(const Complex &op2) const;
    Complex operator*(const Complex &op2) const;
    Complex operator/(const Complex &op2) const;
    void Print() const;
};

inline Complex Complex::operator+(const Complex &op2) const
{
    return Complex(re + op2.re, im + op2.im);
}

inline Complex Complex::operator-(const Complex &op2) const
{
    return Complex(re - op2.re, im - op2.im);
}

inline Complex Complex::operator*(const Complex &op2) const
{
    return Complex(re * op2.re - im * op2.im,
                   re * op2.im + im * op2.re);
}

inline Complex Complex::operator/(const Complex &op2) const
{
    double dvs = op2.re * op2.re + op2.im+op2.im;
    return Complex((re * op2.re + im * op2.im) / dvs,
                   (re * op2.im + im * op2.re) / dvs);
}
main.cppC++ / 17 lines
#include "complex.hpp"

int main()
{
    Complex t, z(3, 4), a(1, 1), b(2, 3), c(1, -1);

    // Complex imag_1(0, 1);
    // t = z * imag_1;
    t = z * Complex(0, 1); // Anonymous
    t.Print();

    t = a + b + c; // Temporary
    t.GetRe();
    t.Print();

    return 0;
}

10.4.15 Member initialization in constructors

Members are initialized before a constructor body runs, so required constructor arguments belong in the initializer list. Actual initialization follows member declaration order, regardless of the order written in that list.

A member without a default constructor must be built in the initializer list:

class A {
    int x, y;
public:
    A(int a_x, int a_y) { x = a_x; y = a_y; }
};

class B {
    A a;
public:
    B() : a(2, 3) {}
};
class B2 {
    A a;
public:
    B2() { a = A(2, 3); }   // error: a would need A() before the body
};

The same syntax initializes ordinary fields, and it is the only way to initialize const and reference members:

class Complex {
    double re, im;
public:
    Complex(double a_re, double a_im) : re(a_re), im(a_im) {}
};

class Limit {
    const int max;
    int &counter;
public:
    Limit(int a_max, int &a_counter) : max(a_max), counter(a_counter) {}
};

Members are initialized in declaration order, whatever the list says:

class Buffer {
    int *data;      // initialized first
    int size;       // initialized second
public:
    Buffer(int n) : data(new int[n]), size(n) {}   // same order: clear
    ~Buffer() { delete [] data; }
};
Detailed notes - 10.4.15: Member initialization in constructors

1

members already need to be constructed before the constructor body runs

  • B contains A a; A requires two constructor arguments
  • assignment inside B's body cannot supply a's initial construction

2

member initializer list follows the constructor header after a colon

  • B::B() : a(2, 3) constructs a with those arguments
  • Complex can initialize re and im in the same way
  • also necessary for reference members and applicable const members

members initialize in declaration order, not initializer-list order

  • write the list in that same order to make dependencies clear
For this single-base class, member declaration order controls initialization.
Construction order also defines destruction order. Open full size - Editable SVG
Tests & experiments (4 files) - 10.4.15: Member initialization in constructors
Section test15 (10-04)In catalog
MakefileMake / 21 lines
CFLAGS   = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS   = -lm

SRCS  = $(wildcard *.c *.cpp)
OBJS  = $(addsuffix .o, $(basename $(SRCS)))
PROGS = $(basename $(shell grep -l "^int main" $(SRCS) /dev/null))
MODS  = $(filter-out $(PROGS:=.o), $(OBJS))

all: $(PROGS)

libmods.a: $(MODS)
    ar crs $@ $^

$(PROGS): %: %.o libmods.a
    $(CXX) $^ $(LDLIBS) -o $@

$(OBJS): $(wildcard *.h *.hpp)

clean:
    rm -f *.o libmods.a $(PROGS)
complex.cppC++ / 7 lines
#include <cstdio>
#include "complex.hpp"

void Complex::Print() const
{
    printf("%g%+gi\n", re, im);
}
complex.hppC++ / 39 lines
#include <math.h>

class Complex {
    double re, im;
public:
    Complex(double a_re = 0, double a_im = 0) : re(a_re), im(a_im) {}
    double Magnitude() const { return sqrt(re*re + im*im); }
    double Argument() const { return atan2(im, re); }
    double GetRe() const { return re; }
    double GetIm() const { return im; }
    Complex operator+(const Complex &op2) const;
    Complex operator-(const Complex &op2) const;
    Complex operator*(const Complex &op2) const;
    Complex operator/(const Complex &op2) const;
    void Print() const;
};

inline Complex Complex::operator+(const Complex &op2) const
{
    return Complex(re + op2.re, im + op2.im);
}

inline Complex Complex::operator-(const Complex &op2) const
{
    return Complex(re - op2.re, im - op2.im);
}

inline Complex Complex::operator*(const Complex &op2) const
{
    return Complex(re * op2.re - im * op2.im,
                   re * op2.im + im * op2.re);
}

inline Complex Complex::operator/(const Complex &op2) const
{
    double dvs = op2.re * op2.re + op2.im+op2.im;
    return Complex((re * op2.re + im * op2.im) / dvs,
                   (re * op2.im + im * op2.re) / dvs);
}
main.cppC++ / 16 lines
#include "complex.hpp"

int main()
{
    Complex t, z(3, 4), a(1, 1), b(2, 3), c(1, -1);

    // Complex imag_1(0, 1);
    // t = z * imag_1;
    t = z * Complex(0, 1); // Anonymous
    t.Print();

    t = a + b + c; // Temporary
    t.Print();

    return 0;
}

10.4.16 Non-member operator functions

A non-member binary operator treats both operands as ordinary parameters, allowing implicit conversions on either side. This makes mixed complex-number arithmetic symmetric, provided competing member and non-member overloads do not make calls ambiguous.

A member operator cannot convert its left operand:

class Complex {
    double re, im;
public:
    Complex(double a_re = 0, double a_im = 0) { re = a_re; im = a_im; }
    Complex operator+(const Complex &op2) const
        { return Complex(re + op2.re, im + op2.im); }
};

Complex t(1, 2);
Complex u = t + 0.5;    // t.operator+(Complex(0.5))
Complex w = 0.5 + t;    // error: 0.5 cannot become the receiving object

A non-member operator takes both operands as parameters:

class Complex {
    double re, im;
public:
    Complex(double a_re = 0, double a_im = 0) { re = a_re; im = a_im; }
    double GetRe() const { return re; }
    double GetIm() const { return im; }
};

Complex operator+(const Complex &a, const Complex &b)
{
    return Complex(a.GetRe() + b.GetRe(), a.GetIm() + b.GetIm());
}

Complex t(1, 2);
Complex u = t + 0.5;    // operator+(t, Complex(0.5))
Complex w = 0.5 + t;    // operator+(Complex(0.5), t)
Detailed notes - 10.4.16: Non-member operator functions

1

a member Complex::operator+ can accept t + 0.5 through conversion

  • 0.5 becomes its explicit Complex argument
  • 0.5 + t cannot first convert 0.5 into the receiving object

2

a non-member operator+(const Complex&, const Complex&) treats both operands as parameters

  • conversions can apply on either side
  • use public component queries to construct the sum

binary member form: a.operator+(b)

non-member form: operator+(a, b)

  • equivalent-quality competing candidates can make a + b ambiguous
  • neither form automatically takes priority

3

non-member operations can extend a type's usable notation

  • useful when its class definition cannot be edited
  • the needed behavior must still be expressible through available access
Tests & experiments (4 files) - 10.4.16: Non-member operator functions
Section test16 (10-04)In catalog
MakefileMake / 21 lines
CFLAGS   = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS   = -lm

SRCS  = $(wildcard *.c *.cpp)
OBJS  = $(addsuffix .o, $(basename $(SRCS)))
PROGS = $(basename $(shell grep -l "^int main" $(SRCS) /dev/null))
MODS  = $(filter-out $(PROGS:=.o), $(OBJS))

all: $(PROGS)

libmods.a: $(MODS)
    ar crs $@ $^

$(PROGS): %: %.o libmods.a
    $(CXX) $^ $(LDLIBS) -o $@

$(OBJS): $(wildcard *.h *.hpp)

clean:
    rm -f *.o libmods.a $(PROGS)
complex.cppC++ / 7 lines
#include <cstdio>
#include "complex.hpp"

void Complex::Print() const
{
    printf("%g%+gi\n", re, im);
}
complex.hppC++ / 40 lines
#ifndef COMPLEX_HPP
#define COMPLEX_HPP

#include <math.h>

class Complex {
    double re, im;
public:
    Complex(double a_re = 0, double a_im = 0) : re(a_re), im(a_im) {}
    double Magnitude() const { return sqrt(re*re + im*im); }
    double Argument() const { return atan2(im, re); }
    double GetRe() const { return re; }
    double GetIm() const { return im; }
    void Print() const;
};

inline Complex operator+(const Complex &a, const Complex &b)
{
    return Complex(a.GetRe() + b.GetRe(), a.GetIm() + b.GetIm());
}

inline Complex operator-(const Complex &a, const Complex &b)
{
    return Complex(a.GetRe() - b.GetRe(), a.GetIm() - b.GetIm());
}

inline Complex operator*(const Complex &a, const Complex &b)
{
    return Complex(a.GetRe() * b.GetRe() - a.GetIm() * b.GetIm(),
                   a.GetRe() * b.GetIm() + a.GetIm() * b.GetRe());
}

inline Complex operator/(const Complex &a, const Complex &b)
{
    double dvs = b.GetRe() * b.GetRe() + b.GetIm() * b.GetIm();
    return Complex((a.GetRe() * b.GetRe() + a.GetIm() * b.GetIm()) / dvs,
                   (a.GetIm() * b.GetRe() - a.GetRe() * b.GetIm()) / dvs);
}

#endif
main.cppC++ / 16 lines
#include "complex.hpp"

int main()
{
    Complex t, z(3, 4), a(1, 1), b(2, 3), c(1, -1);

    // Complex imag_1(0, 1);
    // t = z * imag_1;
    t = z * Complex(0, 1); // Anonymous
    t.Print();

    t = a + b + c; // Temporary
    t.Print();

    return 0;
}

10.4.17 Friend functions and classes

Friendship grants selected external functions or classes access to hidden representation. It can support a non-member operator without exposing public fields, but expands the code responsible for maintaining the class's invariants.

class Complex {
    double re, im;
public:
    Complex(double a_re = 0, double a_im = 0) { re = a_re; im = a_im; }
    friend Complex operator+(const Complex &a, const Complex &b);
};

Complex operator+(const Complex &a, const Complex &b)
{
    return Complex(a.re + b.re, a.im + b.im);   // private access: a friend
}

A whole class can be a friend:

class Node {
    int value;
    Node *next;
    friend class List;      // List's methods may use value and next
};
Detailed notes - 10.4.17: Friend functions and classes

1

friend grants selected external code access to private implementation

  • a friend function can access the granting class's members
  • friend class B grants that access to B's member functions

2

friendship expands the code responsible for preserving invariants

  • friend definitions may be elsewhere in the program
  • use it deliberately, with the participating code understood

3

a non-member operator may need representation access

  • exposing every internal detail through public getters is not ideal
  • friendship can provide narrow access instead

4

declare the operator's prototype with friend inside Complex

  • its external definition can then read a.re, a.im, b.re and b.im
  • it remains a non-member with two explicit operands

5

ordinary functions and whole classes can also be friends

  • friend void f(...); or friend class B;
  • use whole-class access for closely related implementations
  • narrower friendship still exposes less than making all fields public

6

a non-member operator function need not be a friend

  • ordinary public methods may provide all the access it needs
  • overloading and friendship solve different problems
Tests & experiments (4 files) - 10.4.17: Friend functions and classes
Section test17 (10-04)In catalog
MakefileMake / 21 lines
CFLAGS   = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS   = -lm

SRCS  = $(wildcard *.c *.cpp)
OBJS  = $(addsuffix .o, $(basename $(SRCS)))
PROGS = $(basename $(shell grep -l "^int main" $(SRCS) /dev/null))
MODS  = $(filter-out $(PROGS:=.o), $(OBJS))

all: $(PROGS)

libmods.a: $(MODS)
    ar crs $@ $^

$(PROGS): %: %.o libmods.a
    $(CXX) $^ $(LDLIBS) -o $@

$(OBJS): $(wildcard *.h *.hpp)

clean:
    rm -f *.o libmods.a $(PROGS)
complex.cppC++ / 7 lines
#include <cstdio>
#include "complex.hpp"

void Complex::Print() const
{
    printf("%g%+gi\n", re, im);
}
complex.hppC++ / 44 lines
#ifndef COMPLEX_HPP
#define COMPLEX_HPP

#include <math.h>

class Complex {
    friend Complex operator+(const Complex&, const Complex&);
    friend Complex operator-(const Complex&, const Complex&);
    friend Complex operator*(const Complex&, const Complex&);
    friend Complex operator/(const Complex&, const Complex&);
    double re, im;
public:
    Complex(double a_re = 0, double a_im = 0) : re(a_re), im(a_im) {}
    double Magnitude() const { return sqrt(re*re + im*im); }
    double Argument() const { return atan2(im, re); }
    double GetRe() const { return re; }
    double GetIm() const { return im; }
    void Print() const;
};

inline Complex operator+(const Complex &a, const Complex &b)
{
    return Complex(a.re + b.re, a.im + b.im);
}

inline Complex operator-(const Complex &a, const Complex &b)
{
    return Complex(a.re - b.re, a.im - b.im);
}

inline Complex operator*(const Complex &a, const Complex &b)
{
    return Complex(a.re * b.re - a.im * b.im,
                   a.re * b.im + a.im * b.re);
}

inline Complex operator/(const Complex &a, const Complex &b)
{
    double dvs = b.re * b.re + b.im * b.im;
    return Complex((a.re * b.re + a.im * b.im) / dvs,
                   (a.im * b.re - a.re * b.im) / dvs);
}

#endif
main.cppC++ / 16 lines
#include "complex.hpp"

int main()
{
    Complex t, z(3, 4), a(1, 1), b(2, 3), c(1, -1);

    // Complex imag_1(0, 1);
    // t = z * imag_1;
    t = z * Complex(0, 1); // Anonymous
    t.Print();

    t = a + b + c; // Temporary
    t.Print();

    return 0;
}

10.4.18 Assignment operators

Assignment changes an existing object and commonly returns a reference to that object for chaining. Simple assignment must be a member, while compound assignments are independent overloads whose behavior must be defined consistently.

class Complex {
    double re, im;
public:
    Complex(double a_re = 0, double a_im = 0) { re = a_re; im = a_im; }
    Complex& operator=(const Complex &c)
        { re = c.re; im = c.im; return *this; }
    Complex& operator=(double x)
        { re = x; im = 0; return *this; }
    Complex& operator+=(const Complex &c)
        { re += c.re; im += c.im; return *this; }
};
Complex a, b, c(1, 2);
a = b = c;          // a = (b = c)
a += c;             // 2 + 4i: += is a separate operator
b = 7.5;            // operator=(double)

Simple assignment must be a member; compound assignment need not be:

Complex& operator=(Complex &a, double x);   // error: must be a member
Complex& operator-=(Complex &a, const Complex &b);  // allowed
Detailed notes - 10.4.18: Assignment operators

1

some overloadable operators have additional declaration rules

2

assignment is an expression operation in C and C++

  • its result can participate in another expression
  • simple operator= must be a member
  • correction: compound assignments such as operator+= may also be non-members; the source incorrectly extends the restriction to

them

3

an assignment operation normally returns the assigned-to object

  • commonly T&; the book's examples return const T& or void
  • return *this permits chaining without making an extra copy
  • operator= copies Complex's components
  • operator+= adds to the existing components

compound operations are independent overloads

  • defining + and = does not automatically define +=
  • preserve their expected mathematical relationship deliberately

4

assignment may accept a different source type

  • assigning double to Complex can set re to it and im to zero
  • copy assignment from the same class has special implicit-generation rules considered next
Tests & experiments (4 files) - 10.4.18: Assignment operators
Section test18 (10-04)In catalog
MakefileMake / 21 lines
CFLAGS   = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS   = -lm

SRCS  = $(wildcard *.c *.cpp)
OBJS  = $(addsuffix .o, $(basename $(SRCS)))
PROGS = $(basename $(shell grep -l "^int main" $(SRCS) /dev/null))
MODS  = $(filter-out $(PROGS:=.o), $(OBJS))

all: $(PROGS)

libmods.a: $(MODS)
    ar crs $@ $^

$(PROGS): %: %.o libmods.a
    $(CXX) $^ $(LDLIBS) -o $@

$(OBJS): $(wildcard *.h *.hpp)

clean:
    rm -f *.o libmods.a $(PROGS)
complex.cppC++ / 7 lines
#include <cstdio>
#include "complex.hpp"

void Complex::Print() const
{
    printf("%g%+gi\n", re, im);
}
complex.hppC++ / 54 lines
#ifndef COMPLEX_HPP
#define COMPLEX_HPP

#include <math.h>

class Complex {
    friend Complex operator+(const Complex&, const Complex&);
    friend Complex operator+=(Complex &a, const Complex &b);
    friend Complex operator-(const Complex&, const Complex&);
    friend Complex operator*(const Complex&, const Complex&);
    friend Complex operator/(const Complex&, const Complex&);
    double re, im;
public:
    Complex(double a_re = 0, double a_im = 0) : re(a_re), im(a_im) {}
    double Magnitude() const { return sqrt(re*re + im*im); }
    double Argument() const { return atan2(im, re); }
    double GetRe() const { return re; }
    double GetIm() const { return im; }
    Complex &operator=(const Complex &c)
        { re = c.re; im = c.im; return *this; }
    Complex &operator-=(const Complex &c)
        { re -= c.re; im -= c.im; return *this; }
    void Print() const;
};

inline Complex operator+(const Complex &a, const Complex &b)
{
    return Complex(a.re + b.re, a.im + b.im);
}

inline Complex operator+=(Complex &a, const Complex &b)
{
    return a.re += b.re; a.im += b.im; return a;
}

inline Complex operator-(const Complex &a, const Complex &b)
{
    return Complex(a.re - b.re, a.im - b.im);
}

inline Complex operator*(const Complex &a, const Complex &b)
{
    return Complex(a.re * b.re - a.im * b.im,
                   a.re * b.im + a.im * b.re);
}

inline Complex operator/(const Complex &a, const Complex &b)
{
    double dvs = b.re * b.re + b.im * b.im;
    return Complex((a.re * b.re + a.im * b.im) / dvs,
                   (a.im * b.re - a.re * b.im) / dvs);
}

#endif
main.cppC++ / 16 lines
#include "complex.hpp"

int main()
{
    Complex t, z(3, 4), a(1, 1), b(2, 3), c(1, -1);

    // Complex imag_1(0, 1);
    // t = z * imag_1;
    t = z * Complex(0, 1); // Anonymous
    t.Print();

    t += a + b + c; // Temporary
    t.Print();

    return 0;
}

10.4.19 Implicit special members

Compiler-generated special members operate member by member, so raw pointers do not automatically acquire deep-copy or cleanup behavior. A class can restrict copying, and some member types make generated operations unavailable.

A record-like type needs no handwritten special members:

struct Point {
    int x, y;
};

Point p1 = { 1, 2 };
Point p2 = p1;          // implicit copy: memberwise

In the book's subset, declaring copying private and leaving it undefined disables it:

class File {
    int fd;
    File(const File &);                 // not defined: no copying
    void operator=(const File &);       // not defined: no assignment
public:
    File() { fd = -1; }
    ~File() { if (fd != -1) close(fd); }
};

void use(File &f);      // references are still fine
File f1;
File f2(f1);            // error: the copy constructor is private

Declaring any constructor removes the implicit default one:

struct Pair {
    int a, b;
    Pair(int x) { a = b = x; }
};

Pair p;                 // error: no Pair()
Detailed notes - 10.4.19: Implicit special members

1

ordinary record-like classes remain usable without handwritten constructors

  • the compiler can supply special members where their rules permit

2

implicit copying initializes members from corresponding source members

  • class-type members use their copying behavior
  • pointer members copy pointer values, not owned allocations
  • an implicit declaration need not be usable: a member can prevent it

this section describes the book's older subset of special-member rules

3

a default constructor is implicitly declared if no constructor was declared

  • adding a constructor takes responsibility away from that default rule

4

default construction initializes class-type members through their defaults

  • ordinary scalar members are not thereby guaranteed useful values
  • explicitly initialize state that subsequent operations read

5

an implicit destructor destroys members as required by their types

  • a raw pointer's destruction does not delete its pointee

6

implicit copy assignment assigns corresponding members

  • class-type members use their own assignment operations
  • const or reference members can make implicit assignment unavailable
  • its ordinary return type is A&, correcting the source's const A&

7

omitting a copy constructor does not prohibit copying old-subset technique: declare copying and assignment private

  • outside code then cannot call them
  • references and pointers can still be passed
  • a noncopyable member can prevent implicit copying of its owner
  • friends and members still have private access
  • private empty definitions in the example should not be treated as valid implementations of ownership-preserving copying
Tests & experiments (4 files) - 10.4.19: Implicit special members
Section test19 (10-04)In catalog
MakefileMake / 21 lines
CFLAGS   = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS   = -lm

SRCS  = $(wildcard *.c *.cpp)
OBJS  = $(addsuffix .o, $(basename $(SRCS)))
PROGS = $(basename $(shell grep -l "^int main" $(SRCS) /dev/null))
MODS  = $(filter-out $(PROGS:=.o), $(OBJS))

all: $(PROGS)

libmods.a: $(MODS)
    ar crs $@ $^

$(PROGS): %: %.o libmods.a
    $(CXX) $^ $(LDLIBS) -o $@

$(OBJS): $(wildcard *.h *.hpp)

clean:
    rm -f *.o libmods.a $(PROGS)
implicit.cppC++ / 41 lines
#include <stdio.h>

struct Rec {
    const int id;               /* const field: fixed at creation */
    int &counter;               /* reference field: bound at creation */
    int value;                  /* ordinary field */

    Rec(int i, int &c, int v) : id(i), counter(c), value(v) {}
    const Rec &operator=(const Rec &o)
    {
        value = o.value;        /* copy only what can change */
        return *this;
    }
    void Print(const char *name) const
    {
        printf("  %s: id=%d counter=%d value=%d\n",
               name, id, counter, value);
    }
};

int main()
{
    int x = 10, y = 20;
    Rec a(1, x, 100), b(2, y, 200);
    Rec c = a;                  /* copy: c.id = 1, c.counter is x */

    printf("before:\n");
    a.Print("a");
    b.Print("b");
    c.Print("c");

    b = a;                      /* our operator=: only value */
    c.counter++;                /* c.counter is x, so a sees it too */

    printf("after b = a; c.counter++;\n");
    a.Print("a");
    b.Print("b");
    c.Print("c");
    printf("  x = %d, y = %d\n", x, y);
    return 0;
}
private.cppC++ / 14 lines
class A {
public:
    A() {}
private:
    A(const A &ref) {}
    void operator=(const A &ref) {}
};


int main()
{
    A a1, a2;
    // a2 = a1;
}
str.cppC++ / 79 lines
#include <stdio.h>
#include <string.h>

class Str {
    char *s;
    static char *Join(const char *a, const char *b);
public:
    Str(const char *a = "");                /* default + conversion */
    Str(const Str &o);                      /* copy constructor */
    ~Str() { delete[] s; }
    const Str &operator=(const Str &o);     /* assignment: Str = Str */
    const Str &operator=(const char *a);    /* assignment: Str = "..." */
    const Str &operator+=(const Str &o);    /* compound assignment */
    const char *Get() const { return s; }
};

/* new buffer holding a followed by b */
char *Str::Join(const char *a, const char *b)
{
    char *r = new char[strlen(a) + strlen(b) + 1];

    strcpy(r, a);
    strcat(r, b);
    return r;
}

Str::Str(const char *a)
{
    printf("  Str(const char *)\n");
    s = Join(a, "");
}

Str::Str(const Str &o)                      /* *this is new: s is garbage */
{
    printf("  Str(const Str &)          copy constructor\n");
    s = Join(o.s, "");                      /* just build */
}

const Str &Str::operator=(const Str &o)     /* *this exists: s is a buffer */
{
    printf("  operator=(const Str &)\n");
    char *n = Join(o.s, "");                /* build the new one first, */
    delete[] s;                             /* then drop the old one: */
    s = n;                                  /* safe even for a = a */
    return *this;
}

const Str &Str::operator=(const char *a)
{
    printf("  operator=(const char *)\n");
    char *n = Join(a, "");
    delete[] s;
    s = n;
    return *this;
}

const Str &Str::operator+=(const Str &o)
{
    printf("  operator+=(const Str &)\n");
    char *n = Join(s, o.s);                 /* safe even for a += a */
    delete[] s;
    s = n;
    return *this;
}

int main()
{
    printf("Str a(\"hello\");\n");  Str a("hello");
    printf("Str b = a;\n");         Str b = a;
    printf("Str c(a);\n");          Str c(a);
    printf("Str d;\n");             Str d;
    printf("d = a;\n");             d = a;
    printf("d = \"world\";\n");     d = "world";
    printf("d += a;\n");            d += a;
    printf("a = a; a += a;\n");     a = a; a += a;

    printf("a=%s b=%s c=%s d=%s\n", a.Get(), b.Get(), c.Get(), d.Get());
    return 0;
}

10.4.20 Indexing operators

An indexing operator can return a reference into expandable storage, while a const overload supplies read-only behavior. Resizing invalidates earlier element references, and the example also requires initialized elements and safe capacity calculations.

class IntArray {
    int *p;
    unsigned int size;
public:
    IntArray();
    ~IntArray() { delete [] p; }
    int& operator[](unsigned int idx) {
        if (idx >= size)
            Resize(idx);
        return p[idx];
    }
    int operator[](unsigned int idx) const {
        return idx < size ? p[idx] : 0;
    }
private:
    void Resize(unsigned int required_index);
    IntArray(const IntArray &);         // copying is disabled
    void operator=(const IntArray &);
};
IntArray::IntArray()
{
    size = 16;
    p = new int[size];
    for (unsigned int i = 0; i < size; i++)
        p[i] = 0;
}

void IntArray::Resize(unsigned int required_index)
{
    unsigned int new_size = size;
    while (new_size <= required_index)
        new_size *= 2;          // a real version must guard against overflow
    int *new_array = new int[new_size];
    for (unsigned int i = 0; i < new_size; i++)
        new_array[i] = i < size ? p[i] : 0;
    delete [] p;
    p = new_array;
    size = new_size;
}

The non-const version resizes; the const version never does:

IntArray a;
a[5] = 10;
a[100] = 20;                // grows the storage to 128 elements
a[100]++;

const IntArray &ca = a;
int x = ca[1000];           // 0, and no resizing
Detailed notes - 10.4.20: Indexing operators

1

built-in a[b] corresponds to *(a+b)

  • a class can provide operator[] with its own storage interpretation
  • the book uses a member with one explicit index parameter

2

IntArray example: storage grows as an index requires

  • begin with capacity 16
  • repeatedly double capacity until the requested index fits

3

private p and size hold storage and current capacity

  • destructor releases p with delete[]
  • copying and assignment are disabled to prevent shared ownership
  • Resize is an internal operation, not part of the client's interface

4

operator[] returns int& so an element can be read or modified

  • resize when idx >= size
  • then return p[idx]

Resize:

  • calculate enough capacity, allocate replacement storage
  • copy existing initialized values, release old storage
  • install the new pointer and capacity
  • returned element references are invalidated by later reallocation

correctness requirements omitted by the short example:

  • initialize elements before reading or copying their values
  • guard capacity doubling against overflow and impossible sizes

indexing need not use integers or physically contiguous storage

5

the modifying index operation cannot serve a const IntArray

  • resizing changes the object
  • returning a modifiable reference would expose mutable contents

6

members may be overloaded by trailing const

  • non-const objects select the suitable non-const overload
  • const objects require the const overload

7

the read-only overload should not resize

  • return the stored value when present
  • return zero for an out-of-capacity index in this example

8

int operator[](unsigned int idx) const supplies that behavior

  • returns by value, so callers cannot assign through it
  • in-range values still need initialization before being read

9

const overloading is available for other member functions too

10

the author rejects general array-like container classes for his style

  • cites maintenance costs and tension with his view of hidden objects
  • this is a design opinion, not a defect inherent in all containers
Tests & experiments (3 files) - 10.4.20: Indexing operators
Section test20 (10-04)In catalog
MakefileMake / 9 lines
CFLAGS   = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.c *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
int_array.cppC++ / 77 lines
class IntArray {
    int *p;
    unsigned int size;
public:
    IntArray() {
        size = 16;
        p = new int[size];
    }
    ~IntArray() { delete[] p; }
    IntArray(const IntArray& ref);
    const IntArray& operator=(const IntArray& ref);
    int& operator[](unsigned int idx);
    int operator[](unsigned int idx) const;
private:
    void Copy(const IntArray& ref);
    void Resize(unsigned int required_index);
};

IntArray::IntArray(const IntArray& ref)
{
    IntArray::Copy(ref);
}

const IntArray& IntArray::operator=(const IntArray& ref)
{
    if (this != &ref) {
        delete[] p;
        IntArray::Copy(ref);
    }
    return *this;
}

int& IntArray::operator[](unsigned int idx)
{
    if (idx >= size)
        Resize(idx);
    return p[idx];
}

int IntArray::operator[](unsigned int idx) const
{
    if (idx >= size)
        return 0;
    return p[idx];
}

void IntArray::Copy(const IntArray& ref)
{
    size = ref.size;
    p = new int[size];
    for (unsigned int i = 0; i < size; i++)
        p[i] = ref.p[i];
}

void IntArray::Resize(unsigned int required_index)
{
    unsigned int new_size = size;
    while (new_size <= required_index)
        new_size *= 2;
    int *new_array = new int[new_size];
    for (unsigned int i = 0; i < size; i++)
        new_array[i] = p[i];
    delete[] p;
    p = new_array;
    size = new_size;
}

int main()
{
    IntArray arr;
    arr[500] = 15;
    arr[1000] = 30;
    arr[10] = arr[500] + 1;
    arr[10]++;

    return 0;
}
int_array02.cppC++ / 93 lines
#include <stdio.h>
#include <stdlib.h>

class IntArray {
    enum { max_size = 1u << 30 };
    int *p;
    unsigned int size;
public:
    IntArray() {
        size = 16;
        p = new int[size]();
    }
    ~IntArray() { delete[] p; }
    IntArray(const IntArray& ref);
    const IntArray& operator=(const IntArray& ref);
    int& operator[](unsigned int idx);
    int operator[](unsigned int idx) const;
private:
    void Copy(const IntArray& ref);
    void Resize(unsigned int required_index);
};

IntArray::IntArray(const IntArray& ref)
{
    IntArray::Copy(ref);
}

const IntArray& IntArray::operator=(const IntArray& ref)
{
    if (this != &ref) {
        delete[] p;
        IntArray::Copy(ref);
    }
    return *this;
}

int& IntArray::operator[](unsigned int idx)
{
    if (idx >= size)
        Resize(idx);
    return p[idx];
}

int IntArray::operator[](unsigned int idx) const
{
    if (idx >= size)
        return 0;
    return p[idx];
}

void IntArray::Copy(const IntArray& ref)
{
    size = ref.size;
    p = new int[size];
    for (unsigned int i = 0; i < size; i++)
        p[i] = ref.p[i];
}

void IntArray::Resize(unsigned int required_index)
{
    unsigned int new_size = size;

    if (required_index >= max_size) {
        fprintf(stderr, "IntArray: index %u too large\n", required_index);
        abort();
    }
    while (new_size <= required_index)
        new_size *= 2;
    int *new_array = new int[new_size]();
    for (unsigned int i = 0; i < size; i++)
        new_array[i] = p[i];
    delete[] p;
    p = new_array;
    size = new_size;
}

int main()
{
    IntArray arr;
    arr[500] = 15;
    arr[1000] = 30;
    arr[10] = arr[500] + 1;
    arr[10]++;

    IntArray copy = arr;
    const IntArray &ro = copy;
    arr = arr;
    copy[10] = 0;
    printf("arr[10] = %d, arr[3] = %d, copy[10] = %d, ro[99999] = %d\n",
           arr[10], arr[3], copy[10], ro[99999]);

    return 0;
}

10.4.21 Increment and decrement operators

Prefix increment conventionally returns the updated object, while postfix returns a saved old value. A dummy int parameter distinguishes postfix overloads, and the saved local value must never be returned by reference.

class Counter {
    int n;
public:
    Counter() { n = 0; }
    Counter& operator++()           // ++c
        { n++; return *this; }
    Counter operator++(int)         // c++: the int only marks postfix
        { Counter old(*this); n++; return old; }
    int Get() const { return n; }
};
Counter c;
Counter a = c++;        // a is 0, c is 1
Counter b = ++c;        // b is 2, c is 2

The non-member forms take the operand as a parameter:

Counter& operator--(Counter &c);        // --c
Counter operator--(Counter &c, int);    // c--
Detailed notes - 10.4.21: Increment and decrement operators

1

prefix and postfix ++/-- need separate overloads

  • their conventional results differ even when the update is identical

2

prefix member form has no explicit parameters

  • operator++() or operator--()
  • a non-member version takes the operand as its one parameter

3

postfix form adds a dummy int parameter

  • member operator++(int) or operator--(int)
  • non-member form has the operand plus dummy int
  • the dummy parameter distinguishes the overload, not an increment size

the example's calls select first, third, second, fourth in that order

4

usual prefix behavior: update and return the updated object by reference

usual postfix behavior:

  • save a copy of the old value
  • update the original
  • return the saved value by value

never return a reference to the local saved copy

  • it is destroyed as the function exits
  • preserving postfix semantics can cost more for large objects
Tests & experiments (3 files) - 10.4.21: Increment and decrement operators
Section test21 (10-04)In catalog
MakefileMake / 9 lines
CFLAGS   = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.c *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
inc.cppC++ / 20 lines
#include <stdio.h>

class A {
public:
    void operator++() { printf("first\n"); }
    void operator--() { printf("second\n"); }
    void operator++(int) { printf("third\n"); }
    void operator--(int) { printf("fourth\n"); }
};

int main()
{
    A a;
    ++a;
    a++;
    --a;
    a--;

    return 0;
}
int.cppC++ / 21 lines
#include <stdio.h>

class MyInt {
    int i;
public:
    MyInt(int x) : i(x) {}
    operator int() const { return i; }
    const MyInt& operator++() { i++; return *this; }
    MyInt operator++(int) { MyInt tmp(*this); i++; return tmp; }
    void Print() const { printf("%d\n", i); }
};

int main()
{
    MyInt i(3);
    (++i).Print();
    (i++).Print();
    i.Print();

    return 0;
}

10.4.22 The arrow operator

An overloaded arrow operation returns a pointer or another pointer-like object until ordinary member access becomes possible. The owning-wrapper example combines this syntax with cleanup, requiring clear ownership and protection against empty or duplicate adoption.

struct s1 {
    int a, b;
};

class Pointer_s1 {
    s1 *p;
public:
    Pointer_s1(s1 *ptr = 0) { p = ptr; }
    ~Pointer_s1() { delete p; }
    void operator=(s1 *ptr) { if (ptr != p) { delete p; p = ptr; } }
    s1& operator*() const { return *p; }
    s1* operator->() const { return p; }
private:
    Pointer_s1(const Pointer_s1 &);         // no copying:
    void operator=(const Pointer_s1 &);     // it would delete twice
};
void f()
{
    Pointer_s1 p(new s1);
    p->a = 1;           // p.operator->()->a
    (*p).b = 2;
    p = new s1;         // deletes the first object
}                       // the destructor deletes the second
Detailed notes - 10.4.22: The arrow operator

1

operator-> supports objects that behave like pointers

  • allows extra behavior around ordinary member access

2

in p->a, p is an expression but a is a fixed member name

  • the member name is not computed as another runtime operand
  • this motivates the author's description of member-specific access

3

operator-> is a member with no explicit parameters

  • returns a pointer, or another object supporting operator->
  • the compiler repeats the operation until ordinary pointer access works
  • most wrappers simply return their stored pointer

4

Pointer_s1 owns an optional s1 pointer

  • constructor accepts a pointer or starts empty
  • destructor deletes the owned object
  • assignment from a raw pointer releases the old object and adopts new
  • copying the owning wrapper is disabled to avoid double deletion
  • operator* returns s1&; operator-> returns s1*

local owner: acquired objects are cleaned up on normal function exit

requirements for a correct owner:

  • do not dereference an empty wrapper
  • do not adopt storage already owned elsewhere
  • assigning its existing pointer must not delete and retain that pointer
Tests & experiments (10 files) - 10.4.22: The arrow operator
Section test22 (10-04)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
checked_pointer.cppC++ / 41 lines
#include <stdio.h>
#include <stdlib.h>

struct Person {
    const char *name;
    int age;
};

class PersonPtr {                       /* a pointer that checks itself */
    Person *p;
    const char *where;                  /* for the error message */
public:
    PersonPtr(Person *a, const char *w) : p(a), where(w) {}
    Person *operator->() const
    {
        if (!p) {
            fprintf(stderr, "%s: null Person pointer used\n", where);
            abort();
        }
        return p;
    }
};

static Person *find(Person *all, int n, const char *name)
{
    for (int i = 0; i < n; i++)
        if (all[i].name[0] == name[0])
            return &all[i];
    return 0;
}

int main()
{
    Person all[] = { { "Ada", 36 }, { "Ken", 81 } };
    PersonPtr a(find(all, 2, "Ken"), "lookup Ken");
    PersonPtr b(find(all, 2, "Bob"), "lookup Bob");

    printf("%s is %d\n", a->name, a->age);
    printf("%s is %d\n", b->name, b->age);      /* stops here, clearly */
    return 0;
}
const_ptr.cppC++ / 88 lines
/*
 * const_ptr.cpp: const methods of a class that holds a pointer
 *
 *   g++ -Wall -Wextra -ansi -pedantic const_ptr.cpp -o const_ptr
 *   ./const_ptr                        prints 25 61
 *
 * Add -DTRY=n to the g++ line to get one of the errors:
 *   1  a const method assigns to the field p
 *   2  fill gives the constant x another s1
 *   3  the const versions return const: both writes in fill fail
 *   4  the messages name the types of this, &p and &*p
 */
#include <stdio.h>

#ifndef TRY
#define TRY 0
#endif

struct s1 { int a, b; };

class Pointer_s1 {
    s1 *p;
public:
    Pointer_s1(s1 *ptr = 0) : p(ptr) {}
    ~Pointer_s1() { if (p) delete p; }
    s1 *operator=(s1 *ptr);
#if TRY == 3
    s1 &operator*() { return *p; }
    s1 *operator->() { return p; }
    const s1 &operator*() const { return *p; }
    const s1 *operator->() const { return p; }
#else
    s1 &operator*() const { return *p; }        /* p means this->p */
    s1 *operator->() const { return p; }
#endif
#if TRY == 1
    void Reset() const { p = 0; }
#endif
#if TRY == 4
    void InConst() const;
    void InPlain();
#endif
private:
    Pointer_s1(const Pointer_s1&) {}
    void operator=(const Pointer_s1&) {}
};

s1 *Pointer_s1::operator=(s1 *ptr)
{
    if (p)
        delete p;
    p = ptr;
    return p;
}

#if TRY == 4
void Pointer_s1::InConst() const        /* every line is wrong on purpose */
{
    static_cast<int>(this);
    static_cast<int>(&p);
    static_cast<int>(&*p);
}

void Pointer_s1::InPlain()
{
    static_cast<int>(this);
    static_cast<int>(&p);
    static_cast<int>(&*p);
}
#endif

void fill(const Pointer_s1& x)          /* x can't be changed here... */
{
    x->a = 25;                          /* ...but the s1 can */
    (*x).b = x->a + 36;
#if TRY == 2
    x = new s1;
#endif
}

int main()
{
    Pointer_s1 x;
    x = new s1;
    fill(x);
    printf("%d %d\n", x->a, x->b);
    return 0;
}
const_ptr01.cppC++ / 76 lines
#include <stdio.h>

#ifndef TRY
#define TRY 0
#endif

struct s1 { int a, b; };

class Pointer_s1 {
    s1 *p;
public:
    Pointer_s1(s1 *ptr = 0) : p(ptr) {}
    ~Pointer_s1() { if (p) delete p; }
    s1 *operator=(s1 *ptr);
#if TRY == 3
    s1 &operator*() { return *p; }
    s1 *operator->() { return p; }
    const s1 &operator*() const { return *p; }
    const s1 *operator->() const { return p; }
#else
    s1 &operator*() const { return *p; }        /* p means this->p */
    s1 *operator->() const { return p; }
#endif
#if TRY == 1
    void Reset() const { p = 0; }
#endif
#if TRY == 4
    void InConst() const;
    void InPlain();
#endif
private:
    Pointer_s1(const Pointer_s1&) {}
    void operator=(const Pointer_s1&) {}
};

s1 *Pointer_s1::operator=(s1 *ptr)
{
    if (p)
        delete p;
    p = ptr;
    return p;
}

#if TRY == 4
void Pointer_s1::InConst() const        /* every line is wrong on purpose */
{
    static_cast<int>(this);
    static_cast<int>(&p);
    static_cast<int>(&*p);
}

void Pointer_s1::InPlain()
{
    static_cast<int>(this);
    static_cast<int>(&p);
    static_cast<int>(&*p);
}
#endif

void fill(const Pointer_s1& x)          /* x can't be changed here... */
{
    x->a = 25;                          /* ...but the s1 can */
    (*x).b = x->a + 36;
#if TRY == 2
    x = new s1;
#endif
}

int main()
{
    Pointer_s1 x;
    x = new s1;
    fill(x);
    printf("%d %d\n", x->a, x->b);
    return 0;
}
const_ptr02.cppC++ / 29 lines
#include <stdio.h>

struct s1 {
    int a, b;
};

class Pointer_s1 {
    s1 *p;
public:
    Pointer_s1(s1 *ptr) : p(ptr) {}
    s1 *operator->() const { return p; }
    const void *Where() const { return &p; }
};

int main()
{
    s1 one, two;
    const Pointer_s1 x(&one);
    s1 *q = x.operator->();
    printf("x:       lies at %p\n", (void*)&x);
    printf("field p: lies at %p, holds %p\n", x.Where(), (void*)q);
    printf("q:       lies at %p, holds %p\n", (void*)&q, (void*)q);
    q = &two;                           /* q is the caller's own cell */
    printf("after q = &two:\n");
    printf("field p: lies at %p, holds %p\n", x.Where(),
           (void*)x.operator->());
    printf("q:       lies at %p, holds %p\n", (void*)&q, (void*)q);
    return 0;
}
const_ptr03.cppC++ / 40 lines
#include <stdio.h>

struct s1 {
    int a, b;
};

class Pointer_s1 {
    s1 *p;
public:
    Pointer_s1(s1 *ptr = 0) : p(ptr) {}
    s1 *operator=(s1 *ptr);
    s1& operator*() const { return *p; }
    s1* operator->() const { return p; }
    const void *Where() const { return &p; }
private:
    Pointer_s1(const Pointer_s1&) {}
    void operator=(const Pointer_s1&) {}
};

s1 *Pointer_s1::operator=(s1 *ptr)
{
    if (p)
        delete p;
    p = ptr;
    return p;
}

int main()
{
    s1 x;
    x.a = 3;
    x.b = 4;
    Pointer_s1 p;
    p = &x;
    s1 *q = p.operator->();
    printf("%p %p\n", (void*) q, (void*) &x);
    printf("%d %d\n", q->a, q->b);

    return 0;
}
iterator.cppC++ / 61 lines
#include <stdio.h>

struct Person {
    const char *name;
    int age;
};

class PersonList {
    struct Node {                       /* hidden list structure */
        Person data;
        Node *next;
    };
    Node *first;
public:
    class Iter {                        /* behaves like Person * */
        Node *n;
    public:
        Iter(Node *p) : n(p) {}
        Person *operator->() const { return &n->data; }
        Iter &operator++() { n = n->next; return *this; }
        bool AtEnd() const { return n == 0; }
    };
    PersonList() : first(0) {}
    ~PersonList();
    void Add(const char *name, int age);
    Iter Begin() const { return Iter(first); }
private:
    PersonList(const PersonList &);
    void operator=(const PersonList &);
};

PersonList::~PersonList()
{
    while (first) {
        Node *t = first;
        first = first->next;
        delete t;
    }
}

void PersonList::Add(const char *name, int age)
{
    Node *t = new Node;

    t->data.name = name;
    t->data.age = age;
    t->next = first;
    first = t;
}

int main()
{
    PersonList list;

    list.Add("Ada", 36);
    list.Add("Ken", 81);
    list.Add("Dennis", 70);
    for (PersonList::Iter it = list.Begin(); !it.AtEnd(); ++it)
        printf("%-7s %d\n", it->name, it->age);    /* like a pointer */
    return 0;
}
pointer.cppC++ / 29 lines
struct s1 {
    int a, b;
};

class Pointer_s1 {
    s1 *p;
public:
    Pointer_s1(s1 *ptr = 0) : p(ptr) {}
    ~Pointer_s1() { if (p) delete p; }
    s1 *operator=(s1 *ptr) {
        if (p)
            delete p;
        p = ptr;
        return p;
    }
    s1& operator*() const { return *p; }
    s1* operator->() const { return p; }
private:
    Pointer_s1(const Pointer_s1&) {}
    void operator=(const Pointer_s1&) {}
};

int main()
{
    Pointer_s1 p;
    p = new s1;
    p->a = 25;
    p->b = p->a + 36;
}
pointer02.cppC++ / 65 lines
#include <stdio.h>

struct s1 {
    int a, b;
    ~s1() { printf("  s1 deleted\n"); }
};

class Pointer_s1 {
    s1 *p;
public:
    Pointer_s1(s1 *ptr = 0) : p(ptr) {}
    ~Pointer_s1() { if (p) delete p; }
    s1 *operator=(s1 *ptr) {
        if (p)
            delete p;
        p = ptr;
        return p;
    }
    s1 &operator*() const { return *p; }
    s1 *operator->() const { return p; }
private:
    Pointer_s1(const Pointer_s1 &);             /* no copying */
    void operator=(const Pointer_s1 &);         /* no assignments */
};

int with_raw(int x)                 /* plain pointer */
{
    s1 *p = new s1;

    p->a = x;
    if (p->a < 0)
        return -1;                  /* forgot delete: leak */
    p->b = p->a + 36;
    if (p->b > 100)
        return 1;                   /* forgot delete: leak */
    int r = p->b;
    delete p;                       /* only this path frees */
    return r;
}

int with_owner(int x)               /* Pointer_s1 */
{
    Pointer_s1 p(new s1);

    p->a = x;
    if (p->a < 0)
        return -1;                  /* destructor deletes */
    p->b = p->a + 36;
    if (p->b > 100)
        return 1;                   /* destructor deletes */
    return p->b;                    /* destructor deletes */
}

int main()
{
    printf("with_raw(-5):\n");
    with_raw(-5);
    printf("with_raw(90):\n");
    with_raw(90);
    printf("with_owner(-5):\n");
    with_owner(-5);
    printf("with_owner(90):\n");
    with_owner(90);
    return 0;
}
pointer03.cppC++ / 57 lines
#include <stdio.h>

struct s1 {
    int a, b;
};

class Pointer_s1 {
    s1 *p;
public:
    Pointer_s1(s1 *ptr = 0) : p(ptr) {}
    ~Pointer_s1() { if (p) delete p; }
    s1 *operator=(s1 *ptr) {
        if (p)
            delete p;
        p = ptr;
        return p;
    }
    s1 &operator*() const { return *p; }
    s1 *operator->() const { return p; }
private:
    Pointer_s1(const Pointer_s1 &);             /* no copying */
    void operator=(const Pointer_s1 &);         /* no assignments */
};

static void print(const char *what, const s1 &s)    /* takes an s1 */
{
    printf("%-22s a = %d, b = %d\n", what, s.a, s.b);
}

static void twice(s1 &s)                            /* changes an s1 */
{
    s.a *= 2;
    s.b *= 2;
}

int main()
{
    Pointer_s1 p;
    s1 other = { 7, 8 };

    p = new s1;
    (*p).a = 25;                        /* same as p->a = 25 */
    (*p).b = (*p).a + 36;
    print("after (*p).a = ...:", *p);

    *p = other;                         /* copy a whole struct into it */
    print("after *p = other:", *p);

    twice(*p);                          /* pass the object itself */
    print("after twice(*p):", *p);

    s1 copy = *p;                       /* take a copy out */
    copy.a = 0;
    print("copy:", copy);
    print("*p unchanged:", *p);
    return 0;
}

10.4.23 Function-call operators

An object with operator() can be called like a function while retaining its own state. Overloads can accept different argument lists, making such objects callable function objects, also called functors.

#include <stdio.h>

class Fun {
public:
    void operator()() { printf("no arguments\n"); }
    void operator()(int a) { printf("one argument: %d\n", a); }
    void operator()(int a, int b) { printf("two arguments: %d, %d\n", a, b); }
};

int main()
{
    Fun f;

    f();
    f(100);
    f(25, 36);
    return 0;
}
no arguments
one argument: 100
two arguments: 25, 36
Detailed notes - 10.4.23: Function-call operators

1

operator() lets an object use function-call notation

  • void operator()() means a call with no explicit arguments
  • the book defines this operation as a class member

2

Fun overloads calls with zero, one and two integer arguments

  • f(), f(100), f(25, 36) select the corresponding implementations
  • each prints its own parameters

a callable object is often called a function object or functor

Tests & experiments (2 files) - 10.4.23: Function-call operators
Section test23 (10-04)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
functor.cppC++ / 19 lines
#include <stdio.h>

class Fun {
public:
    void operator()()
        { printf("fun0\n"); }
    void operator()(int a)
        { printf("fun1: %d\n", a); }
    void operator()(int a, int b)
        { printf("fun2: %d %d\n", a, b); }
};

int main()
{
    Fun f;
    f();
    f(100);
    f(25, 36);
}

10.4.24 Conversion operators

A conversion member defines conversion out of its class, including conversion to built-in types that cannot receive new constructors. Multiple implicit paths can become ambiguous, so named conversions are often easier to control.

class Fraction {
    int num, den;
public:
    Fraction(int a_num, int a_den) { num = a_num; den = a_den; }
    operator int() const { return num / den; }
    double ToDouble() const { return (double) num / den; }
};
Fraction a(7, 2);
int x;
x = a;                  // operator int(): x is 3
double d = a.ToDouble();    // an explicit, named conversion: 3.5
Detailed notes - 10.4.24: Conversion operators

1

constructors define conversion into their class

  • they cannot add a constructor to a built-in destination type
  • sometimes the source class can be edited but the destination cannot

conversion members provide conversion out of the source class

2

operator int() const defines conversion from the class to int

  • its name already identifies the destination type
  • no separate return type is written
  • int x; x = a can then use the conversion

3

multiple implicit conversion paths can produce ambiguity

  • the author usually prefers explicitly named conversion methods
  • the following proxy example gives a specific reason for a conversion
Tests & experiments (3 files) - 10.4.24: Conversion operators
Section test24 (10-04)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
conv.cppC++ / 38 lines
#include <stdio.h>

class A {                               /* counts events */
    int count;
public:
    A() : count(0) {}
    void Hit() { count++; }
    operator int() const { return count; }  /* A -> int */
};

static void show(int n)                 /* takes a plain int */
{
    printf("  show(%d)\n", n);
}

int main()
{
    A a;
    int x;

    a.Hit();
    a.Hit();
    a.Hit();

    x = a;                              /* x = a.operator int() */
    printf("x = %d\n", x);
    printf("a * 10 = %d\n", a * 10);    /* int * int */
    show(a);                            /* parameter is int */
    if (a)                              /* int in a condition */
        printf("a is not zero\n");
    switch (a) {                        /* int in switch */
    case 3:
        printf("exactly three\n");
        break;
    }
    printf("printf needs a cast: %d\n", (int)a);    /* ... converts nothing */
    return 0;
}
type.cppC++ / 13 lines
class A {
    int i;
public:
    operator int() const { return i; }
};

int main()
{
    A a;
    int x;
    x = a;
    return 0;
}

10.4.25 Example: a sparse array

Sparse indexing returns a proxy that delays access until reading or writing is known. Conversion reads absent entries as zero, while assignment creates or removes entries; compound updates and proxy-to-proxy assignment need their own correct operations.

operator[] returns a proxy that remembers the array and the index; reading and writing happen later, through the proxy's own operators:

class SparseArrayInt {
    struct Item {
        int index;
        int value;
        Item *next;
    };
    Item *first;
public:
    SparseArrayInt() : first(0) {}
    ~SparseArrayInt();
    class Interm {
        friend class SparseArrayInt;
        SparseArrayInt *master;
        int index;
        Interm(SparseArrayInt *a_master, int ind)
            : master(a_master), index(ind) {}
        int& Provide();         // find or create the entry
        void Remove();          // delete the entry, if any
    public:
        operator int() const;                       // read
        int operator=(int x);                       // write
        int operator=(const Interm &other) { return *this = int(other); }
        int operator+=(int x);
        int operator++();
        int operator++(int);
    };
    friend class Interm;
    Interm operator[](int idx) { return Interm(this, idx); }
    int operator[](int idx) const;
private:
    SparseArrayInt(const SparseArrayInt &);
    void operator=(const SparseArrayInt &);
};
SparseArrayInt arr;
arr[1000000] = 5;       // Interm::operator=(int): one list entry
arr[7] += 4;
arr[5] = arr[7];        // Interm::operator=(const Interm&)
int x = arr[123];       // Interm::operator int(): 0, nothing stored
arr[1000000] = 0;       // assigning zero removes the entry
Show the complete program
#include <stdio.h>

class SparseArrayInt {
    struct Item {
        int index;
        int value;
        Item *next;
    };
    Item *first;
public:
    SparseArrayInt() : first(0) {}
    ~SparseArrayInt();
    class Interm {
        friend class SparseArrayInt;
        SparseArrayInt *master;
        int index;
        Interm(SparseArrayInt *a_master, int ind)
            : master(a_master), index(ind) {}
        int& Provide();
        void Remove();
    public:
        operator int() const;
        int operator=(int x);
        int operator=(const Interm &other) { return *this = int(other); }
        int operator+=(int x);
        int operator++();
        int operator++(int);
    };
    friend class Interm;
    Interm operator[](int idx) { return Interm(this, idx); }
    int operator[](int idx) const;
private:
    SparseArrayInt(const SparseArrayInt &);
    void operator=(const SparseArrayInt &);
};

SparseArrayInt::~SparseArrayInt()
{
    while (first) {
        Item *tmp = first;
        first = first->next;
        delete tmp;
    }
}

int SparseArrayInt::operator[](int idx) const
{
    for (Item *tmp = first; tmp; tmp = tmp->next)
        if (tmp->index == idx)
            return tmp->value;
    return 0;
}

int& SparseArrayInt::Interm::Provide()
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    tmp = new Item;
    tmp->index = index;
    tmp->value = 0;             // missing from the book's listing
    tmp->next = master->first;
    master->first = tmp;
    return tmp->value;
}

void SparseArrayInt::Interm::Remove()
{
    Item **tmp;
    for (tmp = &master->first; *tmp; tmp = &(*tmp)->next) {
        if ((*tmp)->index == index) {
            Item *to_delete = *tmp;
            *tmp = (*tmp)->next;
            delete to_delete;
            return;
        }
    }
}

SparseArrayInt::Interm::operator int() const
{
    const SparseArrayInt *m = master;   // select the const operator[]
    return (*m)[index];
}

int SparseArrayInt::Interm::operator=(int x)
{
    if (x == 0)
        Remove();
    else
        Provide() = x;
    return x;
}

int SparseArrayInt::Interm::operator+=(int x)
{
    int& location = Provide();
    location += x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator++()
{
    int& location = Provide();
    int res = ++location;
    if (location == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator++(int)
{
    int& location = Provide();
    int res = location++;
    if (location == 0)
        Remove();
    return res;
}

int main()
{
    SparseArrayInt arr;

    arr[1000000] = 5;
    arr[7] = 3;
    arr[7] += 4;
    arr[42]++;
    arr[5] = arr[7];
    arr[1000000] = 0;
    int sum = arr[5] + arr[7] + arr[42] + arr[1000000] + arr[123];
    printf("%d %d %d %d %d\n", (int) arr[5], (int) arr[7], (int) arr[42],
           (int) arr[1000000], sum);
    return 0;
}
7 7 1 0 15
Detailed notes - 10.4.25: Example: a sparse array

1

sparse array: most positions contain a common value, usually zero

  • storing only exceptions avoids allocating every possible position

2

SparseArrayInt exposes integer indexing

  • stores nonzero entries as a linked list of index/value pairs
  • linear search is acceptable only when that list is small enough
  • private representation permits replacing the search structure later

3

const indexing is straightforward

  • search for the index
  • return its stored value, or zero if absent

4

modifiable indexing has two different uses: read and write

  • both select the non-const operator[] on a non-const array
  • a missing zero element has no stored int to return by reference
  • returning an int value alone would prevent assignment through []

5

creating a zero entry on every access would make assignment possible

  • but reading many absent positions would defeat sparse storage

6

remembering the last accessed node could permit later cleanup

  • repeated creation and removal would still cost time

7

operator[] cannot directly ask whether its result will be read or assigned

  • const overloading answers whether the array is const, not whether this particular expression is a read

8

return a small intermediate proxy object instead

  • stores the array's address and the selected index
  • postpones the actual access until its result is used

9

proxy conversion to int implements reading

proxy assignment implements writing

  • absent index reads as zero
  • assigning nonzero creates or updates an entry
  • assigning zero removes its entry

other modifying syntax needs corresponding proxy overloads

  • +=, both ++ forms, and analogous operations do not appear for free

10

Interm helpers:

  • Provide finds or creates the selected entry and returns int&
  • Remove deletes that entry if present

11

SparseArrayInt disables copying and assignment in this example

  • owns the linked list and deletes all nodes in its destructor
  • nested Interm and the array grant access needed for cooperation

proxy implementation:

  • assignment removes zero, otherwise writes through Provide
  • += updates the value, saves the result, removes a resulting zero
  • prefix ++ returns the new value; postfix ++ returns the old one
  • conversion searches without creating a missing entry

Provide: search first, otherwise prepend a new node

  • correction: initialize its value to 0 before returning the reference
  • the listing omits this, making += and ++ read an uninitialized int

Remove: use a pointer to the link that leads to the selected node

  • redirect that link around the node and delete it
  • this handles the first node without a separate head case

additional proxy case requiring an explicit operation:

  • arr[i] = arr[j] must assign the value read from the right proxy
  • implicit proxy copy assignment would merely copy proxy bookkeeping
  • a retained proxy also requires its owning array to remain alive
The indexing result carries the array and index until its use determines the operation.
A proxy separates reading a cell from writing it. Open full size - Editable SVG
Examples & tests (6 files) - 10.4.25: Example: a sparse array
Book exampleBook example: sparse.cppIn catalog
sparse.cppC++ / 193 lines
// The SparseArray demo
// Copyright (c) Andrey Vikt. Stolyarov, 2010-2025
// This is just a sample program for a book devoted to C++, see
// http://www.stolyarov.info/books/cppintro for details.
// No rights restricted; do whatever you want with this code,
// if you really want to.


#include <stdio.h>

class SparseArrayInt {
    struct Item {
        int index;
        int value;
        Item *next;
    };
    Item *first;
public:
    SparseArrayInt() : first(0) {}
    ~SparseArrayInt();
    class Interm {
        friend class SparseArrayInt;
        SparseArrayInt *master;
        int index;
        Interm(SparseArrayInt *a_master, int ind)
            : master(a_master), index(ind) {}
        int& Provide();
        void Remove();
    public:
        operator int();
        int operator=(int x);
        int operator+=(int x);
        int operator++();
        int operator++(int);
    };
    friend class Interm;

    Interm operator[](int idx)
        { return Interm(this, idx); }
    int operator[](int idx) const;

    int NonzeroCount() const;

private:
    SparseArrayInt(const SparseArrayInt&) {}
    void operator=(const SparseArrayInt&) {}
};

SparseArrayInt::~SparseArrayInt()
{
    while(first) {
        Item *tmp = first;
        first = first->next;
        delete tmp;
    }
}

int SparseArrayInt::operator[](int idx) const
{
    Item* tmp;
    for(tmp = first; tmp; tmp = tmp->next)
        if(tmp->index == idx)
            return tmp->value;
    return 0;
}

int SparseArrayInt::NonzeroCount() const
{
    int r = 0;
    for(Item *tmp = first; tmp; tmp = tmp->next)
        r++;
    return r;
}

int& SparseArrayInt::Interm::Provide()
{
    Item* tmp;
    for(tmp = master->first; tmp; tmp = tmp->next)
        if(tmp->index == index)
            return tmp->value;
    tmp = new Item;
    tmp->index = index;
    tmp->next = master->first;
    master->first = tmp;
    return tmp->value;
}

void SparseArrayInt::Interm::Remove()
{
    Item** tmp;
    for(tmp = &(master->first); *tmp; tmp = &(*tmp)->next) {
        if((*tmp)->index == index) {
            Item *to_delete = *tmp;
            *tmp = (*tmp)->next;
            delete to_delete;
            return;
        }
    }
}

int SparseArrayInt::Interm::operator=(int x)
{
    if(x == 0)
        Remove();
    else
        Provide() = x;
    return x;
}

int SparseArrayInt::Interm::operator+=(int x)
{
    int& location = Provide();
    location += x;
    int res = location;
    if(res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator++()
{
    int& location = Provide();
    location++;
    int res = location;
    if(location == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator++(int)
{
    int& location = Provide();
    int res = location;
    location++;
    if(location == 0)
        Remove();
    return res;
}

SparseArrayInt::Interm::operator int()
{
    Item* tmp;
    for(tmp = master->first; tmp; tmp = tmp->next)
        if(tmp->index == index)
            return tmp->value;
    return 0;
}

static void do_query(SparseArrayInt &array, char *str)
{
    int idx, r;
    r = sscanf(str, "%d", &idx);
    if(r != 1) {
        printf("Invalid index\n");
        return;
    }
    printf("** array[%d] == %d\n", idx, (int) (array[idx]));
}

static void do_assign(SparseArrayInt &array, char *str)
{
    int idx, val, r;
    r = sscanf(str, "%d %d", &idx, &val);
    if(r != 2) {
        printf("Invalid numbers\n");
        return;
    }
    array[idx] = val;
}

int main()
{
    char buf[1024];
    SparseArrayInt array;
    while(fgets(buf, sizeof(buf), stdin)) {
        switch(buf[0]) {
        case '?':
            do_query(array, buf+1);
            break;
        case '!':
            do_assign(array, buf+1);
            break;
        case '#':
            printf("%d items now\n", array.NonzeroCount());
            break;
        case 'q':
            return 0;
        default:
            printf("Unknown action, must be '?', '!', '#' or 'q'\n");
        }
    }
    return 0;
}
Section test25 (10-04)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
sparse.cppC++ / 142 lines
#include <stdio.h>

class SparseArrayInt {
    struct Item {
        int index;
        int value;
        Item *next;
    };
    Item *first;
public:
    SparseArrayInt() : first(0) {}
    ~SparseArrayInt();
    class Interm {
        friend class SparseArrayInt;
        SparseArrayInt *master;
        int index;
        Interm(SparseArrayInt *a_master, int ind)
            : master(a_master), index(ind) {}
        int& Provide();
        void Remove();
    public:
        operator int();
        int operator=(int x);
        int operator+=(int x);
        int operator++();
        int operator++(int);
    };
    friend class Interm;

    Interm operator[](int idx) { return Interm(this, idx); };
    int operator[](int idx) const;
private:
    SparseArrayInt(const SparseArrayInt&) {}
    void operator=(const SparseArrayInt&) {}
};

SparseArrayInt::~SparseArrayInt()
{
    while (first) {
        Item *tmp = first;
        first = first->next;
        delete tmp;
    }
}

int SparseArrayInt::operator[](int idx) const
{
    Item *tmp;
    for (tmp = first; tmp; tmp = tmp->next)
        if (tmp->index == idx)
            return tmp->value;
    return 0;
}

int SparseArrayInt::Interm::operator=(int x)
{
    if (x == 0)
        Remove();
    else
        Provide() = x;
    return x;
}

int SparseArrayInt::Interm::operator+=(int x)
{
    int& location = Provide();
    location += x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator++()
{
    int& location = Provide();
    location++;
    int res = location;
    if (location == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator++(int)
{
    int& location = Provide();
    int res = location;
    location++;
    if (location == 0)
        Remove();
    return res;
}

SparseArrayInt::Interm::operator int()
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    return 0;
}

int& SparseArrayInt::Interm::Provide()
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    tmp = new Item;
    tmp->index = index;
    tmp->next = master->first;
    master->first = tmp;
    return tmp->value;
}

void SparseArrayInt::Interm::Remove()
{
    Item **tmp;
    for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
        if ((*tmp)->index == index) {
            Item *to_delete = *tmp;
            *tmp = (*tmp)->next;
            delete to_delete;
            return;
        }
}

int main()
{
    SparseArrayInt arr;
    int x;

    x = arr[500];
    arr[300] = 50;
    arr[200] = 0;

    arr[15] += 100;
    x = arr[200]++;

    printf("%d\n", x);
    return 0;
}
sparse01.cppC++ / 157 lines
#include <stdio.h>

class SparseArrayInt {
    struct Item {
        int index;
        int value;
        Item *next;
    };
    Item *first;
public:
    SparseArrayInt() : first(0) {}
    ~SparseArrayInt();
    class Interm {
        friend class SparseArrayInt;
        SparseArrayInt *master;
        int index;
        Interm(SparseArrayInt *a_master, int ind)
            : master(a_master), index(ind) {}
        int& Provide();
        void Remove();
    public:
        operator int();
        int operator=(int x);
        int operator+=(int x);
        int operator++();
        int operator++(int);
    };
    friend class Interm;

    Interm operator[](int idx) { return Interm(this, idx); };
    int operator[](int idx) const;
private:
    SparseArrayInt(const SparseArrayInt&) {}
    void operator=(const SparseArrayInt&) {}
};

SparseArrayInt::~SparseArrayInt()
{
    while (first) {
        Item *tmp = first;
        first = first->next;
        delete tmp;
    }
}

int SparseArrayInt::operator[](int idx) const
{
    Item *tmp;
    for (tmp = first; tmp; tmp = tmp->next)
        if (tmp->index == idx)
            return tmp->value;
    return 0;
}

int SparseArrayInt::Interm::operator=(int x)
{
    if (x == 0)
        Remove();
    else
        Provide() = x;
    return x;
}

int SparseArrayInt::Interm::operator+=(int x)
{
    int& location = Provide();
    location += x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator++()
{
    int& location = Provide();
    location++;
    int res = location;
    if (location == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator++(int)
{
    int& location = Provide();
    int res = location;
    location++;
    if (location == 0)
        Remove();
    return res;
}

SparseArrayInt::Interm::operator int()
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    return 0;
}

int& SparseArrayInt::Interm::Provide()
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    tmp = new Item;
    tmp->index = index;
    tmp->value = 0;
    tmp->next = master->first;
    master->first = tmp;
    return tmp->value;
}

void SparseArrayInt::Interm::Remove()
{
    Item **tmp;
    for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
        if ((*tmp)->index == index) {
            Item *to_delete = *tmp;
            *tmp = (*tmp)->next;
            delete to_delete;
            return;
        }
}

int main()
{
    SparseArrayInt arr;
    int x;

    x = arr[500];
    printf("Initial arr[500]: %d\n", x);

    arr[300] = 50;
    printf("After arr[300] = 50: %d\n", int(arr[300]));

    arr[200] = 0;
    printf("After arr[200] = 0: %d\n", int(arr[200]));

    arr[15] += 100;
    printf("After arr[15] += 100: %d\n", int(arr[15]));

    x = arr[200]++;
    printf("After arr[200]++: returned %d, stored %d\n",
           x, int(arr[200]));

    arr[300] = 0;
    printf("After removing arr[300]: %d\n", int(arr[300]));

    arr[15] += -100;
    printf("After arr[15] += -100: %d\n", int(arr[15]));

    return 0;
}
sparse02.cppC++ / 156 lines
#include <stdio.h>

class SparseArrayInt {
    struct Item {
        int index;
        int value;
        Item *next;
    };
    Item *first;
    class Interm {
        friend class SparseArrayInt;
        Item *first;
        int index;
        Interm(Item *a_first, int ind)
            : first(a_first), index(ind) {}
        int& Provide();
        void Remove();
    public:
        operator int();
        int operator=(int x);
        int operator+=(int x);
        int operator++();
        int operator++(int);
    };
public:
    SparseArrayInt() : first(0) {}
    ~SparseArrayInt();

    Interm operator[](int idx) { return Interm(first, idx); };
    int operator[](int idx) const;
private:
    SparseArrayInt(const SparseArrayInt&) {}
    void operator=(const SparseArrayInt&) {}
};

SparseArrayInt::~SparseArrayInt()
{
    while (first) {
        Item *tmp = first;
        first = first->next;
        delete tmp;
    }
}

int SparseArrayInt::operator[](int idx) const
{
    Item *tmp;
    for (tmp = first; tmp; tmp = tmp->next)
        if (tmp->index == idx)
            return tmp->value;
    return 0;
}

int SparseArrayInt::Interm::operator=(int x)
{
    if (x == 0)
        Remove();
    else
        Provide() = x;
    return x;
}

int SparseArrayInt::Interm::operator+=(int x)
{
    int& location = Provide();
    location += x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator++()
{
    int& location = Provide();
    location++;
    int res = location;
    if (location == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator++(int)
{
    int& location = Provide();
    int res = location;
    location++;
    if (location == 0)
        Remove();
    return res;
}

SparseArrayInt::Interm::operator int()
{
    Item *tmp;
    for (tmp = first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    return 0;
}

int& SparseArrayInt::Interm::Provide()
{
    Item *tmp;
    for (tmp = first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    tmp = new Item;
    tmp->index = index;
    tmp->value = 0;
    tmp->next = first;
    first = tmp;
    return tmp->value;
}

void SparseArrayInt::Interm::Remove()
{
    Item **tmp;
    for (tmp = &(first); *tmp; tmp = &(*tmp)->next)
        if ((*tmp)->index == index) {
            Item *to_delete = *tmp;
            *tmp = (*tmp)->next;
            delete to_delete;
            return;
        }
}

int main()
{
    SparseArrayInt arr;
    int x;

    x = arr[500];
    printf("Initial arr[500]: %d\n", x);

    arr[300] = 50;
    printf("After arr[300] = 50: %d\n", int(arr[300]));

    arr[200] = 0;
    printf("After arr[200] = 0: %d\n", int(arr[200]));

    arr[15] += 100;
    printf("After arr[15] += 100: %d\n", int(arr[15]));

    x = arr[200]++;
    printf("After arr[200]++: returned %d, stored %d\n",
           x, int(arr[200]));

    arr[300] = 0;
    printf("After removing arr[300]: %d\n", int(arr[300]));

    arr[15] += -100;
    printf("After arr[15] += -100: %d\n", int(arr[15]));

    return 0;
}
sparse03.cppC++ / 281 lines
#include <stdio.h>

class SparseArrayInt {
    struct Item {
        int index;
        int value;
        Item *next;
    };
    Item *first;
public:
    SparseArrayInt() : first(0) {}
    ~SparseArrayInt();
    class Interm {
        friend class SparseArrayInt;
        SparseArrayInt *master;
        int index;
        Interm(SparseArrayInt *a_master, int ind)
            : master(a_master), index(ind) {}
        int& Provide();
        void Remove();
    public:
        operator int();
        int operator=(int x);

        int operator+=(int x);
        int operator-=(int x);
        int operator*=(int x);
        int operator/=(int x);
        int operator%=(int x);

        int operator<<=(int x);
        int operator>>=(int x);

        int operator|=(int x);
        int operator&=(int x);
        int operator^=(int x);

        int operator++();
        int operator++(int);
        int operator--();
        int operator--(int);
    };

    Interm operator[](int idx) { return Interm(this, idx); };
    int operator[](int idx) const;
private:
    SparseArrayInt(const SparseArrayInt&) {}
    void operator=(const SparseArrayInt&) {}
};

SparseArrayInt::~SparseArrayInt()
{
    while (first) {
        Item *tmp = first;
        first = first->next;
        delete tmp;
    }
}

int SparseArrayInt::operator[](int idx) const
{
    Item *tmp;
    for (tmp = first; tmp; tmp = tmp->next)
        if (tmp->index == idx)
            return tmp->value;
    return 0;
}

int SparseArrayInt::Interm::operator=(int x)
{
    if (x == 0)
        Remove();
    else
        Provide() = x;
    return x;
}

int SparseArrayInt::Interm::operator+=(int x)
{
    int& location = Provide();
    location += x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator-=(int x)
{
    int& location = Provide();
    location -= x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator*=(int x)
{
    int& location = Provide();
    location *= x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator/=(int x)
{
    int& location = Provide();
    location /= x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator%=(int x)
{
    int& location = Provide();
    location %= x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator<<=(int x)
{
    int& location = Provide();
    location <<= x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator>>=(int x)
{
    int& location = Provide();
    location >>= x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator|=(int x)
{
    int& location = Provide();
    location |= x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator&=(int x)
{
    int& location = Provide();
    location &= x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator^=(int x)
{
    int& location = Provide();
    location ^= x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator++()
{
    int& location = Provide();
    location++;
    int res = location;
    if (location == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator++(int)
{
    int& location = Provide();
    int res = location;
    location++;
    if (location == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator--()
{
    int& location = Provide();
    location--;
    int res = location;
    if (location == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator--(int)
{
    int& location = Provide();
    int res = location;
    location--;
    if (location == 0)
        Remove();
    return res;
}

SparseArrayInt::Interm::operator int()
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    return 0;
}

int& SparseArrayInt::Interm::Provide()
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    tmp = new Item;
    tmp->index = index;
    tmp->value = 0;
    tmp->next = master->first;
    master->first = tmp;
    return tmp->value;
}

void SparseArrayInt::Interm::Remove()
{
    Item **tmp;
    for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
        if ((*tmp)->index == index) {
            Item *to_delete = *tmp;
            *tmp = (*tmp)->next;
            delete to_delete;
            return;
        }
}

int main()
{
    SparseArrayInt arr;
    int x;

    x = arr[500];
    printf("Initial arr[500]: %d\n", x);

    arr[300] = 50;
    printf("After arr[300] = 50: %d\n", int(arr[300]));

    arr[200] = 0;
    printf("After arr[200] = 0: %d\n", int(arr[200]));

    arr[15] += 100;
    printf("After arr[15] += 100: %d\n", int(arr[15]));

    x = arr[200]++;
    printf("After arr[200]++: returned %d, stored %d\n",
           x, int(arr[200]));

    arr[300] = 0;
    printf("After removing arr[300]: %d\n", int(arr[300]));

    arr[15] += -100;
    printf("After arr[15] += -100: %d\n", int(arr[15]));

    return 0;
}

10.4.26 Static data members and methods

Static data belongs to the class rather than each instance, and static methods have no implicit receiver. Shared mutable members create global-style coupling, while static creation methods can use class access rights to control construction.

A static data member is declared in the class and defined once, outside it:

class A {
public:
    static int the_static_field;    // declaration
};

int A::the_static_field = 0;        // definition, in one .cpp file
A::the_static_field = 5;
A obj;
obj.the_static_field++;             // the same variable: now 6

The author recommends static data mainly for shared constant tables:

class Weekday {
    static const char *const names[7];
    int day;
public:
    Weekday(int d) { day = d; }
    const char *Name() const { return names[day]; }
};

const char *const Weekday::names[7] = {
    "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
};

A static method has no this, but keeps private access. With a private constructor, it can control how objects are created:

class Connection {
    int fd;
    Connection(int a_fd) { fd = a_fd; }
public:
    static Connection *Open(const char *name);
    ~Connection() { close(fd); }
};

Connection *Connection::Open(const char *name)
{
    int fd = open(name, O_RDWR);
    if (fd == -1)
        return 0;
    return new Connection(fd);      // private constructor: allowed here
}
Connection *c = Connection::Open("/dev/null");
Connection c2(3);       // error: the constructor is private
Detailed notes - 10.4.26: Static data members and methods

1

static members belong to the class independently of individual objects

  • can be used even when no instance exists

2

a static data member has static storage duration and class scope

  • normal public/private access rules still apply

3

one shared data member exists for the class

  • it is not repeated inside each object's storage

4

static int the_static_field inside the class is a declaration

  • the book's non-inline form also needs a definition

5

this resembles an extern declaration of a global variable

  • putting the class declaration in many modules must not allocate independent copies of the supposed shared field

6

define it once outside the class: int A::the_static_field = 0

  • normally in one implementation file, not the shared header

7

public static members can be named through an object or as A::member

  • mutable shared state has the same coupling risks as globals
  • a static list head fixes one list for the whole class
  • later needing two independent lists can require redesign

8

the author recommends static data mainly for immutable shared information

  • transition tables, diagnostic strings or command tables
  • this is his design rule, not a restriction imposed by C++

9

static method: a class-scoped function without an implicit receiver

  • mark its declaration static
  • do not repeat static on the out-of-class definition

10

call through Cls::TheStaticMethod(...) or through an object

  • there is no this parameter
  • non-static fields and methods still require an actual object
  • that object may be passed in, obtained elsewhere, or constructed

11

static methods retain the class's private access rights

  • access control is class-wide
  • private constructors plus a public static creation method can control how instances are made
Tests & experiments (3 files) - 10.4.26: Static data members and methods
Section test26 (10-04)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
factory.cppC++ / 47 lines
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

class File {
    int fd;                             /* always a valid descriptor */
    File(int d) : fd(d) {}              /* private: only Open creates */
    File(const File &);
    void operator=(const File &);
public:
    static File *Open(const char *name);
    ~File() { close(fd); }
    int Read(char *buf, int size) { return read(fd, buf, size); }
};

File *File::Open(const char *name)      /* can refuse: returns 0 */
{
    int d = open(name, O_RDONLY);

    if (d == -1)
        return 0;                       /* no object is created at all */
    return new File(d);
}

static void show_first_line(const char *name)
{
    File *f = File::Open(name);         /* no object needed to call it */
    char buf[80];
    int n, i;

    if (!f) {
        printf("%s: cannot open\n", name);
        return;
    }
    n = f->Read(buf, sizeof(buf));
    for (i = 0; i < n && buf[i] != '\n'; i++)
        ;
    printf("%s: %.*s\n", name, i, buf);
    delete f;
}

int main()
{
    show_first_line("/etc/hostname");
    show_first_line("/no/such/file");
    return 0;
}
table.cppC++ / 142 lines
#include <stdio.h>
#include <string.h>

/* ---------- 1. transition table of a finite state machine ---------- */

class Turnstile {
public:
    enum State { locked, unlocked };
    enum Event { coin, push };
private:
    State state;
    static const State table[2][2];     /* [state][event] -> new state */
    static const char *const names[2];
public:
    Turnstile() : state(locked) {}
    void Step(Event e) { state = table[state][e]; }
    const char *Name() const { return names[state]; }
};

const Turnstile::State Turnstile::table[2][2] = {
    /*               coin      push   */
    /* locked   */ { unlocked, locked },
    /* unlocked */ { unlocked, locked }
};
const char *const Turnstile::names[2] = { "locked", "unlocked" };

/* ---------- 2. diagnostic messages ---------- */

class Parser {
public:
    enum Error { ok, no_digits, too_long, bad_char };
private:
    static const char *const messages[];
public:
    static Error Check(const char *s);
    static const char *Message(Error e) { return messages[e]; }
};

const char *const Parser::messages[] = {
    "ok",
    "no digits",
    "number too long",
    "not a digit"
};

Parser::Error Parser::Check(const char *s)
{
    int i;

    for (i = 0; s[i]; i++)
        if (s[i] < '0' || s[i] > '9')
            return bad_char;
    if (i == 0)
        return no_digits;
    if (i > 9)
        return too_long;
    return ok;
}

/* ---------- 3. command names -> functions ---------- */

class Calc {
    int value;
    struct Command {
        const char *name;
        void (*run)(Calc &c);
    };
    static const Command commands[];
    static void Inc(Calc &c) { c.value++; }
    static void Dbl(Calc &c) { c.value *= 2; }
    static void Clr(Calc &c) { c.value = 0; }
public:
    Calc() : value(0) {}
    bool Do(const char *cmd);
    int Value() const { return value; }
};

const Calc::Command Calc::commands[] = {
    { "inc", Calc::Inc },
    { "dbl", Calc::Dbl },
    { "clr", Calc::Clr },
    { 0, 0 }                            /* end marker */
};

bool Calc::Do(const char *cmd)
{
    int i;

    for (i = 0; commands[i].name; i++)
        if (strcmp(commands[i].name, cmd) == 0) {
            commands[i].run(*this);
            return true;
        }
    return false;
}

/* ---------- demo ---------- */

static void demo_turnstile()
{
    Turnstile t;
    Turnstile::Event ev[] = { Turnstile::push, Turnstile::coin,
                              Turnstile::coin, Turnstile::push };
    const char *evname[] = { "coin", "push" };

    printf("turnstile: %s\n", t.Name());
    for (int i = 0; i < 4; i++) {
        t.Step(ev[i]);
        printf("  %s -> %s\n", evname[ev[i]], t.Name());
    }
}

static void demo_parser()
{
    const char *inputs[] = { "123", "", "12a", "12345678901" };

    printf("parser:\n");
    for (int i = 0; i < 4; i++)
        printf("  \"%s\": %s\n", inputs[i],
               Parser::Message(Parser::Check(inputs[i])));
}

static void demo_calc()
{
    Calc c;
    const char *cmds[] = { "inc", "inc", "dbl", "sqrt", "dbl" };

    printf("calc:\n");
    for (int i = 0; i < 5; i++) {
        bool known = c.Do(cmds[i]);
        printf("  %-4s -> %d%s\n", cmds[i], c.Value(),
               known ? "" : "  (unknown command)");
    }
}

int main()
{
    demo_turnstile();
    demo_parser();
    demo_calc();
    return 0;
}

10.5 Exception handling

Exceptions provide a separate path for propagating failures through callers to a suitable handler. Their usefulness must be weighed against implementation costs and application constraints; the author's objections target particular choices, not the general mechanism.

Detailed notes - 10.5: Exception handling

1

the author distinguishes the useful exception idea from its implementation

  • criticizes runtime support, code size and throwing costs in C++
  • actual costs depend on implementation and workload

2

some projects deliberately disable exceptions

  • the book retains the topic despite its preference for a small subset

3

exceptions can reduce the work needed for complete error propagation

  • compare against code that actually checks all failures
  • assess resource and performance costs for the application

4

exception handling is not unique to C++

  • criticisms of this implementation do not disprove the general idea

5

the author proposes identifying exceptions by stable object addresses

  • offered as an alternative design, not C++ syntax
  • its claimed simplicity and performance are the author's argument

6

understanding exceptions remains useful for other languages and designs

7

the author recommends reserving throws for exceptional failures

  • repeatedly throwing for routine loop exits can be costly
  • ordinary return and explicit control flow suit ordinary completion

8

understand the mechanism's consequences before adopting it

Tests & experiments (3 files) - 10.5: Exception handling
Section test00 (10-05)In catalog
MakefileMake / 9 lines
CXXFLAGS = -O0 -S -fverbose-asm -masm=intel ex.cpp -o ex.s
%.s: %.cpp
    $(CXX) $(CXXFLAGS) -S $< -o $@

%.calls: %.s
    c++filt < $< | grep -E "^[a-z].*:$$|call"

clean:
    rm -f *.s
ex.cppC++ / 28 lines
#include <stdio.h>

struct A {
    ~A() { printf("~A\n"); }
};

void g(int x)
{
    if (x)
        throw 42;
}

void f(int x)
{
    A a;
    g(x);
}

int main()
{
    try {
        f(1);
    }
    catch (int e) {
        printf("caught %d\n", e);
    }
    return 0;
}
ex.sAssembly / 272 lines
    .file   "ex.cpp"
    .intel_syntax noprefix
# GNU C++17 (Debian 14.2.0-19) version 14.2.0 (x86_64-linux-gnu)
#   compiled by GNU C version 14.2.0, GMP version 6.3.0, MPFR version 4.2.1, MPC version 1.3.1, isl version isl-0.27-GMP

# warning: MPFR header version 4.2.1 differs from library version 4.2.2.
# GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
# options passed: -masm=intel -mtune=generic -march=x86-64 -O0 -fasynchronous-unwind-tables
    .text
    .section    .rodata
.LC0:
    .string "~A"
    .section    .text._ZN1AD2Ev,"axG",@progbits,_ZN1AD5Ev,comdat
    .align 2
    .weak   _ZN1AD2Ev
    .type   _ZN1AD2Ev, @function
_ZN1AD2Ev:
.LFB1:
    .cfi_startproc
    .cfi_personality 0x9b,DW.ref.__gxx_personality_v0
    .cfi_lsda 0x1b,.LLSDA1
    push    rbp #
    .cfi_def_cfa_offset 16
    .cfi_offset 6, -16
    mov rbp, rsp    #,
    .cfi_def_cfa_register 6
    sub rsp, 16 #,
    mov QWORD PTR -8[rbp], rdi  # this, this
# ex.cpp:4:     ~A() { printf("~A\n"); }
    lea rax, .LC0[rip]  # tmp98,
    mov rdi, rax    #, tmp98
    call    puts@PLT    #
# ex.cpp:4:     ~A() { printf("~A\n"); }
    nop 
    leave   
    .cfi_def_cfa 7, 8
    ret 
    .cfi_endproc
.LFE1:
    .section    .gcc_except_table._ZN1AD2Ev,"aG",@progbits,_ZN1AD5Ev,comdat
.LLSDA1:
    .byte   0xff
    .byte   0xff
    .byte   0x1
    .uleb128 .LLSDACSE1-.LLSDACSB1
.LLSDACSB1:
.LLSDACSE1:
    .section    .text._ZN1AD2Ev,"axG",@progbits,_ZN1AD5Ev,comdat
    .size   _ZN1AD2Ev, .-_ZN1AD2Ev
    .weak   _ZN1AD1Ev
    .set    _ZN1AD1Ev,_ZN1AD2Ev
    .text
    .globl  _Z1gi
    .type   _Z1gi, @function
_Z1gi:
.LFB3:
    .cfi_startproc
    push    rbp #
    .cfi_def_cfa_offset 16
    .cfi_offset 6, -16
    mov rbp, rsp    #,
    .cfi_def_cfa_register 6
    sub rsp, 16 #,
    mov DWORD PTR -4[rbp], edi  # x, x
# ex.cpp:9:     if (x)
    cmp DWORD PTR -4[rbp], 0    # x,
    je  .L4 #,
# ex.cpp:10:         throw 42;
    mov edi, 4  #,
    call    __cxa_allocate_exception@PLT    #
# ex.cpp:10:         throw 42;
    mov DWORD PTR [rax], 42 # MEM[(int *)_4],
    mov edx, 0  #,
    lea rcx, _ZTIi[rip] # tmp100,
    mov rsi, rcx    #, tmp100
    mov rdi, rax    #, _4
    call    __cxa_throw@PLT #
.L4:
# ex.cpp:11: }
    nop 
    leave   
    .cfi_def_cfa 7, 8
    ret 
    .cfi_endproc
.LFE3:
    .size   _Z1gi, .-_Z1gi
    .globl  _Z1fi
    .type   _Z1fi, @function
_Z1fi:
.LFB4:
    .cfi_startproc
    .cfi_personality 0x9b,DW.ref.__gxx_personality_v0
    .cfi_lsda 0x1b,.LLSDA4
    push    rbp #
    .cfi_def_cfa_offset 16
    .cfi_offset 6, -16
    mov rbp, rsp    #,
    .cfi_def_cfa_register 6
    push    rbx #
    sub rsp, 40 #,
    .cfi_offset 3, -24
    mov DWORD PTR -36[rbp], edi # x, x
# ex.cpp:16:     g(x);
    mov eax, DWORD PTR -36[rbp] # tmp99, x
    mov edi, eax    #, tmp99
.LEHB0:
    call    _Z1gi   #
.LEHE0:
# ex.cpp:17: }
    lea rax, -17[rbp]   # tmp100,
    mov rdi, rax    #, tmp100
    call    _ZN1AD1Ev   #
    jmp .L8 #
.L7:
    mov rbx, rax    # tmp102,
    lea rax, -17[rbp]   # tmp101,
    mov rdi, rax    #, tmp101
    call    _ZN1AD1Ev   #
    mov rax, rbx    # D.3446, tmp102
    mov rdi, rax    #, D.3446
.LEHB1:
    call    _Unwind_Resume@PLT  #
.LEHE1:
.L8:
    mov rbx, QWORD PTR -8[rbp]  #,
    leave   
    .cfi_def_cfa 7, 8
    ret 
    .cfi_endproc
.LFE4:
    .section    .gcc_except_table,"a",@progbits
.LLSDA4:
    .byte   0xff
    .byte   0xff
    .byte   0x1
    .uleb128 .LLSDACSE4-.LLSDACSB4
.LLSDACSB4:
    .uleb128 .LEHB0-.LFB4
    .uleb128 .LEHE0-.LEHB0
    .uleb128 .L7-.LFB4
    .uleb128 0
    .uleb128 .LEHB1-.LFB4
    .uleb128 .LEHE1-.LEHB1
    .uleb128 0
    .uleb128 0
.LLSDACSE4:
    .text
    .size   _Z1fi, .-_Z1fi
    .section    .rodata
.LC1:
    .string "caught %d\n"
    .text
    .globl  main
    .type   main, @function
main:
.LFB5:
    .cfi_startproc
    .cfi_personality 0x9b,DW.ref.__gxx_personality_v0
    .cfi_lsda 0x1b,.LLSDA5
    push    rbp #
    .cfi_def_cfa_offset 16
    .cfi_offset 6, -16
    mov rbp, rsp    #,
    .cfi_def_cfa_register 6
    push    rbx #
    sub rsp, 24 #,
    .cfi_offset 3, -24
# ex.cpp:22:         f(1);
    mov edi, 1  #,
.LEHB2:
    call    _Z1fi   #
.LEHE2:
.L13:
# ex.cpp:27:     return 0;
    mov eax, 0  # _11,
    jmp .L17    #
.L15:
# ex.cpp:24:     catch (int e) {
    cmp rdx, 1  # D.3448,
    je  .L12    #,
    mov rdi, rax    #, D.3449
.LEHB3:
    call    _Unwind_Resume@PLT  #
.LEHE3:
.L12:
# ex.cpp:24:     catch (int e) {
    mov rdi, rax    #, _1
    call    __cxa_begin_catch@PLT   #
# ex.cpp:24:     catch (int e) {
    mov eax, DWORD PTR [rax]    # tmp108, *_6
    mov DWORD PTR -20[rbp], eax # e, tmp108
# ex.cpp:25:         printf("caught %d\n", e);
    mov eax, DWORD PTR -20[rbp] # tmp109, e
    mov esi, eax    #, tmp109
    lea rax, .LC1[rip]  # tmp110,
    mov rdi, rax    #, tmp110
    mov eax, 0  #,
.LEHB4:
    call    printf@PLT  #
.LEHE4:
# ex.cpp:26:     }
    call    __cxa_end_catch@PLT #
    jmp .L13    #
.L16:
    mov rbx, rax    # tmp111,
    call    __cxa_end_catch@PLT #
    mov rax, rbx    # D.3450, tmp111
    mov rdi, rax    #, D.3450
.LEHB5:
    call    _Unwind_Resume@PLT  #
.LEHE5:
.L17:
# ex.cpp:28: }
    mov rbx, QWORD PTR -8[rbp]  #,
    leave   
    .cfi_def_cfa 7, 8
    ret 
    .cfi_endproc
.LFE5:
    .section    .gcc_except_table
    .align 4
.LLSDA5:
    .byte   0xff
    .byte   0x9b
    .uleb128 .LLSDATT5-.LLSDATTD5
.LLSDATTD5:
    .byte   0x1
    .uleb128 .LLSDACSE5-.LLSDACSB5
.LLSDACSB5:
    .uleb128 .LEHB2-.LFB5
    .uleb128 .LEHE2-.LEHB2
    .uleb128 .L15-.LFB5
    .uleb128 0x1
    .uleb128 .LEHB3-.LFB5
    .uleb128 .LEHE3-.LEHB3
    .uleb128 0
    .uleb128 0
    .uleb128 .LEHB4-.LFB5
    .uleb128 .LEHE4-.LEHB4
    .uleb128 .L16-.LFB5
    .uleb128 0
    .uleb128 .LEHB5-.LFB5
    .uleb128 .LEHE5-.LEHB5
    .uleb128 0
    .uleb128 0
.LLSDACSE5:
    .byte   0x1
    .byte   0
    .align 4
    .long   DW.ref._ZTIi-.
.LLSDATT5:
    .text
    .size   main, .-main
    .hidden DW.ref._ZTIi
    .weak   DW.ref._ZTIi
    .section    .data.rel.local.DW.ref._ZTIi,"awG",@progbits,DW.ref._ZTIi,comdat
    .align 8
    .type   DW.ref._ZTIi, @object
    .size   DW.ref._ZTIi, 8
DW.ref._ZTIi:
    .quad   _ZTIi
    .hidden DW.ref.__gxx_personality_v0
    .weak   DW.ref.__gxx_personality_v0
    .section    .data.rel.local.DW.ref.__gxx_personality_v0,"awG",@progbits,DW.ref.__gxx_personality_v0,comdat
    .align 8
    .type   DW.ref.__gxx_personality_v0, @object
    .size   DW.ref.__gxx_personality_v0, 8
DW.ref.__gxx_personality_v0:
    .quad   __gxx_personality_v0
    .globl  __gxx_personality_v0
    .ident  "GCC: (Debian 14.2.0-19) 14.2.0"
    .section    .note.GNU-stack,"",@progbits

10.5.1 Error situations and their handling

The code detecting a failure often lacks the context to decide recovery, reporting, or termination. Exceptions help propagate that failure to a policy-setting layer without requiring every intermediate function to repeat return-code checks.

Propagating a failure by return codes takes code at every level:

int f10(void);          /* returns -1 on failure */

int f9(void)
{
    int res;

    res = f10();
    if (res == -1)
        return -1;      /* f8 does the same with f9, and so on up to f1 */
    /* ... */
    return 0;
}
Detailed notes - 10.5.1: Error situations and their handling

1

operations can fail because external preconditions do not hold

  • unavailable file, unreachable server, invalid mathematical input
  • failure need not imply a bug in the implementing function

2

detecting failure is easier than deciding the appropriate response

  • printing ERROR and exiting can destroy valuable user work
  • a failed editor save should not terminate the editor automatically

3

error reporting depends on the surrounding application

  • a terminal message, GUI interaction and a log have different uses
  • low-level or embedded code may have no direct reporting channel

4

the same failure can be fatal, recoverable or expected

  • ask for another filename
  • try another server
  • search the next directory after a failed file-open attempt

5

policy belongs at the level that understands the whole operation

  • reusable low-level functions report failure to their callers
  • designated application code decides about messages and termination

6

return-code propagation requires work at every intermediate call

  • f10 fails, f9 checks and returns failure, then f8, and so on
  • each function needs a way to represent and propagate that failure

7

the effort tempts programmers to omit checks

  • an ignored failure can appear later under difficult-to-reproduce use

8

exception mechanisms provide language support for this propagation task

10.5.2 The general exception mechanism

A throw searches active calling contexts for a matching handler and skips ordinary remaining work while unwinding. This separates exceptional failure from the function's normal result, even when its return type has no spare error value.

Some results have no spare value to report failure:

int a = atoi("0");      // 0: valid input
int b = atoi("abc");    // 0 as well: invalid input looks the same

With exceptions, the levels in between need no checks at all:

void f2();

void f10()
{
    // ...
    throw "f10 failed";     // leaves f10, f9, ..., f2 without returning
}

void f1()
{
    try {
        f2();               // f2 calls f3, ..., which calls f10
    }
    catch (const char *msg) {
        fprintf(stderr, "%s\n", msg);
    }
}
Detailed notes - 10.5.2: The general exception mechanism

1

a return type may have no spare value for reporting failure

  • atoi cannot distinguish invalid input from valid "0" by its result

exceptions add a different completion route

  • either produce the ordinary result or report exceptional failure

2

exceptions are independent of the OOP paradigm

  • several different language families provide related mechanisms
  • the book later connects them with more general continuations

3

a throw searches active calling contexts for a matching handler

  • intermediate functions need not repeat ordinary failure checks
  • their normal remaining statements are skipped while unwinding
  • f10's failure can reach a handler associated with f1

4

main can provide a useful outer handling boundary

  • it surrounds much ordinary application work
  • initialization before main and destruction afterward are outside it

10.5.3 Throwing exceptions

A thrown value carries diagnostic information, and its type determines possible handlers. The file-counting example throws on open failure; its normal result counts newline characters and still needs separate handling of read errors.

int line_count_in_file(const char *name)
{
    FILE *f = fopen(name, "r");
    if (!f)
        throw "couldn't open the file";
    int n = 0;
    for (;;) {
        int c = fgetc(f);
        if (c == EOF)
            break;
        if (c == '\n')
            n++;
    }
    fclose(f);
    return n;
}

Any copyable value can be thrown; its type selects the handler:

throw 27;           // an int exception
Detailed notes - 10.5.3: Throwing exceptions

1

throw expression creates an exception

  • its type selects possible handlers
  • its value carries information about the failure
  • built-in values and suitable class objects can be thrown

2

line_count_in_file example:

  • open the named file
  • throw a const char* message if opening fails
  • otherwise read characters, count '\n', close and return the count

this counts newline characters, not an unterminated final text line

  • a complete reader would also distinguish an I/O error from EOF

throw 27 would instead create an int exception

  • dedicated exception classes usually express failures more precisely
An exception transfers control to a matching handler and destroys automatic objects on the way.
Stack unwinding releases fully constructed local owners. Open full size - Editable SVG
Tests & experiments (2 files) - 10.5.3: Throwing exceptions
Section test04 (10-05-03)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
exeptions.cppC++ / 36 lines
#include <stdio.h>

unsigned int line_count_in_file(const char *file_name)
{
    FILE *f = fopen(file_name, "r");
    if (!f)
        throw "cound't open the file";
    int n = 0;
    int c = 0;
    while ((c = fgetc(f)) != EOF)
        if (c == '\n')
            n++;
    fclose(f);
    return n;
}

int main(int argc, char **argv)
{
    if (argc < 2) {
        fprintf(stderr, "No file name\n");
        return 1;
    }

    try {
        int res = line_count_in_file(argv[1]);
        printf("The file %s contains %d lines\n",
               argv[2], res);
    }
    catch (const char *exception) {
        fprintf(stderr, "Exception (string): %s\n",
                exception);
        return 2;
    }

    return 0;
}

10.5.4 Handling exceptions

A try block defines the execution interval whose failures its ordered catch clauses handle. Unmatched exceptions continue outward, and a bare throw rethrows the current exception so another layer can decide what to do.

#include <stdio.h>

int line_count_in_file(const char *name)
{
    FILE *f = fopen(name, "r");
    if (!f)
        throw "couldn't open the file";
    int n = 0;
    for (;;) {
        int c = fgetc(f);
        if (c == EOF)
            break;
        if (c == '\n')
            n++;
    }
    fclose(f);
    return n;
}

int main(int argc, char **argv)
{
    if (argc < 2) {
        fprintf(stderr, "No file name given\n");
        return 1;
    }
    try {
        int n = line_count_in_file(argv[1]);
        printf("The file %s contains %d lines\n", argv[1], n);
    }
    catch (const char *exception) {
        fprintf(stderr, "Exception (string): %s\n", exception);
        return 1;
    }
    return 0;
}
Exception (string): couldn't open the file

Handlers are tried in order, and at most one of them runs. throw; passes the current exception on to an outer handler:

void process();
void log_error(const char *msg);
try {
    process();
}
catch (const char *msg) {
    log_error(msg);     // local work first
    throw;              // then let an outer handler decide
}
catch (int code) {
    fprintf(stderr, "error code %d\n", code);
}
Detailed notes - 10.5.4: Handling exceptions

1

handle a failure where the required recovery policy is known

  • code allowed to communicate with the user can request new input

2

a handler surrounds an interval of execution

  • applies to exceptions from its block and functions called indirectly
  • textual nesting of the throwing function is unnecessary

3

try { ... } is followed by one or more catch clauses

  • catch's parameter type identifies accepted exceptions
  • its name provides access to the exception value

4

file-counting main:

  • reject a missing filename before calling the worker
  • place the call and success output inside try
  • catch(const char*) prints the error and returns failure status

on a throw, neither the worker's remainder nor try's remainder executes

5

an exception can originate arbitrarily far down the call chain

  • the active try block can still handle it

6

the thrown C++ string literal produces a const char* exception

  • catch(char*) cannot remove that const qualification

7

multiple handlers are considered in written order

  • the first suitable one handles the exception
  • only one of the sibling catch clauses runs
  • redundant handlers for an already covered case are ineffective

8

handler matching has different conversion rules from function calls

9

a catch clause handles throws from its associated try execution

  • an exception thrown by one catch is not handled by its siblings

10

without a matching handler, propagation continues outward

  • other active try blocks may provide the matching catch
  • an ultimately unhandled exception leads to termination

11

throw; rethrows the currently handled exception

  • useful after local work when the present layer cannot fully recover

10.5.5 Catch-all handlers

A final catch-all handler accepts unknown exception types without exposing their value. It can perform cleanup and rethrow, though resource-owning objects can often replace repeated manual cleanup paths.

Without automatic cleanup, a raw pointer needs a catch-all handler:

void work(int *data);

void process(int n)
{
    int *data = new int[n];
    try {
        work(data);
    }
    catch (...) {
        delete [] data;     // exceptional path
        throw;
    }
    delete [] data;         // normal path
}

As an outer fallback, catch (...) goes after the specific handlers:

void run_application();

int guarded_run()
{
    try {
        run_application();
    }
    catch (const char *msg) {
        fprintf(stderr, "%s\n", msg);
        return 1;
    }
    catch (...) {
        fprintf(stderr, "unknown exception\n");
        return 1;
    }
    return 0;
}
Detailed notes - 10.5.5: Catch-all handlers

1

catch(...) accepts an exception regardless of its type

  • no named parameter exposes the value
  • place it after specific handlers
  • can provide an outer fallback for unknown library exceptions

cleanup-and-rethrow example:

  • allocate an array before entering try
  • normal path deletes it after try
  • exceptional path catches anything, deletes it and uses throw;
  • throwing skips the ordinary delete after the handler

without this cleanup, a raw pointer's scope exit would leak its allocation

Tests & experiments (2 files) - 10.5.5: Catch-all handlers
Section test05 (10-05)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
dots.cppC++ / 27 lines
#include <stdio.h>

void f(int n, int d)
{
    int *p = new int[n];
    try {
        if (d == 0)
            throw 1;
    }
    catch (...) {
        delete[] p;
        throw;
    }
    delete[] p;
}

int main()
{
    try {
        f(5, 0);
    }
    catch (...) {
        fprintf(stderr, "some exception\n");
        return 1;
    }
    return 0;
}

10.5.6 Exception classes

Dedicated exception classes distinguish failure categories and carry structured context such as filenames and saved error codes. Their copying and cleanup must preserve owned information safely, including when constructing the exception itself fails.

class FileException {
    int err_code;
    char *filename;
    char *comment;
public:
    FileException(const char *fn, const char *cmt);
    FileException(const FileException &other);
    ~FileException();
    const char *GetName() const { return filename; }
    const char *GetComment() const { return comment; }
    int GetErrno() const { return err_code; }
private:
    static char *strdup(const char *str);
    void operator=(const FileException &);      // assignment disabled
};

FileException::FileException(const char *fn, const char *cmt)
{
    err_code = errno;       // save errno before anything changes it
    filename = strdup(fn);
    comment = strdup(cmt);
}

FileException::FileException(const FileException &other)
{
    err_code = other.err_code;
    filename = strdup(other.filename);
    comment = strdup(other.comment);
}

FileException::~FileException()
{
    delete [] filename;
    delete [] comment;
}

char *FileException::strdup(const char *str)
{
    char *res = new char[strlen(str) + 1];
    strcpy(res, str);
    return res;
}
FILE *open_for_reading(const char *name)
{
    FILE *f = fopen(name, "r");
    if (!f)
        throw FileException(name, "couldn't open for reading");
    return f;
}

A const reference in the handler avoids another copy:

try {
    FILE *f = open_for_reading("data.txt");
    // ...
}
catch (const FileException &ex) {
    fprintf(stderr, "File exception: %s (%s): %s\n",
            ex.GetName(), ex.GetComment(), strerror(ex.GetErrno()));
}

In production code the constructor must also release filename if allocating comment throws.

Show the complete program
#include <errno.h>
#include <stdio.h>
#include <string.h>

class FileException {
    int err_code;
    char *filename;
    char *comment;
public:
    FileException(const char *fn, const char *cmt);
    FileException(const FileException &other);
    ~FileException();
    const char *GetName() const { return filename; }
    const char *GetComment() const { return comment; }
    int GetErrno() const { return err_code; }
private:
    static char *strdup(const char *str);
    void operator=(const FileException &);
};

FileException::FileException(const char *fn, const char *cmt)
{
    err_code = errno;
    filename = strdup(fn);
    comment = strdup(cmt);
}

FileException::FileException(const FileException &other)
{
    err_code = other.err_code;
    filename = strdup(other.filename);
    comment = strdup(other.comment);
}

FileException::~FileException()
{
    delete [] filename;
    delete [] comment;
}

char *FileException::strdup(const char *str)
{
    char *res = new char[strlen(str) + 1];
    strcpy(res, str);
    return res;
}

int line_count_in_file(const char *name)
{
    FILE *f = fopen(name, "r");
    if (!f)
        throw FileException(name, "couldn't open for reading");
    int n = 0;
    for (;;) {
        int c = fgetc(f);
        if (c == EOF)
            break;
        if (c == '\n')
            n++;
    }
    fclose(f);
    return n;
}

int main(int argc, char **argv)
{
    if (argc < 2) {
        fprintf(stderr, "No file name given\n");
        return 1;
    }
    try {
        int n = line_count_in_file(argv[1]);
        printf("The file %s contains %d lines\n", argv[1], n);
    }
    catch (const FileException &ex) {
        fprintf(stderr, "File exception: %s (%s): %s\n",
                ex.GetName(), ex.GetComment(), strerror(ex.GetErrno()));
        return 1;
    }
    return 0;
}
File exception: /nonexistent/file (couldn't open for reading): No such file or directory
Detailed notes - 10.5.6: Exception classes

1

failures often need several pieces of context

  • filename, operation description and saved errno
  • one integer or string is an awkward combined representation

2

unrelated subsystems may throw the same built-in type

  • type-only matching then cannot distinguish their different meanings

3

dedicated exception classes solve both problems

  • fields carry structured diagnostic information
  • distinct types identify different failure categories or subsystems

4

the exception object must survive the throwing function's scope

  • it is not a reference to a destroyed local object
  • copying, when required, must preserve its owned information
  • an implicit copy constructor is sufficient when members copy safely

5

FileException stores errno, a copied filename and a copied comment

  • capture errno before other operations can change it
  • private static strdup allocates with new[] and copies the string
  • copy constructor creates independent string allocations
  • destructor uses delete[] on both strings

catch(const FileException &ex) avoids a second handler-parameter copy

  • query methods supply filename, comment and error code
  • strerror translates the saved code for reporting

ownership details still need completion in production code

  • if the second allocation throws, release the first allocation
  • define or disable copy assignment to avoid shallow pointer assignment
Tests & experiments (2 files) - 10.5.6: Exception classes
Section test06 (10-05)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
file_exception.cppC++ / 80 lines
#include <stdio.h>
#include <errno.h>
#include <string.h>

class FileException {
    int err_code;
    char *filename;
    char *comment;
public:
    FileException(const char *fn, const char *cmt);
    FileException(const FileException& other);
    ~FileException();
    const char *GetName() const { return filename; }
    const char *GetComment() const { return comment; }
    int GetErrno() const { return err_code; }
private:
    static char *strdup(const char *str);
};

FileException::FileException(const char *fn, const char *cmt)
{
    err_code = errno;
    filename = strdup(fn);
    comment = strdup(cmt);
}

FileException::FileException(const FileException& other)
{
    err_code = other.err_code;
    filename = strdup(other.filename);
    comment = strdup(other.comment);
}

FileException::~FileException()
{
    delete[] filename;
    delete[] comment;
}

char *FileException::strdup(const char *str)
{
    char *res = new char[strlen(str)+1];
    strcpy(res, str);
    return res;
}

unsigned int line_count_in_file(const char *file_name)
{
    FILE *f = fopen(file_name, "r");
    if (!f)
        throw FileException(file_name, "cound't open the file");
    int n = 0;
    int c = 0;
    while ((c = fgetc(f)) != EOF)
        if (c == '\n')
            n++;
    fclose(f);
    return n;
}

int main(int argc, char **argv)
{
    if (argc < 2) {
        fprintf(stderr, "No file name\n");
        return 1;
    }

    try {
        int res = line_count_in_file(argv[1]);
        printf("The file %s contains %d lines\n",
               argv[2], res);
    }
    catch (const FileException &ex) {
        fprintf(stderr, "File exception: %s (%s): %s\n",
                ex.GetName(), ex.GetComment(), strerror(ex.GetErrno()));
        return 2;
    }

    return 0;
}

10.5.7 Automatic cleanup

Stack unwinding destroys fully constructed automatic objects as their scopes are left. Resource-owning destructors therefore provide the same cleanup on exceptional exits and normal returns, reducing manual catch-and-rethrow code.

Unwinding runs the destructors of the local objects it leaves:

#include <stdio.h>

class A {
public:
    A() { printf("A acquired\n"); }
    ~A() { printf("A released\n"); }
};

void g()
{
    throw "failure in g";
}

void f()
{
    A a;
    g();
    printf("not reached\n");
}

int main()
{
    try {
        f();
    }
    catch (const char *msg) {
        printf("caught: %s\n", msg);
    }
    return 0;
}
A acquired
A released
caught: failure in g

So an owning object replaces the catch-all handler of the previous section:

class IntBuffer {
    int *data;
public:
    IntBuffer(int n) { data = new int[n]; }
    ~IntBuffer() { delete [] data; }
    int *Get() { return data; }
private:
    IntBuffer(const IntBuffer &);
    void operator=(const IntBuffer &);
};

void work(int *data);

void process(int n)
{
    IntBuffer buf(n);
    work(buf.Get());        // if work throws, ~IntBuffer still runs
}
Detailed notes - 10.5.7: Automatic cleanup

1

stack unwinding destroys fully constructed automatic objects it leaves

  • their destructors release the resources they own
  • removes many manual catch-cleanup-rethrow blocks

2

if f has a local A and calls g, a throw from g can unwind f

  • A's destructor runs during that unwinding
  • the same cleanup occurs on an ordinary return
  • cleanup is tied to object lifetime, not to a particular return statement
Tests & experiments (2 files) - 10.5.7: Automatic cleanup
Section test07 (10-05)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
autoclean.cppC++ / 39 lines
#include <stdio.h>

class A {
    int *buf;
    A(const A &);               /* no copies */
    void operator=(const A &);
public:
    A() : buf(new int[100]) { printf("  A: buffer allocated\n"); }
    ~A() { delete[] buf; printf("  ~A: buffer freed\n"); }
};

void g(bool fail)
{
    printf("  g: working\n");
    if (fail)
        throw "g failed";
}

void f(bool fail)
{
    A a;
    printf("  f: before g\n");
    g(fail);
    printf("  f: after g\n");
}

int main()
{
    printf("g returns normally:\n");
    f(false);
    printf("g throws:\n");
    try {
        f(true);
    }
    catch (const char *s) {
        printf("  main: caught \"%s\"\n", s);
    }
    return 0;
}

10.5.8 Exception type matching

Exception matching is more restricted than ordinary argument conversion: an int handler does not accept every numeric type. References, permitted qualification changes, and suitable class inheritance provide specific matching relationships.

Handlers match types without numeric conversions:

#include <stdio.h>

void test(int kind)
{
    try {
        if (kind == 0)
            throw 'x';          // char
        if (kind == 1)
            throw 42L;          // long
        throw 7;                // int
    }
    catch (int n) {
        printf("int %d\n", n);
    }
    catch (...) {
        printf("not an int\n");
    }
}

int main()
{
    test(0);
    test(1);
    test(2);
    return 0;
}
not an int
not an int
int 7

Adding const is allowed, so catch (const char *) accepts a thrown char *:

char buf[] = "message";
try {
    throw buf;              // char*
}
catch (const char *s) {     // matches
    printf("%s\n", s);
}
Detailed notes - 10.5.8: Exception type matching

1

handler matching does not perform arbitrary numeric conversions

  • catch(int) does not catch char or long exceptions

2

an exception object can be caught by reference

  • catch(A &ref) refers to the thrown A object
  • adding permitted const qualification is possible
  • catch(const char*) can accept char*, not the reverse
  • class inheritance provides another important matching relationship
Tests & experiments (2 files) - 10.5.8: Exception type matching
Section test08 (10-05)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
types.cppC++ / 73 lines
#include <stdio.h>

struct A {
    int code;
    A(int c) : code(c) {}
};

void to_reference()
{
    try {
        throw A(42);
    }
    catch (A &ref) {
        printf("A      caught as A&:           code %d\n", ref.code);
    }
}

void to_const_reference()
{
    try {
        throw A(43);
    }
    catch (const A &ref) {
        printf("A      caught as const A&:     code %d\n", ref.code);
    }
}

void pointer_to_const()
{
    char text[] = "from an array";
    try {
        throw text;                     /* type char* */
    }
    catch (const char *s) {
        printf("char*  caught as const char*: %s\n", s);
    }
}

void literal()
{
    try {
        throw "a literal";              /* type const char* */
    }
    catch (char *s) {                   /* skipped: const can't be dropped */
        printf("literal caught as char*: %s\n", s);
    }
    catch (const char *s) {
        printf("literal caught as const char*: %s\n", s);
    }
}

void integers()
{
    try {
        throw 'x';                      /* type char */
    }
    catch (int n) {                     /* skipped: no char -> int */
        printf("char   caught as int: %d\n", n);
    }
    catch (char c) {
        printf("char   caught as char:         %c\n", c);
    }
}

int main()
{
    to_reference();
    to_const_reference();
    pointer_to_const();
    literal();
    integers();
    return 0;
}

10.6 Inheritance and polymorphism

Inheritance relates specialized types to a common interface, extending methods and hidden state with substitutable behavior. Runtime virtual dispatch selects an implementation from the actual object rather than ordinary overload resolution alone.

Detailed notes - 10.6: Inheritance and polymorphism

1

methods and hidden state alone do not exhaust the book's view of OOP

  • the author calls that restricted approach object-based programming

2

inheritance adds related types and substitutable interfaces

  • the following runtime polymorphism differs from earlier overloading

10.6.1 Hierarchical domains

Domain hierarchies organize shared properties and specialized operations, such as road users, vehicles, and freight vehicles. Inheritance defines these relationships in the language, avoiding fragile attempts to align unrelated C structure layouts manually.

class RoadUser {            // every road user has a position and speed
protected:
    double x, y, speed;
};

class Pedestrian : public RoadUser {
};

class Vehicle : public RoadUser {
protected:
    double fuel;
public:
    void Refuel(double amount) { fuel += amount; }
};

class Truck : public Vehicle {
    double load;
public:
    void Load(double amount) { load += amount; }
    void Unload() { load = 0; }
};
Detailed notes - 10.6.1: Hierarchical domains

1

domain entities often fall into successively narrower categories

  • road users include pedestrians and vehicles
  • vehicles can have more specialized subcategories

2

properties of a category apply to its subcategories

  • all road users have relevant position and motion information
  • a particular vehicle model may have fuel and refuelling operations
  • freight vehicles additionally have load/unload operations

choose categories and assumptions that actually fit the modeled domain

3

related structures need both shared and specialized fields and operations

  • hand-matching initial fields in C leads to fragile pointer conversions
  • inheritance supplies a language-defined relationship instead

4

first examine inherited data, then add inherited methods and behavior

Tests & experiments (2 files) - 10.6.1: Hierarchical domains
Section test01 (10-06)In catalog
MakefileMake / 9 lines
CFLAGS   = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.c *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
student.cC / 70 lines
#include <stdio.h>
#include <string.h>

enum kind { k_person, k_student };

struct person {
    enum kind kind;                     /* what the object really is */
    char name[64];
    char sex;
    int year_of_birth;
};

struct student {
    struct person base;                 /* the same first fields */
    int code;
    int year;
    float average;
};

void init_person(struct person *p, enum kind kind, const char *name,
                 char sex, int year_of_birth)
{
    p->kind = kind;
    strcpy(p->name, name);
    p->sex = sex;
    p->year_of_birth = year_of_birth;
}

void print_person(const struct person *p)
{
    printf("%s (%c), born %d\n", p->name, p->sex, p->year_of_birth);
}

void print_student(const struct student *s)
{
    print_person(&s->base);
    printf("    code %d, year %d, average %.2f\n",
           s->code, s->year, s->average);
}

void print_any(const struct person *p)
{
    if (p->kind == k_student)
        print_student((const struct student *)p);       /* cast down */
    else
        print_person(p);
}

int main(void)
{
    struct person p1;
    struct student s1;
    struct person *all[2];
    int i;

    init_person(&p1, k_person, "Ivan Petrov", 'm', 1975);
    init_person(&s1.base, k_student, "John Doe", 'm', 1989);
    s1.code = 51311;
    s1.year = 2;
    s1.average = 4.75;

    all[0] = &p1;
    all[1] = (struct person *)&s1;                      /* cast up */
    for (i = 0; i < 2; i++)
        print_any(all[i]);
#ifdef BUG
    print_student((const struct student *)&p1);         /* not a student */
#endif
    return 0;
}

10.6.2 Inherited structures and pointer polymorphism

A derived object includes a base subobject and can be accessed through a suitable base pointer or reference. The reverse conversion is not automatic because a general person, for example, need not be a student.

struct person {
    char name[64];
    char sex;
    int year_of_birth;
};

struct student : person {   // for a struct, public inheritance is the default
    int code;
    int year;
    float average;
};

void print_person(const person &p)
{
    printf("%s, born %d\n", p.name, p.year_of_birth);
}
student s;
strcpy(s.name, "Anna");
s.year_of_birth = 2004;
print_person(s);            // student& converts to person&
person *pp = &s;            // and student* to person*
person p;
student *ps = &p;           // error: a person need not be a student
Detailed notes - 10.6.2: Inherited structures and pointer polymorphism

1

inheritance specializes a more general concept

2

student derives from person

  • person supplies name, sex and year_of_birth in this example
  • student adds subject code, study year and average mark
  • the derived object contains its base subobject plus added state

person: base/parent; student: derived/child

3

a student can be accessed through its person part

  • student* converts to a suitable accessible unambiguous person*
  • corresponding reference conversion also works
  • a function accepting person& can therefore receive a student

the reverse is not automatic: an arbitrary person need not be a student

  • the language handles any required pointer adjustment
  • do not generalize the diagram into a universal zero-offset layout rule

4

the author calls this pointer or reference polymorphism

  • one operation can accept several related concrete types
  • other sources use narrower definitions of the word polymorphism
A pointer or reference can preserve access to the complete object; a base value cannot contain it.
Copying into a base value discards the derived part. Open full size - Editable SVG
Tests & experiments (2 files) - 10.6.2: Inherited structures and pointer polymorphism
Section test02 (10-06)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
student.cppC++ / 39 lines
#include <stdio.h>
#include <string.h>

struct person {
    char name[64];
    char sex; // 'm' or 'f'
    int year_of_birth;
};

struct student : person {
    int code;
    int year; // study year
    float average;
};

void print_person(const person &p)
{
    printf("%s, %d, %d\n", p.name, p.sex, p.year_of_birth);
}

int main()
{
    student s1;

    strcpy(s1.name, "John Doe");
    s1.sex = 'm';
    s1.year_of_birth = 1989;
    s1.code = 51311;
    s1.year = 2;
    s1.average = 4.75;

    person *p;
    p = &s1;
    person &ref1 = s1;

    print_person(s1);

    return 0;
}

10.6.3 Methods and access in inheritance

Public inheritance exposes a base interface, while private inheritance treats it as implementation detail. Derived code does not gain access to base-private members, and protected members become a contract that subclasses may depend on.

class A {
    int secret;             // A's own methods only
protected:
    int shared;             // also for derived classes
public:
    int Get() const { return shared; }
};

class B : public A {        // B is an A, for everyone
public:
    void Set(int x) { shared = x; }
};

class C : private A {       // C uses A only in its implementation
public:
    int Value() const { return Get(); }
};
class D : public A {
    int Peek() const { return secret; }   // error: private in A
};
B b;
b.shared = 1;               // error: protected
C c;
A *pa = &c;                 // error: A is a private base of C
Detailed notes - 10.6.3: Methods and access in inheritance

1

inheritance works with both class and struct declarations

  • either can derive from the other
  • class here also means the OOP concept, independent of that keyword

2

public inheritance exposes the base interface as part of the derived type

private inheritance makes that relationship an implementation detail

  • class B : public A and class C : private A express the distinction
  • access and implicit base conversions depend on that choice

3

default inheritance: public for struct, private for class

  • the book normally writes public explicitly for derived classes

4

a derived class does not automatically gain the base's private access

  • private base details remain the base implementation's responsibility

5

protected members form an interface for derived classes

  • accessible in the class, permitted derived contexts and friends
  • unavailable to arbitrary clients

6

protected is a published contract for subclasses

  • unknown future subclasses may depend on it
  • document it and change it as carefully as a public interface
  • private implementation has a more limited, identifiable set of users

7

inherited ordinary methods retain their base implementation

  • a truck can reuse its vehicle's refuelling operation
  • that operation need not know the truck's extra state

8

the inherited method receives a base view of this

  • conversion from the derived object supplies the appropriate base part

9

public derivation means the specialized object accepts its base's messages

  • clients can use the shared interface without knowing the subtype

10

two compatible views:

  • design: the derived object is a specialized base object
  • implementation: it contains a base-class subobject
Tests & experiments (2 files) - 10.6.3: Methods and access in inheritance
Section test03 (10-06)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic -DERRORS

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
chain.cppC++ / 56 lines
#include <stdio.h>

class A {
protected:
    int prot;
public:
    int pub;
    A() : prot(0), pub(0) {}
    void Print() const { printf("  prot = %d, pub = %d\n", prot, pub); }
};

/* public all the way: A <- B1 <- C1 */
class B1 : public A {
public:
    void f() { prot = 1; pub = 1; }     /* direct descendant: fine */
};

class C1 : public B1 {
public:
    void g() { prot = 2; pub = 2; }     /* far descendant: fine too */
};

/* private in the middle: A <- B2 <- C2 */
class B2 : private A {
public:
    void f() { prot = 1; pub = 1; }     /* direct descendant: fine */
    void Show() const { Print(); }      /* B2 decides what to expose */
};

class C2 : public B2 {
public:
#ifdef ERRORS
    void g() { prot = 2; pub = 2; }     /* line 33 */
    void h() { ::A *p = this; (void)p; }        /* line 34 */
#endif
};

int main()
{
    C1 c1;
    C2 c2;

    printf("C1 (public chain):\n");
    c1.f();
    c1.g();
    c1.Print();                         /* A's method, from outside */

    printf("C2 (private in the middle):\n");
    c2.f();                             /* B2's own public method */
    c2.Show();
#ifdef ERRORS
    c2.g();
    c2.Print();                         /* line 53 */
#endif
    return 0;
}

10.6.4 Constructing and destroying derived objects

Base construction precedes the derived constructor body, and destruction proceeds in the reverse direction. The derived initializer list supplies base constructor arguments before member initialization and ordinary body statements run.

#include <stdio.h>

class A {
public:
    A(int x, int y) { printf("A(%d, %d)\n", x, y); }
    ~A() { printf("~A\n"); }
};

class Member {
public:
    Member(int v) { printf("Member(%d)\n", v); }
    ~Member() { printf("~Member\n"); }
};

class B : public A {
    Member i;
public:
    B() : A(2, 3), i(4) { printf("B body\n"); }
    ~B() { printf("~B body\n"); }
};

int main()
{
    B b;
    return 0;
}
A(2, 3)
Member(4)
B body
~B body
~Member
~A
Detailed notes - 10.6.4: Constructing and destroying derived objects

1

base construction precedes use by the derived constructor body

  • the derived body needs its base part to exist

destruction reverses the order

  • the derived destructor body runs while the base still exists

2

the compiler arranges the base destructor after derived cleanup constructor arguments for the base go in the initializer list

  • B::B() : A(2, 3), i(4) initializes base A, then member i
  • the body executes after that initialization
Tests & experiments (2 files) - 10.6.4: Constructing and destroying derived objects
Section test04 (10-06)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic -DERRORS

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
child.cppC++ / 16 lines
class A {
public:
    A(int p, int q) {}
};

class B : public A {
    int i;
public:
    B() : A(2, 3), i(4) {};
};

int main()
{
    B b;
    return 0;
}

10.6.5 Virtual functions

Virtual methods let a common algorithm invoke behavior belonging to the actual object's type. A shared Move operation can hide and redraw different graphical shapes through their overrides, typically using virtual-function tables.

Move is written once, in Pixel. Because Show and Hide are virtual, it calls Circle's versions for a circle:

#include <stdio.h>

class Pixel {
protected:
    double x, y;
    int color;
public:
    Pixel(double a_x, double a_y, int a_color)
        : x(a_x), y(a_y), color(a_color) {}
    virtual ~Pixel() {}
    virtual void Show() { printf("pixel at (%g, %g)\n", x, y); }
    virtual void Hide() { printf("hide pixel at (%g, %g)\n", x, y); }
    void Move(double nx, double ny) {
        Hide();
        x = nx;
        y = ny;
        Show();
    }
};

class Circle : public Pixel {
    double radius;
public:
    Circle(double x, double y, double rad, int color)
        : Pixel(x, y, color), radius(rad) {}
    virtual void Show() { printf("circle r=%g at (%g, %g)\n", radius, x, y); }
    virtual void Hide() { printf("hide circle r=%g at (%g, %g)\n", radius, x, y); }
};

int main()
{
    Circle c(1, 2, 5, 0);
    Pixel *p = &c;

    c.Move(3, 4);           // Pixel::Move calls Circle::Hide and Circle::Show
    p->Show();              // dispatch through a base pointer
    return 0;
}
hide circle r=5 at (1, 2)
circle r=5 at (3, 4)
circle r=5 at (3, 4)

Without virtual, Move would call Pixel::Hide and Pixel::Show even for the circle.

Detailed notes - 10.6.5: Virtual functions

1

a derived object may need a different reaction to a shared message

  • virtual functions let the base interface allow that variation

2

graphics example: Pixel has coordinates, color, Show, Hide and Move

Move algorithm:

  • Hide at the old position
  • change x and y
  • Show at the new position

Circle initially derives from Pixel and adds radius

  • supplies circle-specific Show and Hide
  • constructor initializes inherited coordinates/color and its radius
  • protected fields make these values available to its drawing methods
  • the text later repairs the conceptual error of treating a circle as a specialized pixel

3

inherited Move would be ideal because its algorithm does not change

  • ordinary non-virtual calls inside Pixel::Move bind to Pixel's methods
  • merely adding Circle methods does not change those calls

4

that ordinary binding would erase and draw a point for a circle

  • the reused algorithm would perform the wrong concrete operations

5

declare Show and Hide virtual in the base

  • calls can select the override for the actual receiving object
  • descendants share the message but may change its implementation
  • constructors and static member functions cannot be virtual

6

common implementation: a virtual-function table

  • object contains hidden information identifying its class's table
  • a virtual call obtains the chosen function address through that table
  • this is an implementation model, not a prescribed memory layout

7

derived classes have corresponding tables with appropriate overrides

  • object construction establishes the appropriate dispatch information

8

Move now works through the shared algorithm

  • its virtual calls reach Circle's Hide and Show for a Circle

9

provide a virtual destructor for this polymorphic owning interface

  • derived destruction then works through a base pointer
  • overriding methods remain virtual even without repeating the keyword

10

virtual dispatch also works for calls outside the class

  • references and pointers may designate different derived types
  • when the actual type is known, the compiler may resolve directly without a table lookup while preserving behavior

11

p->Show() through Pixel* or Circle* selects the appropriate final override

  • caller need not list all concrete classes that might appear later
Shape* describes the interface; the referenced object chooses the final override.
A virtual call follows the actual object type. Open full size - Editable SVG
Tests & experiments (2 files) - 10.6.5: Virtual functions
Section test05 (10-06)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic -DERRORS

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
graphics.cppC++ / 42 lines
#include <stdio.h>

class Pixel {
protected:
    double x, y;
    int color;
public:
    Pixel(double ax, double ay, int acolor)
        : x(ax), y(ay), color(acolor) {}
    virtual ~Pixel() {}
    virtual void Show() { printf("hide pixel\n"); }
    virtual void Hide() { printf("show pixel\n"); }
    void Move(double nx, double ny);
};

void Pixel::Move(double nx, double ny)
{
    Hide();
    printf("generic move\n");
    x = nx;
    y = ny;
    Show();
}

class Circle : public Pixel {
    double radius;
public:
    Circle(double x, double y, double rad, int color)
        : Pixel(x, y, color), radius(rad) {}
    virtual ~Circle() {}
    virtual void Show() { printf("hide circle\n"); }
    virtual void Hide() { printf("show circle\n"); }
};

int main()
{
    Pixel *p = new Circle(1, 2, 3, 4);
    Pixel *q = new Pixel(5, 6, 7);
    p->Move(1, 2);
    q->Move(3, 4);
    return 0;
}

10.6.6 Pure virtual methods and abstract classes

An abstract base defines a shared interface without requiring a meaningless generic implementation. Making drawing operations pure virtual lets Pixel and Circle share movement behavior as separate kinds of graphical object.

A circle is not a kind of pixel; both are kinds of graphical object, which cannot draw itself:

class GraphObject {
protected:
    double x, y;
    int color;
public:
    GraphObject(double a_x, double a_y, int a_color)
        : x(a_x), y(a_y), color(a_color) {}
    virtual ~GraphObject() {}
    virtual void Show() = 0;
    virtual void Hide() = 0;
    void Move(double nx, double ny) {
        Hide();
        x = nx;
        y = ny;
        Show();
    }
};

class Pixel : public GraphObject {
public:
    Pixel(double x, double y, int color) : GraphObject(x, y, color) {}
    virtual void Show();
    virtual void Hide();
};

class Circle : public GraphObject {
    double radius;
public:
    Circle(double x, double y, double rad, int color)
        : GraphObject(x, y, color), radius(rad) {}
    virtual void Show();
    virtual void Hide();
};
GraphObject g(0, 0, 1);     // error: GraphObject is abstract
Detailed notes - 10.6.6: Pure virtual methods and abstract classes

1

a circle is not a kind of pixel

  • both can instead be kinds of graphical figure
  • each has color and an anchor position

2

the shared Move algorithm uses the anchor independently of shape

3

introduce a general figure base and derive both Pixel and Circle from it

  • this follows the domain relationship instead of borrowing an unrelated concrete class only for its fields

4

a shape without a particular form has no useful generic drawing body

5

the base can still implement Move using a required Show/Hide interface

  • concrete descendants must provide the missing behavior

6

virtual void f() = 0 declares a pure virtual member

  • marks an interface obligation for concrete descendants
  • it does not prescribe a literal zero table entry
  • pure virtual functions can have separate definitions in C++

7

= 0 is the fixed declaration syntax

  • the author's dissatisfaction with it is a syntax preference

8

a class with an unimplemented pure virtual obligation is abstract

  • cannot create an object whose most-derived type is that class
  • a subclass remains abstract until it supplies the required overrides
  • abstract base subobjects can exist inside concrete derived objects

9

GraphObject stores anchor/color and declares pure virtual Show and Hide

  • supplies constructor, virtual destructor and the common Move
  • Move's virtual calls dispatch to concrete implementations

10

Pixel and Circle derive independently from GraphObject

  • both define Show and Hide
  • Circle additionally stores radius
  • declaring those non-pure methods without required definitions causes missing-definition problems at link time
Tests & experiments (3 files) - 10.6.6: Pure virtual methods and abstract classes
Section test06 (10-06)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic -DERRORS

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
graphics.cppC++ / 52 lines
#include <stdio.h>

class GraphObject {
protected:
    double x, y;
    int color;
public:
    GraphObject(double ax, double ay, int acolor)
        : x(ax), y(ay), color(acolor) {}
    virtual ~GraphObject() {}
    virtual void Show() = 0;
    virtual void Hide() = 0;
    void Move(double nx, double ny);
};

void GraphObject::Move(double nx, double ny)
{
    Hide();
    printf("move graph object\n");
    x = nx;
    y = ny;
    Show();
}


class Pixel : public GraphObject {
public:
    Pixel(double x, double y, int color)
        : GraphObject(x, y, color) {}
    virtual ~Pixel() {}
    virtual void Show() { printf("hide pixel\n"); }
    virtual void Hide() { printf("show pixel\n"); }
};

class Circle : public GraphObject {
    double radius;
public:
    Circle(double x, double y, double rad, int color)
        : GraphObject(x, y, color), radius(rad) {}
    virtual ~Circle() {}
    virtual void Show() { printf("hide circle\n"); }
    virtual void Hide() { printf("show circle\n"); }
};

int main()
{
    GraphObject *p = new Circle(1, 2, 3, 4);
    GraphObject *q = new Pixel(5, 6, 7);
    p->Move(1, 2);
    q->Move(3, 4);
    return 0;
}
pure_virtual.cppC++ / 13 lines
class A {
    virtual void f() = 0;
};

class B : public A {
    virtual void f() {}
};

int main()
{
    B b;
    return 0;
}

10.6.7 Virtual calls during construction and destruction

Virtual calls during construction and destruction use the current lifetime stage, not a later or already-destroyed derived part. Base constructors therefore cannot rely on descendant overrides to complete their work.

During construction and destruction, virtual calls use the current stage:

#include <stdio.h>

class Base {
public:
    Base() { Hello(); }
    virtual ~Base() { Hello(); }
    virtual void Hello() { printf("Base::Hello\n"); }
};

class Derived : public Base {
public:
    Derived() { Hello(); }
    ~Derived() { Hello(); }
    virtual void Hello() { printf("Derived::Hello\n"); }
};

int main()
{
    Derived d;
    return 0;
}
Base::Hello
Derived::Hello
Derived::Hello
Base::Hello
Detailed notes - 10.6.7: Virtual calls during construction and destruction

1

construction proceeds through base and derived stages

  • the object cannot yet behave as a fully constructed later descendant

2

virtual calls on the object under construction/destruction use the current

class's stage, not a more-derived override

  • base construction invokes base-stage behavior
  • base destruction occurs after derived-stage cleanup

3

do not rely on a descendant to finish work called virtually by a base constructor or destructor

  • virtual calls reaching a pure virtual function are invalid
  • avoid such calls when their lifetime behavior is unclear
Tests & experiments (2 files) - 10.6.7: Virtual calls during construction and destruction
Section test07 (10-06)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
virtual.cppC++ / 33 lines
#include <stdio.h>

class Base {
public:
    Base();
    virtual ~Base();
    virtual void Name() { printf("I am Base\n"); }
    void Ask(const char *where);        /* not virtual; calls Name() */
};

class Derived : public Base {
public:
    Derived() { Ask("Derived::Derived"); }
    virtual ~Derived() { Ask("Derived::~Derived"); }
    virtual void Name() { printf("I am Derived\n"); }
};

void Base::Ask(const char *where)
{
    void *vmtp = *(void **)this;        /* the hidden field */
    printf("%-18s vmtp = %p  ", where, vmtp);
    Name();                             /* a virtual call */
}

Base::Base() { Ask("Base::Base"); }
Base::~Base() { Ask("Base::~Base"); }

int main()
{
    Derived d;
    d.Ask("main");
    return 0;
}

10.6.8 Deriving a class for its constructor

A derived constructor can package a useful setup sequence while inheriting ordinary behavior, as a square initializes a polygonal chain. The inherited mutation interface still matters: adding arbitrary vertices would break a permanent square invariant.

class PolygonalChain : public GraphObject {
    struct Vertex {
        double dx, dy;
        Vertex *next;
    };
    Vertex *first;
public:
    PolygonalChain(double x, double y, int color)
        : GraphObject(x, y, color), first(0) {}
    virtual ~PolygonalChain();
    void AddVertex(double dx, double dy);
    virtual void Show();
    virtual void Hide();
private:
    PolygonalChain(const PolygonalChain &);     // an owner: no copying
    void operator=(const PolygonalChain &);
};

void PolygonalChain::AddVertex(double dx, double dy)
{
    Vertex *v = new Vertex;
    v->dx = dx;
    v->dy = dy;
    v->next = first;
    first = v;
}

PolygonalChain::~PolygonalChain()
{
    while (first) {
        Vertex *v = first;
        first = first->next;
        delete v;
    }
}

Square adds nothing but a constructor:

class Square : public PolygonalChain {
public:
    Square(double x, double y, double a, int color)
        : PolygonalChain(x, y, color)
    {
        AddVertex(0, 0);
        AddVertex(0, a);
        AddVertex(a, a);
        AddVertex(a, 0);
        AddVertex(0, 0);
    }
};
Detailed notes - 10.6.8: Deriving a class for its constructor

1

a derived class can add only a convenient construction procedure

  • reuse the base's state and ordinary operations
  • example: construct a square using a polygonal chain

2

PolygonalChain stores relative vertex offsets in a private linked list

  • starts with no vertices
  • AddVertex prepends one vertex
  • reverse traversal still draws the same unoriented chain
  • Show and Hide interpret offsets relative to the inherited anchor
  • destructor walks the list and deletes every node

as an owning class, copying needs either a real deep copy or prohibition

3

axis-aligned square of side a is a closed five-vertex chain

  • include the first corner again at the end
  • offsets describe the four corners around the chosen anchor

4

Square's constructor initializes PolygonalChain, then adds those vertices

  • drawing, hiding, movement and cleanup are inherited
  • this saves repeating the construction sequence at each use
  • inherited AddVertex can still alter the shape, so the example alone does not enforce a permanent square invariant
Tests & experiments (2 files) - 10.6.8: Deriving a class for its constructor
Section test08 (10-06)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
graphics.cppC++ / 101 lines
#include <stdio.h>

class GraphObject {
protected:
    double x, y;
    int color;
public:
    GraphObject(double ax, double ay, int acolor)
        : x(ax), y(ay), color(acolor) {}
    virtual ~GraphObject() {}
    virtual void Show() = 0;
    virtual void Hide() = 0;
    void Move(double nx, double ny);
};

void GraphObject::Move(double nx, double ny)
{
    Hide();
    printf("move graph object\n");
    x = nx;
    y = ny;
    Show();
}

class Pixel : public GraphObject {
public:
    Pixel(double x, double y, int color)
        : GraphObject(x, y, color) {}
    virtual ~Pixel() {}
    virtual void Show() { printf("hide pixel\n"); }
    virtual void Hide() { printf("show pixel\n"); }
};

class Circle : public GraphObject {
    double radius;
public:
    Circle(double x, double y, double rad, int color)
        : GraphObject(x, y, color), radius(rad) {}
    virtual ~Circle() {}
    virtual void Show() { printf("hide circle\n"); }
    virtual void Hide() { printf("show circle\n"); }
};


class PolygonalChain : public GraphObject {
    struct Vertex {
        double dx, dy;
        Vertex *next;
    };
    Vertex *first;
public:
    PolygonalChain(double x, double y, int color)
        : GraphObject(x, y, color), first(0) {}
    virtual ~PolygonalChain();
    void AddVertex(double adx, double ady);
    virtual void Show() { printf("hide polygonal chain\n"); }
    virtual void Hide() { printf("show polygonal chain\n"); }
};

void PolygonalChain::AddVertex(double adx, double ady)
{
    Vertex *tmp = new Vertex;
    tmp->dx = adx;
    tmp->dy = ady;
    tmp->next = first;
    first = tmp;
}

PolygonalChain::~PolygonalChain()
{
    while (first) {
        Vertex *tmp = first;
        first = first->next;
        delete tmp;
    }

}

class Square : public PolygonalChain {
public:
    Square(double x, double y, int color, double a)
        : PolygonalChain(x, y, color)
    {
        AddVertex(0, 0);
        AddVertex(0, a);
        AddVertex(a, a);
        AddVertex(a, 0);
        AddVertex(0, 0);
    }
};

int main()
{
    GraphObject *p = new Circle(1, 2, 3, 4);
    GraphObject *q = new Pixel(5, 6, 7);
    GraphObject *s = new Square(5, 6, 7, 8);
    p->Move(1, 2);
    q->Move(3, 4);
    s->Move(3, 4);
    return 0;
}

10.6.9 Virtual destructors

Deleting a derived object through a base pointer requires a suitable virtual base destructor. This invokes complete derived cleanup; without it, the example's polymorphic deletion has undefined behavior rather than merely incomplete cleanup.

GraphObject *p = new Square(10, 10, 5, 1);
p->Move(20, 20);
delete p;       // ~Square, then ~PolygonalChain frees the vertices, then
                // ~GraphObject; without a virtual destructor: undefined
#include <stdio.h>

class Base {
public:
    virtual ~Base() { printf("~Base\n"); }
};

class Derived : public Base {
    char *buf;
public:
    Derived() { buf = new char[100]; }
    ~Derived() { delete [] buf; printf("~Derived\n"); }
};

int main()
{
    Base *p = new Derived;
    delete p;
    return 0;
}
~Derived
~Base
Detailed notes - 10.6.9: Virtual destructors

1

polymorphic deletion needs the destruction behavior of the actual object

2

GraphObject* can hold the result of new Square(...)

  • delete through that pointer must destroy the whole Square
  • virtual base destructor leads through Square, PolygonalChain and base
  • PolygonalChain then releases its allocated vertices

without a virtual base destructor, this base-pointer deletion has undefined

behavior; it is not merely a guaranteed call to the wrong destructor

3

the author recommends virtual destructors on polymorphic base classes

  • keeps future deletion through that interface correct
  • runtime representation costs depend on the implementation
Tests & experiments (2 files) - 10.6.9: Virtual destructors
Section test09 (10-06)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
graphics.cppC++ / 106 lines
#include <stdio.h>

class GraphObject {
protected:
    double x, y;
    int color;
public:
    GraphObject(double ax, double ay, int acolor)
        : x(ax), y(ay), color(acolor) {}
    virtual ~GraphObject() {}
    virtual void Show() = 0;
    virtual void Hide() = 0;
    void Move(double nx, double ny);
};

void GraphObject::Move(double nx, double ny)
{
    Hide();
    printf("move graph object\n");
    x = nx;
    y = ny;
    Show();
}

class Pixel : public GraphObject {
public:
    Pixel(double x, double y, int color)
        : GraphObject(x, y, color) {}
    virtual ~Pixel() {}
    virtual void Show() { printf("hide pixel\n"); }
    virtual void Hide() { printf("show pixel\n"); }
};

class Circle : public GraphObject {
    double radius;
public:
    Circle(double x, double y, double rad, int color)
        : GraphObject(x, y, color), radius(rad) {}
    virtual ~Circle() {}
    virtual void Show() { printf("hide circle\n"); }
    virtual void Hide() { printf("show circle\n"); }
};


class PolygonalChain : public GraphObject {
    struct Vertex {
        double dx, dy;
        Vertex *next;
    };
    Vertex *first;
public:
    PolygonalChain(double x, double y, int color)
        : GraphObject(x, y, color), first(0) {}
    virtual ~PolygonalChain();
    void AddVertex(double adx, double ady);
    virtual void Show() { printf("hide polygonal chain\n"); }
    virtual void Hide() { printf("show polygonal chain\n"); }
};

void PolygonalChain::AddVertex(double adx, double ady)
{
    Vertex *tmp = new Vertex;
    tmp->dx = adx;
    tmp->dy = ady;
    tmp->next = first;
    first = tmp;
}

PolygonalChain::~PolygonalChain()
{
    while (first) {
        Vertex *tmp = first;
        first = first->next;
        delete tmp;
    }

}

class Square : public PolygonalChain {
public:
    Square(double x, double y, int color, double a)
        : PolygonalChain(x, y, color)
    {
        AddVertex(0, 0);
        AddVertex(0, a);
        AddVertex(a, a);
        AddVertex(a, 0);
        AddVertex(0, 0);
    }
};

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

    p = new Square(27.3, 37.7, 0xff0000, 10.0);
    q = new Pixel(1, 2, 0x00ff00);

    p->Move(1, 2);
    q->Move(3, 4);

    delete p;
    delete q;

    return 0;
}

10.6.10 More polymorphism

A collection of base pointers can hold different graphical shapes and invoke their runtime-selected behavior through one interface. Cleanup must delete each object correctly and then release the pointer array, including partial-construction failure paths.

int scene_length = 3;
GraphObject **scene = new GraphObject*[scene_length];
scene[0] = new Pixel(1, 1, 2);
scene[1] = new Circle(5, 5, 3, 4);
scene[2] = new Square(0, 0, 10, 1);

for (int i = 0; i < scene_length; i++)
    scene[i]->Show();           // each object's own Show
for (int i = 0; i < scene_length; i++)
    scene[i]->Move(i, i);

for (int i = 0; i < scene_length; i++)
    delete scene[i];            // virtual destructors
delete [] scene;
Show the complete program
#include <stdio.h>

class GraphObject {
protected:
    double x, y;
    int color;
public:
    GraphObject(double a_x, double a_y, int a_color)
        : x(a_x), y(a_y), color(a_color) {}
    virtual ~GraphObject() {}
    virtual void Show() = 0;
    virtual void Hide() = 0;
    void Move(double nx, double ny) {
        Hide();
        x = nx;
        y = ny;
        Show();
    }
};

class Pixel : public GraphObject {
public:
    Pixel(double x, double y, int color) : GraphObject(x, y, color) {}
    virtual void Show() { printf("pixel (%g, %g)\n", x, y); }
    virtual void Hide() { printf("hide pixel\n"); }
};

class Circle : public GraphObject {
    double radius;
public:
    Circle(double x, double y, double rad, int color)
        : GraphObject(x, y, color), radius(rad) {}
    virtual void Show() { printf("circle (%g, %g) r=%g\n", x, y, radius); }
    virtual void Hide() { printf("hide circle\n"); }
};

class PolygonalChain : public GraphObject {
    struct Vertex {
        double dx, dy;
        Vertex *next;
    };
    Vertex *first;
public:
    PolygonalChain(double x, double y, int color)
        : GraphObject(x, y, color), first(0) {}
    virtual ~PolygonalChain();
    void AddVertex(double dx, double dy);
    virtual void Show();
    virtual void Hide() { printf("hide chain\n"); }
private:
    PolygonalChain(const PolygonalChain &);
    void operator=(const PolygonalChain &);
};

void PolygonalChain::AddVertex(double dx, double dy)
{
    Vertex *v = new Vertex;
    v->dx = dx;
    v->dy = dy;
    v->next = first;
    first = v;
}

void PolygonalChain::Show()
{
    printf("chain");
    for (Vertex *v = first; v; v = v->next)
        printf(" (%g, %g)", x + v->dx, y + v->dy);
    printf("\n");
}

PolygonalChain::~PolygonalChain()
{
    while (first) {
        Vertex *v = first;
        first = first->next;
        delete v;
    }
}

class Square : public PolygonalChain {
public:
    Square(double x, double y, double a, int color)
        : PolygonalChain(x, y, color)
    {
        AddVertex(0, 0);
        AddVertex(0, a);
        AddVertex(a, a);
        AddVertex(a, 0);
        AddVertex(0, 0);
    }
};

int main()
{
    int scene_length = 3;
    GraphObject **scene = new GraphObject*[scene_length];
    scene[0] = new Pixel(1, 1, 2);
    scene[1] = new Circle(5, 5, 3, 4);
    scene[2] = new Square(0, 0, 10, 1);

    for (int i = 0; i < scene_length; i++)
        scene[i]->Show();
    scene[2]->Move(1, 1);

    for (int i = 0; i < scene_length; i++)
        delete scene[i];
    delete [] scene;
    return 0;
}
pixel (1, 1)
circle (5, 5) r=3
chain (0, 0) (10, 0) (10, 10) (0, 10) (0, 0)
hide chain
chain (1, 1) (11, 1) (11, 11) (1, 11) (1, 1)
Detailed notes - 10.6.10: More polymorphism

1

a scene may contain an unknown mixture of concrete graphical objects

  • types and count can come from a file or runtime generation

2

store an array of GraphObject* after determining scene_length

  • each initialized slot owns a Pixel, Circle, Square or other subtype
  • valid index range is 0 <= i < scene_length
  • Show, Hide and Move work through the shared interface

cleanup:

  • delete each stored object through its virtual-destructor base
  • then delete[] the pointer array itself
  • construction-failure paths must also release objects already created

behavior selected from the actual runtime type is dynamic polymorphism

Tests & experiments (2 files) - 10.6.10: More polymorphism
Section test10 (10-06)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
graphics.cppC++ / 122 lines
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

enum { rand_limit = 10 };

class GraphObject {
protected:
    double x, y;
    int color;
public:
    GraphObject(double ax, double ay, int acolor)
        : x(ax), y(ay), color(acolor) {}
    virtual ~GraphObject() {}
    virtual void Show() = 0;
    virtual void Hide() = 0;
    void Move(double nx, double ny);
};

void GraphObject::Move(double nx, double ny)
{
    Hide();
    printf("move graph object\n");
    x = nx;
    y = ny;
    Show();
}

class Pixel : public GraphObject {
public:
    Pixel(double x, double y, int color)
        : GraphObject(x, y, color) {}
    virtual ~Pixel() {}
    virtual void Show() { printf("hide pixel\n"); }
    virtual void Hide() { printf("show pixel\n"); }
};

class Circle : public GraphObject {
    double radius;
public:
    Circle(double x, double y, double rad, int color)
        : GraphObject(x, y, color), radius(rad) {}
    virtual ~Circle() {}
    virtual void Show() { printf("hide circle\n"); }
    virtual void Hide() { printf("show circle\n"); }
};


class PolygonalChain : public GraphObject {
    struct Vertex {
        double dx, dy;
        Vertex *next;
    };
    Vertex *first;
public:
    PolygonalChain(double x, double y, int color)
        : GraphObject(x, y, color), first(0) {}
    virtual ~PolygonalChain();
    void AddVertex(double adx, double ady);
    virtual void Show() { printf("hide polygonal chain\n"); }
    virtual void Hide() { printf("show polygonal chain\n"); }
};

void PolygonalChain::AddVertex(double adx, double ady)
{
    Vertex *tmp = new Vertex;
    tmp->dx = adx;
    tmp->dy = ady;
    tmp->next = first;
    first = tmp;
}

PolygonalChain::~PolygonalChain()
{
    while (first) {
        Vertex *tmp = first;
        first = first->next;
        delete tmp;
    }

}

class Square : public PolygonalChain {
public:
    Square(double x, double y, int color, double a)
        : PolygonalChain(x, y, color)
    {
        AddVertex(0, 0);
        AddVertex(0, a);
        AddVertex(a, a);
        AddVertex(a, 0);
        AddVertex(0, 0);
    }
};

int random_number(int limit)
{
    return 1.0 * limit * rand() / (RAND_MAX + 1.0);
}

int main()
{
    int i;
    srand(time(NULL));

    int scene_length = 3 + random_number(rand_limit);
    GraphObject **scene;

    scene = new GraphObject*[scene_length];

    scene[0] = new Pixel(1.25, 15.75, 0xff0000);
    scene[1] = new Circle(20.9, 7.25, 0x005500, 3.5);
    scene[2] = new Square(55.0, 30.5, 0x008080, 10.0);
    for (i = 3; i < scene_length; i++)
        scene[i] = new Circle(i, i, 0x0000ff, 1);

    for (i = 0; i < scene_length; i++)
        delete scene[i];
    delete[] scene;

    return 0;
}

10.6.11 Private and protected destructors

Private or protected destructors restrict which code may end an object's lifetime. Such designs can control client deletion or support specialized heap-only interfaces, but self-deletion still requires precise ownership and no subsequent access.

A private destructor allows only heap objects that destroy themselves:

class HeapOnly {
    ~HeapOnly() {}
public:
    void Disappear() { delete this; }
};
HeapOnly *h = new HeapOnly;
h->Disappear();             // h must not be used after this
HeapOnly local;             // error: the destructor is private
Detailed notes - 10.6.11: Private and protected destructors

1

private destruction restricts access to members and friends protected destruction also permits the relevant derived-class contexts

2

ordinary outside automatic objects need an accessible destructor

  • making it private prevents that ordinary lifetime arrangement
  • a controlled heap-only interface can expose a Disappear method

delete this requires a compatible dynamic allocation and careful ownership

  • no further object access afterward
  • no later second deletion through another owner

private destruction also prevents ordinary derived

construction/destruction

unless friendship grants the needed access

  • protected destruction can permit derivation while restricting clients

3

applying the access policy throughout a hierarchy can enforce controlled

destruction for ordinary clients

  • privileged members and friends retain their special access

4

this is a specialized lifetime-design tool

  • the author notes its usefulness without developing a full example
Tests & experiments (2 files) - 10.6.11: Private and protected destructors
Section test11 (10-06)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
private_destructor.cppC++ / 12 lines
class A {
    ~A() {}
public:
    void Disappear() { delete this; }
};

int main()
{
    A *p = new A;
    p->Disappear();
    return 0;
}

10.6.12 Overloading and name hiding

A derived declaration can hide all same-named base declarations rather than extend their overload set. Explicit qualification selects a base member, while a using declaration can restore base overloads to ordinary lookup.

class A {
public:
    void f(int a, int b) { printf("A::f(%d, %d)\n", a, b); }
};

class B : public A {
public:
    void f(const char *s) { printf("B::f(%s)\n", s); }
};

B b;
b.f(2, 3);              // error: B::f hides A::f
b.A::f(2, 3);           // explicit qualification still works

A using-declaration brings the base overloads into the derived scope:

class B2 : public A {
public:
    using A::f;
    void f(const char *s) { printf("B2::f(%s)\n", s); }
};

B2 b2;
b2.f(2, 3);             // A::f
b2.f("text");           // B2::f
Detailed notes - 10.6.12: Overloading and name hiding

1

a declaration named f in a derived scope can hide base declarations named f

  • even a data member can hide a base method
  • the inherited member still exists
  • b.A::f(2, 3) explicitly selects the base declaration if accessible

2

a derived f(const char*) also hides a base f(int, int)

  • ordinary lookup does not combine these scopes into an overload set
  • b.f(2, 3) therefore fails in the example
  • explicit qualification works; using A::f can also expose base overloads
Tests & experiments (3 files) - 10.6.12: Overloading and name hiding
Section test12 (10-06)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
overloading.cppC++ / 17 lines
#include <stdio.h>

class A {
public:
    void f(int a, int b) { printf("%d %d\n", a, b); }
};

class B : public A {
    double f;
};

int main()
{
    B b;
    b.A::f(2, 3);
    return 0;
}
overloading01.cppC++ / 19 lines
#include <stdio.h>

class A {
public:
    void f(int a, int b) { printf("%d %d\n", a, b); }
};

class B : public A {
public:
    double f(const char *str) { return 1.0; }
};

int main()
{
    B b;
    double t = b.f("hello there");
    b.A::f(2, 3);
    return 0;
}

10.6.13 Bypassing virtual dispatch

Explicit class qualification selects that class's implementation and suppresses virtual dispatch for the call. An override can use this to perform the base operation before adding specialized behavior.

#include <stdio.h>

class A {
public:
    virtual ~A() {}
    virtual void f() { printf("first\n"); }
    void g() { f(); }
    void h() { A::f(); }
};

class B : public A {
public:
    virtual void f() { printf("second\n"); }
};

int main()
{
    B b;
    A *pa = &b;

    b.g();          // virtual call inside g
    b.f();
    b.h();          // A::f() bypasses dispatch
    b.A::f();
    pa->f();
    pa->A::f();
    return 0;
}
second
second
first
first
second
first

An override often extends the base operation by calling it explicitly:

class Window {
public:
    virtual ~Window() {}
    virtual void Draw() { /* draw the window */ }
};

class FramedWindow : public Window {
public:
    virtual void Draw() {
        Window::Draw();         // not a recursive call
        /* then draw the frame */
    }
};
Detailed notes - 10.6.13: Bypassing virtual dispatch

1

explicit class qualification suppresses virtual dispatch for that call

  • A::f() calls A's implementation even on a B object
  • an unqualified f() still dispatches to the override

example: b.g() and b.f() print second

  • b.h() and b.A::f() print first
  • pa->f() dispatches; pa->A::f() explicitly selects A

useful when an override extends the base operation

  • explicitly call the base version, then add derived behavior
Tests & experiments (2 files) - 10.6.13: Bypassing virtual dispatch
Section test13 (10-06)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
main.cppC++ / 26 lines
#include <stdio.h>

class A {
public:
    virtual void f() { printf("first\n"); }
    void g() { f(); }
    void h() { A::f(); }
};

class B : public A {
public:
    virtual void f() { printf("second\n"); }
};

int main()
{
    B b;
    b.g();
    b.h();
    b.f();
    b.A::f();
    A *pa = &b;
    pa->f();
    pa->A::f();
    return 0;
}

10.6.14 Explicit casts

Named casts make distinct conversion intentions visible, separating qualification changes, ordinary conversions, low-level reinterpretation, and checked downcasts. A failed dynamic pointer cast returns null, while a failed reference cast throws.

void old_print(char *s);        // an old interface that never modifies s
const char *msg = "hello";
old_print(const_cast<char*>(msg));          // only the qualification changes

double half = static_cast<double>(7) / 2;   // an ordinary conversion: 3.5

GraphObject *g = new Circle(0, 0, 1, 1);
Circle *c1 = static_cast<Circle*>(g);       // unchecked: we know it is a Circle
Circle *c2 = dynamic_cast<Circle*>(g);      // checked at run time
if (c2)
    c2->Show();                             // a Pixel would give a null pointer

int value = 1;
unsigned char *bytes = reinterpret_cast<unsigned char*>(&value);

Each named cast refuses conversions outside its category:

int *ip = const_cast<int*>(msg);            // error: changes the type
char *p = reinterpret_cast<char*>(msg);     // error: removes const
struct P { int x; };
struct Q : P { };
P *pp = 0;
Q *qq = dynamic_cast<Q*>(pp);               // error: P is not polymorphic
Detailed notes - 10.6.14: Explicit casts

1

C-style casts can conceal several different kinds of conversion

  • pointer reinterpretation especially needs careful reasoning
  • a cast does not establish object validity or permission to modify it

2

C++ named casts make the intended conversion category visible

  • syntax: cast_name<DestinationType>(expression)

const_cast changes appropriate const/volatile qualification

  • cannot convert an unrelated character pointer into an integer pointer
  • casting away const does not make a genuinely const object writable
  • first check whether a missing const-qualified interface is the problem

3

static_cast can perform a permitted base-to-derived pointer/reference cast

  • programmer must ensure the object has the required derived type
  • unrelated class pointers do not become related through this cast

correction: static_cast also supports many ordinary conversions

  • it is not restricted to inheritance casts

4

reinterpret_cast expresses specified low-level reinterpretations

  • does not remove const
  • is not permission to convert absolutely anything into anything
  • valid storage access still depends on type, lifetime and alignment rules

5

dynamic_cast can check a polymorphic downcast at runtime

  • failed pointer cast yields a null pointer
  • avoids asserting an unverified derived type with static_cast

6

the runtime check uses type information associated with polymorphic objects

  • checked downcasts need a polymorphic source, e.g. a virtual method
  • ordinary unambiguous upcasts do not need this runtime mechanism

7

the author discourages routine repeated dynamic_cast use

  • prefers behavior expressed through the shared virtual interface
  • actual cost depends on implementation and hierarchy

8

failed dynamic_cast to a reference throws std::bad_cast

  • a reference has no null result to return
  • the book prefers pointer casting followed by an explicit null check
Tests & experiments (7 files) - 10.6.14: Explicit casts
Section test14 (10-06)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
const_cast.cppC++ / 12 lines
int main()
{
    int *p;
    const int *q;
    const char *s;

    q = p;
    // p = q;
    p = const_cast<int*>(q);
    // p = const_cast<int*>(s);
    return 0;
}
dynamic_cast.cppC++ / 61 lines
#include <stdio.h>
#ifdef WITH_STD
#include <typeinfo>
#endif

class GraphObject {
public:
    virtual ~GraphObject() {}
};

class Circle : public GraphObject {
    int radius;
public:
    Circle(int r) : radius(r) {}
    void Grow() { radius *= 2; }
    int Radius() const { return radius; }
};

class Square : public GraphObject {
};

#ifdef WITH_STD
/* the reference form: failure is an exception from the library */
void grow(GraphObject& obj)
{
    try {
        Circle& c = dynamic_cast<Circle&>(obj);
        c.Grow();
        printf("circle, radius %d\n", c.Radius());
    }
    catch (const std::bad_cast&) {
        printf("not a circle\n");
    }
}
#else
/* the book's advice: address, pointer form, check, dereference */
void grow(GraphObject& obj)
{
    Circle *p = dynamic_cast<Circle*>(&obj);
    if (!p) {
        printf("not a circle\n");
        return;
    }
    Circle& c = *p;
    c.Grow();
    printf("circle, radius %d\n", c.Radius());
}
#endif

int main()
{
    Circle circle(5);
    Square square;
    grow(circle);
    grow(square);
#ifdef UNCAUGHT
    Circle& c = dynamic_cast<Circle&>(static_cast<GraphObject&>(square));
    c.Grow();
#endif
    return 0;
}
graphics.cppC++ / 125 lines
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

enum { rand_limit = 10 };

class GraphObject {
protected:
    double x, y;
    int color;
public:
    GraphObject(double ax, double ay, int acolor)
        : x(ax), y(ay), color(acolor) {}
    virtual ~GraphObject() {}
    virtual void Show() = 0;
    virtual void Hide() = 0;
    void Move(double nx, double ny);
};

void GraphObject::Move(double nx, double ny)
{
    Hide();
    printf("move graph object\n");
    x = nx;
    y = ny;
    Show();
}

class Pixel : public GraphObject {
public:
    Pixel(double x, double y, int color)
        : GraphObject(x, y, color) {}
    virtual ~Pixel() {}
    virtual void Show() { printf("hide pixel\n"); }
    virtual void Hide() { printf("show pixel\n"); }
};

class Circle : public GraphObject {
    double radius;
public:
    Circle(double x, double y, double rad, int color)
        : GraphObject(x, y, color), radius(rad) {}
    virtual ~Circle() {}
    virtual void Show() { printf("hide circle\n"); }
    virtual void Hide() { printf("show circle\n"); }
};


class PolygonalChain : public GraphObject {
    struct Vertex {
        double dx, dy;
        Vertex *next;
    };
    Vertex *first;
public:
    PolygonalChain(double x, double y, int color)
        : GraphObject(x, y, color), first(0) {}
    virtual ~PolygonalChain();
    void AddVertex(double adx, double ady);
    virtual void Show() { printf("hide polygonal chain\n"); }
    virtual void Hide() { printf("show polygonal chain\n"); }
};

void PolygonalChain::AddVertex(double adx, double ady)
{
    Vertex *tmp = new Vertex;
    tmp->dx = adx;
    tmp->dy = ady;
    tmp->next = first;
    first = tmp;
}

PolygonalChain::~PolygonalChain()
{
    while (first) {
        Vertex *tmp = first;
        first = first->next;
        delete tmp;
    }

}

class Square : public PolygonalChain {
public:
    Square(double x, double y, int color, double a)
        : PolygonalChain(x, y, color)
    {
        AddVertex(0, 0);
        AddVertex(0, a);
        AddVertex(a, a);
        AddVertex(a, 0);
        AddVertex(0, 0);
    }
};

int random_number(int limit)
{
    return 1.0 * limit * rand() / (RAND_MAX + 1.0);
}

int main()
{
    int i;
    srand(time(NULL));

    int scene_length = 3 + random_number(rand_limit);
    GraphObject **scene;

    scene = new GraphObject*[scene_length];

    scene[0] = new Pixel(1.25, 15.75, 0xff0000);
    scene[1] = new Circle(20.9, 7.25, 0x005500, 3.5);
    scene[2] = new Square(55.0, 30.5, 0x008080, 10.0);
    for (i = 3; i < scene_length; i++)
        scene[i] = new Circle(i, i, 0x0000ff, 1);

    // Square *sp = (Square*) scene[3];
    Square *sp = static_cast<Square*>(scene[3]);

    for (i = 0; i < scene_length; i++)
        delete scene[i];
    delete[] scene;

    return 0;
}
graphics01.cppC++ / 53 lines
#include <stdio.h>

class GraphObject {
public:
    virtual ~GraphObject() {}
    virtual const char *Name() const { return "object"; }
};

class Pixel : public GraphObject {
public:
    virtual const char *Name() const { return "pixel"; }
};

class Circle : public GraphObject {
    int radius;
public:
    Circle(int r) : radius(r) {}
    virtual const char *Name() const { return "circle"; }
    void SetRadius(int r) { radius = r; }
    int Radius() const { return radius; }
};

class Square : public GraphObject {
    int side;
public:
    Square(int s) : side(s) {}
    virtual const char *Name() const { return "square"; }
    int Side() const { return side; }
};

class Unrelated {
};

int main()
{
    GraphObject *p = new Square(7);
    Circle *c = static_cast<Circle*>(p);        /* it is a Square */
    printf("%s, radius %d\n", c->Name(), c->Radius());
    c->SetRadius(100);
    printf("side is now %d\n", static_cast<Square*>(p)->Side());
    printf("dynamic_cast: %p\n", (void*) dynamic_cast<Circle*>(p));
    delete p;
#ifdef SMALLER
    p = new Pixel;
    c = static_cast<Circle*>(p);                /* no radius there */
    c->SetRadius(100);
    delete p;
#endif
#ifdef ERRORS
    Unrelated *u = static_cast<Unrelated*>(p);
#endif
    return 0;
}
reinterpret_cast.cppC++ / 56 lines
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>

/* 1. look at an object as plain bytes */
void show_bytes()
{
    int n = 0x11223344;
    const unsigned char *bytes = reinterpret_cast<const unsigned char*>(&n);
    unsigned int i;
    for (i = 0; i < sizeof(n); i++)
        printf("%02x ", bytes[i]);
    printf("\n");
}

/* 2. an address as a number */
void show_address()
{
    int n;
    unsigned long addr = reinterpret_cast<unsigned long>(&n);
    printf("%lx, divisible by 4: %s\n", addr, addr % 4 == 0 ? "yes" : "no");
}

/* 3. a pointer to one structure as a pointer to another */
void bind_socket()
{
    struct sockaddr_in addr;
    socklen_t len = sizeof(addr);
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    addr.sin_port = 0;                  /* any free port */
    if (bind(fd, reinterpret_cast<struct sockaddr*>(&addr), len) == -1)
        perror("bind");
    getsockname(fd, reinterpret_cast<struct sockaddr*>(&addr), &len);
    printf("bound to port %d\n", ntohs(addr.sin_port));
    close(fd);
}

int main()
{
    show_bytes();
    show_address();
    bind_socket();
#ifdef ERRORS
    int n = 5;
    const int *cp = &n;
    unsigned char *a = static_cast<unsigned char*>(&n);
    double d = reinterpret_cast<double>(n);
    char *b = reinterpret_cast<char*>(cp);
#endif
    return 0;
}
static_cast.cppC++ / 18 lines
class A { };
class B : public A { };
class C { };

int main()
{
    A *ap;
    B *bp;
    // C *cp;

    ap = bp;
    // bp = ap;

    bp = static_cast<B*>(ap);
    // cp = static_cast<C*>(ap);

    return 0;
}

10.6.15 Exception hierarchies

An exception hierarchy supports recovery at different levels of specificity through a shared base interface. Catch specific types before general ones, and use references to avoid slicing a derived exception into a base-only copy.

#include <stdio.h>

class Error {
public:
    virtual ~Error() {}
    virtual const char *Message() const { return "error"; }
};

class UserError : public Error {
public:
    virtual const char *Message() const { return "invalid input"; }
};

class IncorrectPassword : public UserError {
public:
    virtual const char *Message() const { return "incorrect password"; }
};

class ExternalError : public Error {
public:
    virtual const char *Message() const { return "I/O failure"; }
};

void attempt(int kind)
{
    if (kind == 0)
        throw IncorrectPassword();
    if (kind == 1)
        throw UserError();
    throw ExternalError();
}

void try_one(int kind)
{
    try {
        attempt(kind);
    }
    catch (const IncorrectPassword &e) {    // most specific first
        printf("ask for the password again\n");
    }
    catch (const UserError &e) {
        printf("user error: %s\n", e.Message());
    }
    catch (const Error &e) {
        printf("other error: %s\n", e.Message());
    }
}

int main()
{
    try_one(0);
    try_one(1);
    try_one(2);
    try {
        throw ExternalError();
    }
    catch (Error e) {                       // by value: sliced to Error
        printf("by value: %s\n", e.Message());
    }
    return 0;
}
ask for the password again
user error: invalid input
other error: I/O failure
by value: error

g++ -Wall warns about the by-value handler: catching polymorphic type 'class Error' by value.

Detailed notes - 10.6.15: Exception hierarchies

1

inheritance supplies another relationship used by exception handlers

2

catch(const A&) accepts A and a suitably publicly derived B

  • the handler sees the base interface of the exception object

3

Error can be the root of a failure classification

  • UserError: input, filename, password, incompatible requests
  • ExternalError: storage, memory, I/O or network failures
  • Bug: broken program assumptions needing correction

more specific subclasses allow more specific handling

  • IncorrectPassword handler handles that category
  • UserError handler handles its broader family
  • Error handler handles the whole hierarchy

order catches from specific to general when both are present

  • prefer const-reference catching to retain the dynamic exception object
  • correction: catching a base by value can also match a derived exception, but copies only the base portion and slices it
Tests & experiments (4 files) - 10.6.15: Exception hierarchies
Section test15 (10-06)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
exceptions.cppC++ / 16 lines
#include <stdio.h>

class A { };
class B : public A { };

int main()
{
    try {
        // throw A();
        throw B();
    }
    catch (const A& ex) {
        printf("caught A childs\n");
    }
    return 0;
}
exceptions01.cppC++ / 28 lines
#include <stdio.h>

class Error {};
class UserError : public Error {};
class IncorrectInput : public UserError {};
class WrongFileName : public UserError {};
class IncorrectPassword : public UserError {};
class ExternalError : public Error {};
class Bug : public Error {};

int main()
{
    try {
        // throw IncorrectPassword();
        // throw WrongFileName();
        throw ExternalError();
    }
    catch (const IncorrectPassword& ex) {
        printf("incorrect password\n");
    }
    catch (const UserError& ex) {
        printf("user error\n");
    }
    catch (const Error& ex) {
        printf("any error\n");
    }
    return 0;
}
pointer.cppC++ / 46 lines
#include <stdio.h>

class Error {
    int code;
public:
    Error(int c) : code(c) {}
    ~Error() { printf("  destructor of Error %d\n", code); }
    int Code() const { return code; }
};

void throw_object() { throw Error(1); }
void throw_new() { throw new Error(2); }

void throw_local()
{
    Error e(3);
    throw &e;                   /* e dies during unwinding */
}

void attempt(void (*f)())
{
    try {
        f();
    }
    catch (const Error *ex) {
        printf("  caught a pointer\n");
        if (f == throw_new) {
            printf("  code %d\n", ex->Code());
            delete ex;          /* nobody else will */
        }
    }
    catch (const Error& ex) {
        printf("  caught an object, code %d\n", ex.Code());
    }
}

int main()
{
    printf("throw Error(1):\n");
    attempt(throw_object);
    printf("throw new Error(2):\n");
    attempt(throw_new);
    printf("throw &e:\n");
    attempt(throw_local);
    return 0;
}

10.7 Templates

Templates remove duplication when definitions vary by type or supported compile-time values. They generate concrete functions or classes, supporting parametric polymorphism and metaprogramming independently of object-oriented design.

Detailed notes - 10.7: Templates

1

duplicating nearly identical code creates repeated maintenance work

  • every fix must reach every copy
  • eventually one copy is easily missed

2

ordinary functions remove duplication when only values differ

  • parameters express the varying values
  • pointers/references can identify different variables to operate on

3

varying types are harder to express with an ordinary function

  • integer and floating-point elements need different operations/layout
  • C macros can generate variants but introduce their own difficulties

4

template: a parameterized definition used to produce functions or classes

  • common parameters are types; supported constant values are also possible
  • supply arguments to obtain a particular specialization
  • the author compares this generative role with sophisticated macros

5

templates support parametric polymorphism

  • their type-dependent work is resolved during compilation
  • they are useful independently of OOP

6

templates also support metaprogramming

  • describe how concrete program structures are to be generated
  • specialization can produce more than simple textual substitution
Examples & tests (6 files) - 10.7: Templates
Book exampleBook example: sparse_t.cppIn catalog
sparse_t.cppC++ / 311 lines
// The SparseArray template demo
// Copyright (c) Andrey Vikt. Stolyarov, 2010-2025
// This is just a sample program for a book devoted to C++, see
// http://www.stolyarov.info/books/cppintro for details.
// No rights restricted; do whatever you want with this code,
// if you really want to.


#include <stdio.h>

template<class T>
class SparseArray {
    struct Item {
        int index;
        T value;
        Item *next;
    };
    Item *first;
    T defval;
public:
    SparseArray(const T &dv) : first(0), defval(dv) {}
    ~SparseArray();
    class Interm {
        friend class SparseArray<T>;
        SparseArray<T> *master;
        int index;
        Interm(SparseArray<T> *a_master, int ind)
            : master(a_master), index(ind) {}
        T& Provide();
        void Remove();
    public:
        operator T();
        T operator=(const T &x);
        T operator+=(const T &x);
        T operator++();
        T operator++(int);
        T operator<<=(int n);
        T operator->() { return Provide(); }
    };
    friend class Interm;

    Interm operator[](int idx)
        { return Interm(this, idx); }
    T operator[](int idx) const;

    int NonzeroCount() const;

private:
    SparseArray(const SparseArray<T>&) {}
    void operator=(const SparseArray<T>&) {}
};

template <class T>
SparseArray<T>::~SparseArray()
{
    while(first) {
        Item *tmp = first;
        first = first->next;
        delete tmp;
    }
}

template <class T>
T SparseArray<T>::operator[](int idx) const
{
    Item* tmp;
    for(tmp = first; tmp; tmp = tmp->next)
        if(tmp->index == idx)
            return tmp->value;
    return defval;
}

template <class T>
int SparseArray<T>::NonzeroCount() const
{
    int r = 0;
    for(Item *tmp = first; tmp; tmp = tmp->next)
        r++;
    return r;
}

template <class T>
T& SparseArray<T>::Interm::Provide()
{
    Item* tmp;
    for(tmp = master->first; tmp; tmp = tmp->next)
        if(tmp->index == index)
            return tmp->value;
    tmp = new Item;
    tmp->index = index;
    tmp->next = master->first;
    master->first = tmp;
    return tmp->value;
}

template <class T>
void SparseArray<T>::Interm::Remove()
{
    Item** tmp;
    for(tmp = &(master->first); *tmp; tmp = &(*tmp)->next) {
        if((*tmp)->index == index) {
            Item *to_delete = *tmp;
            *tmp = (*tmp)->next;
            delete to_delete;
            return;
        }
    }
}

template <class T>
T SparseArray<T>::Interm::operator=(const T &x)
{
    if(x == master->defval)
        Remove();
    else
        Provide() = x;
    return x;
}

template <class T>
T SparseArray<T>::Interm::operator+=(const T &x)
{
    T& location = Provide();
    location += x;
    T res = location;
    if(res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator++()
{
    T& location = Provide();
    ++location;
    T res = location;
    if(location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator++(int)
{
    T& location = Provide();
    T res = location;
    location++;
    if(location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator<<=(int n)
{
    T& location = Provide();
    location <<= n;
    T res = location;
    if(res == master->defval)
        Remove();
    return res;
}

template <class T>
SparseArray<T>::Interm::operator T()
{
    Item* tmp;
    for(tmp = master->first; tmp; tmp = tmp->next)
        if(tmp->index == index)
            return tmp->value;
    return master->defval;
}

////////////////////////////////////////////////////////////
// tests

#ifdef TEST_ON_INT

static void do_query(SparseArray<int> &array, char *str)
{
    int idx, r;
    r = sscanf(str, "%d", &idx);
    if(r != 1) {
        printf("Invalid index\n");
        return;
    }
    printf("** array[%d] == %d\n", idx, (int) (array[idx]));
}

static void do_assign(SparseArray<int> &array, char *str)
{
    int idx, val, r;
    r = sscanf(str, "%d %d", &idx, &val);
    if(r != 2) {
        printf("Invalid numbers\n");
        return;
    }
    array[idx] = val;
}

int main()
{
    char buf[1024];
    SparseArray<int> array(0);
    printf("The following commands are recognized:\n"
           "   ? <key>            query the given key\n"
           "   ! <key> <value>    set the value for the key\n"
           "   #                  query the number of non-default items\n"
           "   q                  quit (or just EOF\n"
           "Please note both keys and values must be integers, suitable\n"
           "for 32 bit int\n");
    while(fgets(buf, sizeof(buf), stdin)) {
        switch(buf[0]) {
            case '?': do_query(array, buf+1); break;
            case '!': do_assign(array, buf+1); break;
            case '#':
                printf("%d items now\n", array.NonzeroCount());
                break;
            case 'q': return 0;
            default:
                printf("Unknown action, must be '?', '!', '#' or 'q'\n");
        }
    }
    return 0;
}

#else  // not TEST_ON_INT

#include <string.h>

class MyStr {
    char *p;
public:
    MyStr() {
        p = new char[1];
        *p = 0;
    }
    MyStr(const char *s) {
        int len = strlen(s);
        p = new char[len+1];
        strcpy(p, s);
    }
    MyStr(const MyStr &a) {
        int len = strlen(a.p);
        p = new char[len+1];
        strcpy(p, a.p);
    }
    ~MyStr() { delete[] p; }
    void operator=(const MyStr &s) {
        delete[] p;
        int len = strlen(s.p);
        p = new char[len+1];
        strcpy(p, s.p);
    }
    const char *str() const { return p; }
    bool operator==(const MyStr &s) const {
        return strcmp(p, s.p) == 0;
    }
};

static void do_query(SparseArray<MyStr> &array, char *str)
{
    int idx, r;
    r = sscanf(str, "%d", &idx);
    if(r != 1) {
        printf("Invalid index\n");
        return;
    }
    MyStr s = array[idx];
    printf("** array[%d] == %s\n", idx, s.str());
}

static void do_assign(SparseArray<MyStr> &array, char *str)
{
    int idx, r;
    char val[1024];
    r = sscanf(str, "%d %1023s", &idx, val);
    if(r != 2) {
        printf("Invalid numbers\n");
        return;
    }
    array[idx] = val;
}

int main()
{
    char buf[1024];
    SparseArray<MyStr> array(MyStr("--//--"));
    printf("The following commands are recognized:\n"
           "   ? <key>            query the given key\n"
           "   ! <key> <value>    set the value for the key\n"
           "   #                  query the number of non-default items\n"
           "   q                  quit (or just EOF\n"
           "Please note keys must be integers, suitable for 32 bit int,\n"
           "while a value may be any string not containing whitespace\n");
    while(fgets(buf, sizeof(buf), stdin)) {
        switch(buf[0]) {
            case '?': do_query(array, buf+1); break;
            case '!': do_assign(array, buf+1); break;
            case '#':
                printf("%d items now\n", array.NonzeroCount());
                break;
            case 'q': return 0;
            default:
                printf("Unknown action, must be '?', '!', '#' or 'q'\n");
        }
    }
    return 0;
}

#endif  // TEST_ON_INT
Section test00 (10-07)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
error00.cppC++ / 14 lines
#include <stdio.h>

#define SWAP(a, b) { int tmp = a; a = b; b = tmp; }

int main()
{
    int x = 5, y = 3;
    if (x > y)
        SWAP(x, y) //;
    else
        printf("already in order\n");
    printf("%d %d\n", x, y);
    return 0;
}
error01.cppC++ / 23 lines
#include <stdio.h>

#define REPEAT(n) { int repeat_i; for (repeat_i = 0; repeat_i < (n); repeat_i++) // {
#define END_REPEAT }

void greet()
{
    REPEAT(3)
        printf("hello\n");
    END_REPEAT
}

int square(int x)
{
    return x * x;
}

int main()
{
    greet();
    printf("%d\n", square(4));
    return 0;
}
templates.cppC++ / 50 lines
#include <stdio.h>

/* 1. a type */
template <class T>
T max_of(T a, T b)
{
    return a > b ? a : b;
}

/* 2. an integer value */
template <int size>
struct Buffer {
    char data[size];
    int Size() const { return size; }
};

/* 3. an address: of a global variable ... */
template <int *counter>
void count()
{
    ++*counter;
}

/* ... or of a function */
template <void (*report)(const char *)>
void check(bool ok, const char *msg)
{
    if (!ok)
        report(msg);
}

int errors = 0, warnings = 0;

void complain(const char *msg) { printf("problem: %s\n", msg); }

int main()
{
    Buffer<16> small;
    Buffer<4096> big;
    printf("%d %g\n", max_of<int>(3, 7), max_of<double>(2.5, 1.5));
    printf("%d %d\n", small.Size(), big.Size());
    printf("%lu %lu\n", (unsigned long) sizeof(small),
           (unsigned long) sizeof(big));
    count<&errors>();
    count<&errors>();
    count<&warnings>();
    printf("%d %d\n", errors, warnings);
    check<complain>(1 + 1 == 3, "arithmetic");
    return 0;
}
variables.cppC++ / 18 lines
#include <stdio.h>

void clamp(int *v, int min, int max)
{
    if (*v < min)
        *v = min;
    if (*v > max)
        *v = max;
}

int main()
{
    int width = 130, height = -5;
    clamp(&width, 0, 100);
    clamp(&height, 0, 50);
    printf("%d %d\n", width, height);
    return 0;
}

10.7.1 Function templates

A function template expresses one algorithm over different suitable types, as generic bubble sort replaces separate integer and floating-point versions. Instantiation and argument deduction supply concrete types, which must support the operations the algorithm requires.

template <class T>
void sort(T *array, int len)
{
    for (int start = 0; start < len - 1; start++) {
        bool swapped = false;
        for (int i = len - 1; i > start; i--) {
            if (array[i] < array[i-1]) {
                T tmp = array[i];
                array[i] = array[i-1];
                array[i-1] = tmp;
                swapped = true;
            }
        }
        if (!swapped)
            break;              // a pass without swaps: sorted
    }
}
int a[30];
double b[10];
// ... fill the arrays ...
sort<int>(a, 30);           // explicit template argument
sort(b, 10);                // deduced from the argument: sort<double>
Detailed notes - 10.7.1: Function templates

1

bubble-sort example:

  • scan adjacent pairs from the end toward the settled prefix
  • swap when the later element is smaller
  • a pass without swaps proves the array is sorted

integer and double versions otherwise have the same algorithm

  • differ in element pointer type and temporary swap variable type

2

template<class T> makes those types parameters of sort

  • T *array and T tmp replace the fixed int uses
  • class here means a type parameter, including built-in types
  • size, comparison and copying depend on the eventual argument type

3

sort<int> and sort<double> request concrete function specializations

  • any usable T must support copying, assignment and the comparison
  • the comparison must describe a suitable consistent ordering

4

instantiation produces the required function from the template

  • repeated calls to the same specialization do not require separate source copies of the algorithm

5

template argument deduction can infer T from the array argument

  • sort(a, 30) can select sort<int> for an int array
  • the book's claim that class arguments always require explicit spelling belongs to its older C++ subset
Template arguments are chosen at compile time; ordinary calls then use instantiated code.
One template produces type-specific operations. Open full size - Editable SVG
Tests & experiments (3 files) - 10.7.1: Function templates
Section test01 (10-07)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
bubble_sort_macro.cppC++ / 34 lines
#include <stdio.h>

#define MAKE_SORT(TYPE)                                 \
void sort_##TYPE(TYPE *array, int len)                  \
{                                                       \
    int start, i, done;                                 \
    TYPE tmp;                                           \
    for (start = 0; ; start++) {                        \
        done = 1;                                       \
        for (i = len - 2; i >= start; i--)              \
            if (array[i + 1] < array[i]) {              \
                tmp = array[i];                         \
                array[i] = array[i + 1];                \
                array[i + 1] = tmp;                     \
                done = 0;                               \
            }                                           \
        if (done)                                       \
            break;                                      \
    }                                                   \
}

MAKE_SORT(int)
MAKE_SORT(double)

int main()
{
    int a[] = { 5, 2, 8, 1 };
    double d[] = { 2.5, -1.0, 0.5 };
    sort_int(a, 4);
    sort_double(d, 3);
    printf("%d %d %d %d\n", a[0], a[1], a[2], a[3]);
    printf("%g %g %g\n", d[0], d[1], d[2]);
    return 0;
}
bubble_sort_template.cppC++ / 35 lines
#include <stdio.h>

template <class T>
inline void swap(T &x, T &y)
{
    T tmp = x;
    x = y;
    y = tmp;
}

template <class T>
void sort(T *array, int len)
{
    for (int start = 0; ; start++) {
        bool done = true;
        for (int i = len - 2; i >= start; i--)
            if (array[i+1] < array[i]) {
                swap(array[i], array[i+1]);
                done = false;
            }
        if (done)
            break;
    }
}

int main()
{
    int a[] = { 5, 2, 8, 1 };
    double d[] = { 2.5, -1.0, 0.5 };
    sort(a, 4);
    sort(d, 3);
    printf("%d %d %d %d\n", a[0], a[1], a[2], a[3]);
    printf("%g %g %g\n", d[0], d[1], d[2]);
    return 0;
}

10.7.2 Class templates

A generic sparse array needs a configurable default value and documented requirements on its element type. Its proxy cannot transparently forward every possible operation, and returning const references avoids silently modifying disposable copies during read access.

SparseArray<T> generalizes SparseArrayInt from 10.4.25. An element type need not have a zero, so the array stores a default value:

template <class T>
class SparseArray {
    struct Item {
        int index;
        T value;
        Item *next;
    };
    Item *first;
    T defval;
public:
    SparseArray(const T &dv) : first(0), defval(dv) {}
    ~SparseArray();
    class Interm {
        friend class SparseArray<T>;
        SparseArray<T> *master;
        int index;
        Interm(SparseArray<T> *a_master, int ind)
            : master(a_master), index(ind) {}
        T& Provide();
        void Remove();
    public:
        operator T() const;
        const T& operator=(const T &x);
    };
    friend class Interm;
    Interm operator[](int idx) { return Interm(this, idx); }
    const T& operator[](int idx) const;
private:
    SparseArray(const SparseArray<T> &);
    void operator=(const SparseArray<T> &);
};

Definitions outside the class repeat the template header:

template <class T>
const T& SparseArray<T>::Interm::operator=(const T &x)
{
    if (x == master->defval)
        Remove();
    else
        Provide() = x;
    return x;
}
Show the complete program
#include <stdio.h>

template <class T>
class SparseArray {
    struct Item {
        int index;
        T value;
        Item *next;
    };
    Item *first;
    T defval;
public:
    SparseArray(const T &dv) : first(0), defval(dv) {}
    ~SparseArray();
    class Interm {
        friend class SparseArray<T>;
        SparseArray<T> *master;
        int index;
        Interm(SparseArray<T> *a_master, int ind)
            : master(a_master), index(ind) {}
        T& Provide();
        void Remove();
    public:
        operator T() const;
        const T& operator=(const T &x);
    };
    friend class Interm;
    Interm operator[](int idx) { return Interm(this, idx); }
    const T& operator[](int idx) const;
private:
    SparseArray(const SparseArray<T> &);
    void operator=(const SparseArray<T> &);
};

template <class T>
SparseArray<T>::~SparseArray()
{
    while (first) {
        Item *tmp = first;
        first = first->next;
        delete tmp;
    }
}

template <class T>
const T& SparseArray<T>::operator[](int idx) const
{
    for (Item *tmp = first; tmp; tmp = tmp->next)
        if (tmp->index == idx)
            return tmp->value;
    return defval;
}

template <class T>
T& SparseArray<T>::Interm::Provide()
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    tmp = new Item;
    tmp->index = index;
    tmp->value = master->defval;
    tmp->next = master->first;
    master->first = tmp;
    return tmp->value;
}

template <class T>
void SparseArray<T>::Interm::Remove()
{
    Item **tmp;
    for (tmp = &master->first; *tmp; tmp = &(*tmp)->next) {
        if ((*tmp)->index == index) {
            Item *to_delete = *tmp;
            *tmp = (*tmp)->next;
            delete to_delete;
            return;
        }
    }
}

template <class T>
SparseArray<T>::Interm::operator T() const
{
    const SparseArray<T> *m = master;
    return (*m)[index];
}

template <class T>
const T& SparseArray<T>::Interm::operator=(const T &x)
{
    if (x == master->defval)
        Remove();
    else
        Provide() = x;
    return x;
}

int main()
{
    SparseArray<int> a(-1);
    a[10] = 5;
    a[20] = -1;                 // the default value: nothing is stored
    printf("%d %d %d\n", (int) a[10], (int) a[20], (int) a[30]);

    SparseArray<double> d(0.5);
    d[3] = 2.25;
    const SparseArray<double> &cd = d;
    printf("%g %g\n", cd[3], cd[4]);
    return 0;
}
5 -1 -1
2.25 0.5
Detailed notes - 10.7.2: Class templates

1

generalize SparseArrayInt instead of copying it for every element type

  • SparseArray<T> shares the same storage/proxy design

2

a generic element type need not have a usable numeric zero

  • constructor accepts a default value and stores it as defval
  • entries equal to defval need not be stored

3

the possible operations on an unknown T are not limited to integer operators

  • begin with assignment rather than pretending to implement all behavior

4

accept generic values through const references where appropriate

  • their copying cost is not known in advance

5

SparseArray<T> stores Item nodes with T values, plus first and defval

  • nested Interm holds SparseArray<T>* and the selected index
  • conversion supplies a T value; assignment updates/removes the entry
  • destructor releases nodes
  • out-of-class definitions begin template<class T> and qualify the relevant specialization, e.g. SparseArray<T>::Interm

correction to the listing:

  • the assignment definition must use const T& to match its declaration
  • C++ also permits the injected class name in appropriate class scope; the book's rule to spell <T> everywhere has exceptions

6

the full remaining example implementation is in the accompanying archive

  • its operations follow the preceding sparse integer design

7

an unknown element type makes a complete proxy interface difficult

  • its operations need not match the finite integer operator set

8

class-template member bodies are generally instantiated when required

  • an unused dependent <<= implementation need not invalidate an otherwise usable SparseArray<Complex>
  • actually requesting that operation requires T to support it
  • <<= updates through Provide and removes a result equal to defval

9

arbitrary fields and methods cannot all be forwarded by this proxy

  • array[idx].re and array[idx].GetRe() operate on Interm itself
  • . cannot be overloaded to redirect the operation
  • returning a real T& recreates the missing-element storage problem

10

const indexing returning T by value has another trap

  • calling a modifying method changes only the temporary result
  • it does not update the array element
  • a compile-successful expression can therefore conceal lost work

11

changing a parameter from mutable reference to const reference can expose

that difference without producing a diagnostic

12

for a reference-like read interface, return const T& from const indexing

  • prevents direct modification through the returned access
  • a stored entry can supply its value reference
  • an absent entry can refer to the owner's stored defval
  • those references still depend on owner/node lifetime

13

for pointer-like element types, forwarding operator-> can be useful

  • it does not solve arbitrary forwarding through the dot operator

14

this template still imposes concrete requirements on T

  • construction used by node allocation
  • copying, assignment and equality comparison with defval
  • the exact required operations depend on the implementation used

15

document a template's requirements

  • generic does not mean valid for every imaginable type
Tests & experiments (39 files) - 10.7.2: Class templates
Section test02 (10-07)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
sparse00.cppC++ / 309 lines
#include <stdio.h>

class SparseArrayInt {
    struct Item {
        int index;
        int value;
        Item *next;
    };
    Item *first;
public:
    SparseArrayInt() : first(0) {}
    ~SparseArrayInt();
    class Interm {
        friend class SparseArrayInt;
        SparseArrayInt *master;
        int index;
        Interm(SparseArrayInt *a_master, int ind)
            : master(a_master), index(ind) {}
        int& Provide();
        void Remove();
    public:
        operator int();
        int operator=(int x);

        int operator+=(int x);
        int operator-=(int x);
        int operator*=(int x);
        int operator/=(int x);
        int operator%=(int x);

        int operator<<=(int x);
        int operator>>=(int x);

        int operator|=(int x);
        int operator&=(int x);
        int operator^=(int x);

        int operator++();
        int operator++(int);
        int operator--();
        int operator--(int);
    };
    friend class Interm;

    Interm operator[](int idx)
        { return Interm(this, idx); };
    int operator[](int idx) const;

    int NonzeroCount() const;
private:
    SparseArrayInt(const SparseArrayInt&) {}
    void operator=(const SparseArrayInt&) {}
};

SparseArrayInt::~SparseArrayInt()
{
    while (first) {
        Item *tmp = first;
        first = first->next;
        delete tmp;
    }
}

int SparseArrayInt::operator[](int idx) const
{
    Item *tmp;
    for (tmp = first; tmp; tmp = tmp->next)
        if (tmp->index == idx)
            return tmp->value;
    return 0;
}

int SparseArrayInt::NonzeroCount() const
{
    int r = 0;
    for (Item *tmp = first; tmp; tmp = tmp->next)
        r++;
    return r;
}

int& SparseArrayInt::Interm::Provide()
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    tmp = new Item;
    tmp->index = index;
    tmp->value = 0;
    tmp->next = master->first;
    master->first = tmp;
    return tmp->value;
}

void SparseArrayInt::Interm::Remove()
{
    Item **tmp;
    for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
        if ((*tmp)->index == index) {
            Item *to_delete = *tmp;
            *tmp = (*tmp)->next;
            delete to_delete;
            return;
        }
}

int SparseArrayInt::Interm::operator=(int x)
{
    if (x == 0)
        Remove();
    else
        Provide() = x;
    return x;
}

int SparseArrayInt::Interm::operator+=(int x)
{
    int& location = Provide();
    location += x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator-=(int x)
{
    int& location = Provide();
    location -= x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator*=(int x)
{
    int& location = Provide();
    location *= x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator/=(int x)
{
    int& location = Provide();
    location /= x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator%=(int x)
{
    int& location = Provide();
    location %= x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator<<=(int x)
{
    int& location = Provide();
    location <<= x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator>>=(int x)
{
    int& location = Provide();
    location >>= x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator|=(int x)
{
    int& location = Provide();
    location |= x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator&=(int x)
{
    int& location = Provide();
    location &= x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator^=(int x)
{
    int& location = Provide();
    location ^= x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator++()
{
    int& location = Provide();
    location++;
    int res = location;
    if (location == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator++(int)
{
    int& location = Provide();
    int res = location;
    location++;
    if (location == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator--()
{
    int& location = Provide();
    location--;
    int res = location;
    if (location == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator--(int)
{
    int& location = Provide();
    int res = location;
    location--;
    if (location == 0)
        Remove();
    return res;
}

SparseArrayInt::Interm::operator int()
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    return 0;
}

static void do_query(SparseArrayInt &array, char *str)
{
    int idx, r;
    r = sscanf(str, "%d", &idx);
    if (r != 1) {
        printf("Invalid index\n");
        return;
    }
    printf("** array[%d] == %d\n", idx, (int) (array[idx]));
}

static void do_assign(SparseArrayInt &array, char *str)
{
    int idx, val, r;
    r = sscanf(str, "%d %d", &idx, &val);
    if (r != 2) {
        printf("Invalid numbers\n");
        return;
    }
    array[idx] = val;
}

int main()
{
    char buf[1024];
    SparseArrayInt array;
    while (fgets(buf, sizeof(buf), stdin)) {
        switch(buf[0]) {
            case '?':
                do_query(array, buf+1);
                break;
            case '!':
                do_assign(array, buf+1);
                break;
            case '#':
                printf("%d items now\n", array.NonzeroCount());
                break;
            case 'q':
                return 0;
            default:
                printf("Unknown action, must be '?', '!', '#' or 'q'\n");
        }
    }
    return 0;
}
sparse01.cppC++ / 423 lines
#include <stdio.h>

template <class T>
class SparseArray {
    struct Item {
        int index;
        T value;
        Item *next;
    };
    Item *first;
    T defval;
public:
    SparseArray(const T &dv) : first(0), defval(dv) {}
    ~SparseArray();
    class Interm {
        friend class SparseArray<T>;
        SparseArray<T> *master;
        int index;
        Interm(SparseArray<T> *a_master, int ind)
            : master(a_master), index(ind) {}
        T& Provide();
        void Remove();
    public:
        operator T();
        T operator=(const T& x);

        T operator+=(const T& x);
        T operator-=(const T& x);
        T operator*=(const T& x);
        T operator/=(const T& x);
        T operator%=(const T& x);

        T operator<<=(int n);
        T operator>>=(int n);

        T operator|=(const T& x);
        T operator&=(const T& x);
        T operator^=(const T& x);

        T operator++();
        T operator++(int);
        T operator--();
        T operator--(int);

        T operator->() { return Provide(); }
    };
    friend class Interm;

    Interm operator[](int idx) { return Interm(this, idx); };
    const T& operator[](int idx) const;

    int NonzeroCount() const;
private:
    SparseArray(const SparseArray<T>&) {}
    void operator=(const SparseArray<T>&) {}
};

template <class T>
SparseArray<T>::~SparseArray()
{
    while (first) {
        Item *tmp = first;
        first = first->next;
        delete tmp;
    }
}

template <class T>
const T& SparseArray<T>::operator[](int idx) const
{
    Item *tmp;
    for (tmp = first; tmp; tmp = tmp->next)
        if (tmp->index == idx)
            return tmp->value;
    return defval;
}

template <class T>
int SparseArray<T>::NonzeroCount() const
{
    int sum = 0;
    for (Item *tmp = first; tmp; tmp = tmp->next)
        sum++;
    return sum;
}

template <class T>
T& SparseArray<T>::Interm::Provide()
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    tmp = new Item;
    tmp->index = index;
    tmp->value = master->defval;
    tmp->next = master->first;
    master->first = tmp;
    return tmp->value;
}

template<class T>
void SparseArray<T>::Interm::Remove()
{
    Item **tmp;
    for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
        if ((*tmp)->index == index) {
            Item *to_delete = *tmp;
            *tmp = (*tmp)->next;
            delete to_delete;
            return;
        }
}

template <class T>
T SparseArray<T>::Interm::operator=(const T &x)
{
    if (x == master->defval)
        Remove();
    else
        Provide() = x;
    return x;
}

template <class T>
T SparseArray<T>::Interm::operator+=(const T& x)
{
    T& location = Provide();
    location += x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator-=(const T& x)
{
    T& location = Provide();
    location -= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator*=(const T& x)
{
    T& location = Provide();
    location *= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator/=(const T& x)
{
    T& location = Provide();
    location /= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator%=(const T& x)
{
    T& location = Provide();
    location %= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator<<=(int n)
{
    T& location = Provide();
    location <<= n;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator>>=(int n)
{
    T& location = Provide();
    location >>= n;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator|=(const T& x)
{
    T& location = Provide();
    location |= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator&=(const T& x)
{
    T& location = Provide();
    location &= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator^=(const T& x)
{
    T& location = Provide();
    location ^= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator++()
{
    T& location = Provide();
    ++location;
    T res = location;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator++(int)
{
    T& location = Provide();
    T res = location;
    location++;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator--()
{
    T& location = Provide();
    --location;
    T res = location;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator--(int)
{
    T& location = Provide();
    T res = location;
    location--;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
SparseArray<T>::Interm::operator T()
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    return master->defval;
}

#ifdef TEST_ON_INT

static void do_query(SparseArray<int> &array, char *str)
{
    int idx, r;
    r = sscanf(str, "%d", &idx);
    if (r != 1) {
        printf("Invalid index\n");
        return;
    }
    printf("%% array[%d] == %d\n", idx, (int) (array[idx]));
}

static void do_assign(SparseArray<int> &array, char *str)
{
    int idx, val, r;
    r = sscanf(str, "%d %d", &idx, &val);
    if (r != 2) {
        printf("Invalid numbers\n");
        return;
    }
    array[idx] = val;
}

int main()
{
    char buf[1024];
    SparseArray<int> array(0);
    printf("The following commands are recognized:\n"
           "   ? <key>            query the given key\n"
           "   ! <key> <value>    set the value for the key\n"
           "   #                  query the number of non-default items\n"
           "   q                  quit (or just EOF\n"
           "Please note both keys and values must be integers, suitable\n"
           "for 32 bit int\n");
    while(fgets(buf, sizeof(buf), stdin)) {
        switch(buf[0]) {
            case '?': do_query(array, buf+1); break;
            case '!': do_assign(array, buf+1); break;
            case '#':
                printf("%d items now\n", array.NonzeroCount());
                break;
            case 'q': return 0;
            default:
                printf("Unknown action, must be '?', '!', '#' or 'q'\n");
        }
    }
    return 0;
}

#else  // not TEST_ON_INT

#include <string.h>

class MyStr {
    char *p;
public:
    MyStr() {
        p = new char[1];
        *p = 0;
    }
    MyStr(const char *s) {
        int len = strlen(s);
        p = new char[len+1];
        strcpy(p, s);
    }
    MyStr(const MyStr &a) {
        int len = strlen(a.p);
        p = new char[len+1];
        strcpy(p, a.p);
    }
    ~MyStr() { delete[] p; }
    void operator=(const MyStr &s) {
        delete[] p;
        int len = strlen(s.p);
        p = new char[len+1];
        strcpy(p, s.p);
    }
    const char *str() const { return p; }
    bool operator==(const MyStr &s) const {
        return strcmp(p, s.p) == 0;
    }
};

static void do_query(SparseArray<MyStr> &array, char *str)
{
    int idx, r;
    r = sscanf(str, "%d", &idx);
    if(r != 1) {
        printf("Invalid index\n");
        return;
    }
    MyStr s = array[idx];
    printf("** array[%d] == %s\n", idx, s.str());
}

static void do_assign(SparseArray<MyStr> &array, char *str)
{
    int idx, r;
    char val[1024];
    r = sscanf(str, "%d %1023s", &idx, val);
    if(r != 2) {
        printf("Invalid numbers\n");
        return;
    }
    array[idx] = val;
}

int main()
{
    char buf[1024];
    SparseArray<MyStr> array(MyStr("--//--"));
    printf("The following commands are recognized:\n"
           "   ? <key>            query the given key\n"
           "   ! <key> <value>    set the value for the key\n"
           "   #                  query the number of non-default items\n"
           "   q                  quit (or just EOF\n"
           "Please note keys must be integers, suitable for 32 bit int,\n"
           "while a value may be any string not containing whitespace\n");
    while(fgets(buf, sizeof(buf), stdin)) {
        switch(buf[0]) {
            case '?': do_query(array, buf+1); break;
            case '!': do_assign(array, buf+1); break;
            case '#':
                printf("%d items now\n", array.NonzeroCount());
                break;
            case 'q': return 0;
            default:
                printf("Unknown action, must be '?', '!', '#' or 'q'\n");
        }
    }
    return 0;
}

#endif  // TEST_ON_INT
sparse02.cppC++ / 386 lines
#include <stdio.h>

template <class T>
class SparseArray {
    struct Item {
        int index;
        T value;
        Item *next;
    };
    Item *first;
    T defval;
public:
    SparseArray(const T &dv) : first(0), defval(dv) {}
    ~SparseArray();
    class Interm {
        friend class SparseArray<T>;
        SparseArray<T> *master;
        int index;
        Interm(SparseArray<T> *a_master, int ind)
            : master(a_master), index(ind) {}
        T& Provide();
        void Remove();
    public:
        operator T() const;
        T operator=(const T& x);
        T operator=(const Interm& x);

        T operator+=(const T& x);
        T operator-=(const T& x);
        T operator*=(const T& x);
        T operator/=(const T& x);
        T operator%=(const T& x);

        T operator<<=(int n);
        T operator>>=(int n);

        T operator|=(const T& x);
        T operator&=(const T& x);
        T operator^=(const T& x);

        T operator++();
        T operator++(int);
        T operator--();
        T operator--(int);

        T operator->() const { return *this; }
    };
    friend class Interm;

    Interm operator[](int idx) { return Interm(this, idx); }
    const T& operator[](int idx) const;

    int NonzeroCount() const;
private:
    SparseArray(const SparseArray<T>&) {}
    void operator=(const SparseArray<T>&) {}
};

template <class T>
SparseArray<T>::~SparseArray()
{
    while (first) {
        Item *tmp = first;
        first = first->next;
        delete tmp;
    }
}

template <class T>
const T& SparseArray<T>::operator[](int idx) const
{
    Item *tmp;
    for (tmp = first; tmp; tmp = tmp->next)
        if (tmp->index == idx)
            return tmp->value;
    return defval;
}

template <class T>
int SparseArray<T>::NonzeroCount() const
{
    int sum = 0;
    for (Item *tmp = first; tmp; tmp = tmp->next)
        sum++;
    return sum;
}

template <class T>
T& SparseArray<T>::Interm::Provide()
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    tmp = new Item;
    tmp->index = index;
    tmp->value = master->defval;
    tmp->next = master->first;
    master->first = tmp;
    return tmp->value;
}

template<class T>
void SparseArray<T>::Interm::Remove()
{
    Item **tmp;
    for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
        if ((*tmp)->index == index) {
            Item *to_delete = *tmp;
            *tmp = (*tmp)->next;
            delete to_delete;
            return;
        }
}

template <class T>
T SparseArray<T>::Interm::operator=(const T &x)
{
    if (x == master->defval)
        Remove();
    else
        Provide() = x;
    return x;
}

template <class T>
T SparseArray<T>::Interm::operator=(const Interm& x)
{
    T value = x;
    return *this = value;
}

template <class T>
T SparseArray<T>::Interm::operator+=(const T& x)
{
    T& location = Provide();
    location += x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator-=(const T& x)
{
    T& location = Provide();
    location -= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator*=(const T& x)
{
    T& location = Provide();
    location *= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator/=(const T& x)
{
    T& location = Provide();
    location /= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator%=(const T& x)
{
    T& location = Provide();
    location %= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator<<=(int n)
{
    T& location = Provide();
    location <<= n;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator>>=(int n)
{
    T& location = Provide();
    location >>= n;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator|=(const T& x)
{
    T& location = Provide();
    location |= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator&=(const T& x)
{
    T& location = Provide();
    location &= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator^=(const T& x)
{
    T& location = Provide();
    location ^= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator++()
{
    T& location = Provide();
    ++location;
    T res = location;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator++(int)
{
    T& location = Provide();
    T res = location;
    location++;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator--()
{
    T& location = Provide();
    --location;
    T res = location;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator--(int)
{
    T& location = Provide();
    T res = location;
    location--;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
SparseArray<T>::Interm::operator T() const
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    return master->defval;
}

class Counter {
    int n;
public:
    static int copies;
    Counter(int a = 0) : n(a) {}
    Counter(const Counter& other) : n(other.n) { copies++; }
    void Add(int k) { n += k; }
    int Get() const { return n; }
    bool operator==(const Counter& other) const { return n == other.n; }
};

int Counter::copies = 0;

struct Point {
    int x, y;
};

/* gets the array by const reference, so arr[i] is the const version */
int total(const SparseArray<Counter>& arr, int from, int to)
{
    int sum = 0;
    for (int i = from; i <= to; i++)
        sum += arr[i].Get();
    return sum;
}

/* the const version gives the stored object itself, not a copy */
void test_reference()
{
    SparseArray<Counter> a(Counter(0));
    const SparseArray<Counter>& c = a;
    a[1] = Counter(5);
    a[3] = Counter(7);
    printf("values:               %d %d %d\n",
           c[1].Get(), c[2].Get(), c[3].Get());
    printf("same element twice:   %d\n", &c[1] == &c[1]);
    printf("missing are defval:   %d\n", &c[2] == &c[100]);
    printf("existing is not:      %d\n", &c[1] == &c[2]);

    Counter::copies = 0;
    printf("total:                %d\n", total(a, 0, 10));
    printf("copies by const []:   %d\n", Counter::copies);
    Counter::copies = 0;
    Counter x = a[1];
    printf("copies by Interm:     %d (value %d)\n",
           Counter::copies, x.Get());
}

/* the reference follows the element, and can't be used to change it */
void test_reference_lifetime()
{
    SparseArray<Counter> a(Counter(0));
    const SparseArray<Counter>& c = a;
    a[3] = Counter(7);
    const Counter& r = c[3];
    a[3] = Counter(8);
    printf("reference sees 8:     %d\n", r.Get());
#ifdef ERRORS
    c[3].Add(5);
    c[3] = Counter(1);
#endif
#ifdef DANGLING
    a[3] = Counter(0);          /* removes the element r refers to */
    printf("%d\n", r.Get());    /* reads freed memory */
#endif
}

void test_fixes()
{
    SparseArray<int> a(0);
    SparseArray<Point*> ptrs(0);
    Point p = { 3, 4 };
    a[1] = 10;
    a[2] = 20;
    a[1] = a[2];
    printf("a[1] = a[2]:          %d\n", (int) a[1]);
    ptrs[1] = &p;
    ptrs[1]->x = 30;
    printf("arrow:                %d\n", p.x);
    ptrs[9].operator->();
    printf("count after ->:       %d\n", ptrs.NonzeroCount());
}

int main()
{
    test_reference();
    test_reference_lifetime();
    test_fixes();
    return 0;
}
Section test02b (10-07)In catalog
MakefileMake / 18 lines
SRCMODULES = complex.cpp sparse.cpp
OBJMODULES = $(SRCMODULES:.cpp=.o)

PROGRAMS = main

CXXFLAGS = -g -Wall -ansi -pedantic -Wno-long-long -fwrapv
LDLIBS   = -lm

all: $(PROGRAMS)

%.o: %.cpp %.hpp
    $(CXX) $(CXXFLAGS) -c $< -o $@

$(PROGRAMS): %: %.cpp $(OBJMODULES)
    $(CXX) $(CXXFLAGS) $^ -o $@

clean:
    rm -f *.o $(PROGRAMS)
complex.cppC++ / 22 lines
#include "complex.hpp"

const Complex& Complex::operator*=(const Complex &c)
{
    double r = re * c.re - im * c.im;
    double i = re * c.im + im * c.re;
    re = r;
    im = i;
    return *this;
}

const Complex& Complex::operator/=(const Complex &c)
{
    double dvs = c.re * c.re + c.im * c.im;
    double r = re * c.re + im * c.im / dvs;
    double i = im * c.re - re * c.im / dvs;
    re = r;
    im = i;
    return *this;
}


complex.hppC++ / 35 lines
#ifndef COMPLEX_HPP
#define COMPLEX_HPP

#include <math.h>

class Complex {
    double re, im;
public:
    Complex(double a_re = 0, double a_im = 0) : re(a_re), im(a_im) {}

    double GetRe() const { return re; }
    double GetIm() const { return im; }

    double Magnitude() const { return sqrt(re*re + im*im); }
    double Argument() const { return atan2(im, re); }

    const Complex& operator=(const Complex &c)
        { re = c.re; im = c.im; return *this; }

    const Complex &operator+=(const Complex &c)
        { re += c.re; im += c.im; return *this; }
    const Complex &operator-=(const Complex &c)
        { re -= c.re; im -= c.re; return *this; }
    const Complex &operator*=(const Complex &c);
    const Complex &operator/=(const Complex &c);

    void Print() const;
};

inline Complex operator+(Complex a, const Complex& b) { return a += b; }
inline Complex operator-(Complex a, const Complex& b) { return a -= b; }
inline Complex operator*(Complex a, const Complex& b) { return a *= b; }
inline Complex operator/(Complex a, const Complex& b) { return a /= b; }

#endif
main.cppC++ / 11 lines
#include <stdio.h>

#include "complex.hpp"
#include "sparse.hpp"

int main()
{
    SparseArray<Complex> s(Complex(0, 0));

    return 0;
}
sparse.cppC++ / 239 lines
#include "sparse.hpp"

template <class T>
SparseArray<T>::~SparseArray()
{
    while (first) {
        Item *tmp = first;
        first = first->next;
        delete tmp;
    }
}

template <class T>
const T& SparseArray<T>::operator[](int idx) const
{
    Item *tmp;
    for (tmp = first; tmp; tmp = tmp->next)
        if (tmp->index == idx)
            return tmp->value;
    return defval;
}

template <class T>
int SparseArray<T>::NonzeroCount() const
{
    int sum = 0;
    for (Item *tmp = first; tmp; tmp = tmp->next)
        sum++;
    return sum;
}

template <class T>
T& SparseArray<T>::Interm::Provide()
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    tmp = new Item;
    tmp->index = index;
    tmp->value = master->defval;
    tmp->next = master->first;
    master->first = tmp;
    return tmp->value;
}

template<class T>
void SparseArray<T>::Interm::Remove()
{
    Item **tmp;
    for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
        if ((*tmp)->index == index) {
            Item *to_delete = *tmp;
            *tmp = (*tmp)->next;
            delete to_delete;
            return;
        }
}

template <class T>
T SparseArray<T>::Interm::operator=(const T &x)
{
    if (x == master->defval)
        Remove();
    else
        Provide() = x;
    return x;
}

template <class T>
T SparseArray<T>::Interm::operator=(const Interm& x)
{
    T value = x;
    return *this = value;
}

template <class T>
T SparseArray<T>::Interm::operator+=(const T& x)
{
    T& location = Provide();
    location += x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator-=(const T& x)
{
    T& location = Provide();
    location -= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator*=(const T& x)
{
    T& location = Provide();
    location *= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator/=(const T& x)
{
    T& location = Provide();
    location /= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator%=(const T& x)
{
    T& location = Provide();
    location %= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator<<=(int n)
{
    T& location = Provide();
    location <<= n;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator>>=(int n)
{
    T& location = Provide();
    location >>= n;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator|=(const T& x)
{
    T& location = Provide();
    location |= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator&=(const T& x)
{
    T& location = Provide();
    location &= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator^=(const T& x)
{
    T& location = Provide();
    location ^= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator++()
{
    T& location = Provide();
    ++location;
    T res = location;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator++(int)
{
    T& location = Provide();
    T res = location;
    location++;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator--()
{
    T& location = Provide();
    --location;
    T res = location;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator--(int)
{
    T& location = Provide();
    T res = location;
    location--;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
SparseArray<T>::Interm::operator T() const
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    return master->defval;
}
sparse.hppC++ / 60 lines
#ifndef SPARSE_HPP
#define SPARSE_HPP

template <class T>
class SparseArray {
    struct Item {
        int index;
        T value;
        Item *next;
    };
    Item *first;
    T defval;
public:
    SparseArray(const T &dv) : first(0), defval(dv) {}
    ~SparseArray();
    class Interm {
        friend class SparseArray<T>;
        SparseArray<T> *master;
        int index;
        Interm(SparseArray<T> *a_master, int ind)
            : master(a_master), index(ind) {}
        T& Provide();
        void Remove();
    public:
        operator T() const;
        T operator=(const T& x);
        T operator=(const Interm& x);

        T operator+=(const T& x);
        T operator-=(const T& x);
        T operator*=(const T& x);
        T operator/=(const T& x);
        T operator%=(const T& x);

        T operator<<=(int n);
        T operator>>=(int n);

        T operator|=(const T& x);
        T operator&=(const T& x);
        T operator^=(const T& x);

        T operator++();
        T operator++(int);
        T operator--();
        T operator--(int);

        T operator->() const { return *this; }
    };
    friend class Interm;

    Interm operator[](int idx) { return Interm(this, idx); }
    const T& operator[](int idx) const;

    int NonzeroCount() const;
private:
    SparseArray(const SparseArray<T>&) {}
    void operator=(const SparseArray<T>&) {}
};

#endif
Section test02c (10-07)In catalog
MakefileMake / 20 lines
MODULES = complex sparse

SRCMODULES = $(wildcard $(MODULES:=.cpp))
HEADERS = $(wildcard $(MODULES:=.hpp))
OBJMODULES = $(SRCMODULES:.cpp=.o)

PROGRAMS = main

CXXFLAGS = -g -Wall -ansi -pedantic -Wno-long-long -fwrapv

all: $(PROGRAMS)

%.o: %.cpp $(HEADERS)
    $(CXX) $(CXXFLAGS) -c $< -o $@

$(PROGRAMS): %: %.cpp $(OBJMODULES) $(HEADERS)
    $(CXX) $(CXXFLAGS) $(filter-out %.hpp,$^) $(LDLIBS) -o $@

clean:
    rm -f *.o $(PROGRAMS)
complex.cppC++ / 20 lines
#include "complex.hpp"

const Complex& Complex::operator*=(const Complex &c)
{
    double r = re * c.re - im * c.im;
    double i = re * c.im + im * c.re;
    re = r;
    im = i;
    return *this;
}

const Complex& Complex::operator/=(const Complex &c)
{
    double dvs = c.re * c.re + c.im * c.im;
    double r = (re * c.re + im * c.im) / dvs;
    double i = (im * c.re - re * c.im) / dvs;
    re = r;
    im = i;
    return *this;
}
complex.hppC++ / 34 lines
#ifndef COMPLEX_HPP
#define COMPLEX_HPP

#include <math.h>

class Complex {
    double re, im;
public:
    Complex(double a_re = 0, double a_im = 0) : re(a_re), im(a_im) {}

    double GetRe() const { return re; }
    double GetIm() const { return im; }

    double Magnitude() const { return sqrt(re*re + im*im); }
    double Argument() const { return atan2(im, re); }

    const Complex &operator+=(const Complex &c)
        { re += c.re; im += c.im; return *this; }
    const Complex &operator-=(const Complex &c)
        { re -= c.re; im -= c.im; return *this; }
    const Complex &operator*=(const Complex &c);
    const Complex &operator/=(const Complex &c);

    bool operator==(const Complex &c) const
        { return re == c.re && im == c.im; }
    bool operator!=(const Complex &c) const { return !(*this == c); }
};

inline Complex operator+(Complex a, const Complex& b) { return a += b; }
inline Complex operator-(Complex a, const Complex& b) { return a -= b; }
inline Complex operator*(Complex a, const Complex& b) { return a *= b; }
inline Complex operator/(Complex a, const Complex& b) { return a /= b; }

#endif
main.cppC++ / 48 lines
#include <stdio.h>

#include "complex.hpp"
#include "sparse.hpp"

void show(const char *what, const Complex& c)
{
    printf("%-18s ", what);
    printf("%g %+gi", c.GetRe(), c.GetIm());
    printf("\n");
}

void test_complex()
{
    Complex a(3, 4), b(1, 2), c(3, 4);
    show("(3+4i) + (1+2i):", a + b);
    show("(3+4i) - (1+2i):", a - b);
    show("(3+4i) * (1+2i):", a * b);
    show("(3+4i) / (1+2i):", a / b);
    c /= c;
    show("c /= c:", c);
    show("1 + a:", 1 + a);
    printf("%-18s %g\n", "|3+4i|:", a.Magnitude());
    printf("%-18s %d %d\n", "==, !=:", a == Complex(3, 4), a != b);
}

void test_sparse()
{
    SparseArray<Complex> s(Complex(0, 0));
    const SparseArray<Complex>& c = s;
    s[1] = Complex(1, 2);
    s[5] = Complex(3, 4);
    s[5] *= c[1];
    s[7] += Complex(0, 1);
    show("s[1]:", c[1]);
    show("s[5]:", c[5]);
    show("s[7]:", c[7]);
    show("s[9]:", c[9]);
    s[1] -= c[1];
    printf("%-18s %d\n", "stored:", s.NonzeroCount());
}

int main()
{
    test_complex();
    test_sparse();
    return 0;
}
sparse.hppC++ / 298 lines
#ifndef SPARSE_HPP
#define SPARSE_HPP

template <class T>
class SparseArray {
    struct Item {
        int index;
        T value;
        Item *next;
    };
    Item *first;
    T defval;
public:
    SparseArray(const T &dv) : first(0), defval(dv) {}
    ~SparseArray();
    class Interm {
        friend class SparseArray<T>;
        SparseArray<T> *master;
        int index;
        Interm(SparseArray<T> *a_master, int ind)
            : master(a_master), index(ind) {}
        T& Provide();
        void Remove();
    public:
        operator T() const;
        T operator=(const T& x);
        T operator=(const Interm& x);

        T operator+=(const T& x);
        T operator-=(const T& x);
        T operator*=(const T& x);
        T operator/=(const T& x);
        T operator%=(const T& x);

        T operator<<=(int n);
        T operator>>=(int n);

        T operator|=(const T& x);
        T operator&=(const T& x);
        T operator^=(const T& x);

        T operator++();
        T operator++(int);
        T operator--();
        T operator--(int);

        T operator->() const { return *this; }
    };
    friend class Interm;

    Interm operator[](int idx) { return Interm(this, idx); }
    const T& operator[](int idx) const;

    int NonzeroCount() const;
private:
    SparseArray(const SparseArray<T>&) {}
    void operator=(const SparseArray<T>&) {}
};

template <class T>
SparseArray<T>::~SparseArray()
{
    while (first) {
        Item *tmp = first;
        first = first->next;
        delete tmp;
    }
}

template <class T>
const T& SparseArray<T>::operator[](int idx) const
{
    Item *tmp;
    for (tmp = first; tmp; tmp = tmp->next)
        if (tmp->index == idx)
            return tmp->value;
    return defval;
}

template <class T>
int SparseArray<T>::NonzeroCount() const
{
    int sum = 0;
    for (Item *tmp = first; tmp; tmp = tmp->next)
        sum++;
    return sum;
}

template <class T>
T& SparseArray<T>::Interm::Provide()
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    tmp = new Item;
    tmp->index = index;
    tmp->value = master->defval;
    tmp->next = master->first;
    master->first = tmp;
    return tmp->value;
}

template<class T>
void SparseArray<T>::Interm::Remove()
{
    Item **tmp;
    for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
        if ((*tmp)->index == index) {
            Item *to_delete = *tmp;
            *tmp = (*tmp)->next;
            delete to_delete;
            return;
        }
}

template <class T>
T SparseArray<T>::Interm::operator=(const T &x)
{
    if (x == master->defval)
        Remove();
    else
        Provide() = x;
    return x;
}

template <class T>
T SparseArray<T>::Interm::operator=(const Interm& x)
{
    T value = x;
    return *this = value;
}

template <class T>
T SparseArray<T>::Interm::operator+=(const T& x)
{
    T& location = Provide();
    location += x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator-=(const T& x)
{
    T& location = Provide();
    location -= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator*=(const T& x)
{
    T& location = Provide();
    location *= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator/=(const T& x)
{
    T& location = Provide();
    location /= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator%=(const T& x)
{
    T& location = Provide();
    location %= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator<<=(int n)
{
    T& location = Provide();
    location <<= n;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator>>=(int n)
{
    T& location = Provide();
    location >>= n;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator|=(const T& x)
{
    T& location = Provide();
    location |= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator&=(const T& x)
{
    T& location = Provide();
    location &= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator^=(const T& x)
{
    T& location = Provide();
    location ^= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator++()
{
    T& location = Provide();
    ++location;
    T res = location;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator++(int)
{
    T& location = Provide();
    T res = location;
    location++;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator--()
{
    T& location = Provide();
    --location;
    T res = location;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator--(int)
{
    T& location = Provide();
    T res = location;
    location--;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
SparseArray<T>::Interm::operator T() const
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    return master->defval;
}

#endif
Section test02d (10-07)In catalog
MakefileMake / 20 lines
MODULES = complex sparse

SRCMODULES = $(wildcard $(MODULES:=.cpp))
HEADERS = $(wildcard $(MODULES:=.hpp))
OBJMODULES = $(SRCMODULES:.cpp=.o)

PROGRAMS = main

CXXFLAGS = -g -Wall -ansi -pedantic -Wno-long-long -fwrapv

all: $(PROGRAMS)

%.o: %.cpp $(HEADERS)
    $(CXX) $(CXXFLAGS) -c $< -o $@

$(PROGRAMS): %: %.cpp $(OBJMODULES) $(HEADERS)
    $(CXX) $(CXXFLAGS) $(filter-out %.hpp,$^) $(LDLIBS) -o $@

clean:
    rm -f *.o $(PROGRAMS)
complex.cppC++ / 20 lines
#include "complex.hpp"

const Complex& Complex::operator*=(const Complex &c)
{
    double r = re * c.re - im * c.im;
    double i = re * c.im + im * c.re;
    re = r;
    im = i;
    return *this;
}

const Complex& Complex::operator/=(const Complex &c)
{
    double dvs = c.re * c.re + c.im * c.im;
    double r = (re * c.re + im * c.im) / dvs;
    double i = (im * c.re - re * c.im) / dvs;
    re = r;
    im = i;
    return *this;
}
complex.hppC++ / 37 lines
#ifndef COMPLEX_HPP
#define COMPLEX_HPP

#include <math.h>

class Complex {
    double re, im;
public:
    Complex(double a_re = 0, double a_im = 0) : re(a_re), im(a_im) {}

    double GetRe() const { return re; }
    double GetIm() const { return im; }

    // void SetRe(double r) { re = r; }
    // void SetIm(double i) { im = i; }

    double Magnitude() const { return sqrt(re*re + im*im); }
    double Argument() const { return atan2(im, re); }

    const Complex &operator+=(const Complex &c)
        { re += c.re; im += c.im; return *this; }
    const Complex &operator-=(const Complex &c)
        { re -= c.re; im -= c.im; return *this; }
    const Complex &operator*=(const Complex &c);
    const Complex &operator/=(const Complex &c);

    bool operator==(const Complex &c) const
        { return re == c.re && im == c.im; }
    bool operator!=(const Complex &c) const { return !(*this == c); }
};

inline Complex operator+(Complex a, const Complex& b) { return a += b; }
inline Complex operator-(Complex a, const Complex& b) { return a -= b; }
inline Complex operator*(Complex a, const Complex& b) { return a *= b; }
inline Complex operator/(Complex a, const Complex& b) { return a /= b; }

#endif
main.cppC++ / 29 lines
#include <stdio.h>

#include "complex.hpp"
#include "sparse.hpp"

void print(const SparseArray<Complex> &s, int i)
{
    printf("%g+%gi\n", s[i].GetRe(), s[i].GetIm());
}

// void f(const SparseArray<Complex> &s)
// {
//     s[1].SetRe(3);
// }

int main()
{
    SparseArray<Complex> s(Complex(0, 0));
    s[1] = Complex(1, 2);

    // s[1] <<= 2;
    // s[1].GetRe();

    // f(s);

    print(s, 2);

    return 0;
}
sparse.hppC++ / 298 lines
#ifndef SPARSE_HPP
#define SPARSE_HPP

template <class T>
class SparseArray {
    struct Item {
        int index;
        T value;
        Item *next;
    };
    Item *first;
    T defval;
public:
    SparseArray(const T &dv) : first(0), defval(dv) {}
    ~SparseArray();
    class Interm {
        friend class SparseArray<T>;
        SparseArray<T> *master;
        int index;
        Interm(SparseArray<T> *a_master, int ind)
            : master(a_master), index(ind) {}
        T& Provide();
        void Remove();
    public:
        operator T() const;
        T operator=(const T& x);
        T operator=(const Interm& x);

        T operator+=(const T& x);
        T operator-=(const T& x);
        T operator*=(const T& x);
        T operator/=(const T& x);
        T operator%=(const T& x);

        T operator<<=(int n);
        T operator>>=(int n);

        T operator|=(const T& x);
        T operator&=(const T& x);
        T operator^=(const T& x);

        T operator++();
        T operator++(int);
        T operator--();
        T operator--(int);

        T operator->() const { return *this; }
    };
    friend class Interm;

    Interm operator[](int idx) { return Interm(this, idx); }
    const T& operator[](int idx) const;

    int NonzeroCount() const;
private:
    SparseArray(const SparseArray<T>&) {}
    void operator=(const SparseArray<T>&) {}
};

template <class T>
SparseArray<T>::~SparseArray()
{
    while (first) {
        Item *tmp = first;
        first = first->next;
        delete tmp;
    }
}

template <class T>
const T& SparseArray<T>::operator[](int idx) const
{
    Item *tmp;
    for (tmp = first; tmp; tmp = tmp->next)
        if (tmp->index == idx)
            return tmp->value;
    return defval;
}

template <class T>
int SparseArray<T>::NonzeroCount() const
{
    int sum = 0;
    for (Item *tmp = first; tmp; tmp = tmp->next)
        sum++;
    return sum;
}

template <class T>
T& SparseArray<T>::Interm::Provide()
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    tmp = new Item;
    tmp->index = index;
    tmp->value = master->defval;
    tmp->next = master->first;
    master->first = tmp;
    return tmp->value;
}

template<class T>
void SparseArray<T>::Interm::Remove()
{
    Item **tmp;
    for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
        if ((*tmp)->index == index) {
            Item *to_delete = *tmp;
            *tmp = (*tmp)->next;
            delete to_delete;
            return;
        }
}

template <class T>
T SparseArray<T>::Interm::operator=(const T &x)
{
    if (x == master->defval)
        Remove();
    else
        Provide() = x;
    return x;
}

template <class T>
T SparseArray<T>::Interm::operator=(const Interm& x)
{
    T value = x;
    return *this = value;
}

template <class T>
T SparseArray<T>::Interm::operator+=(const T& x)
{
    T& location = Provide();
    location += x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator-=(const T& x)
{
    T& location = Provide();
    location -= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator*=(const T& x)
{
    T& location = Provide();
    location *= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator/=(const T& x)
{
    T& location = Provide();
    location /= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator%=(const T& x)
{
    T& location = Provide();
    location %= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator<<=(int n)
{
    T& location = Provide();
    location <<= n;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator>>=(int n)
{
    T& location = Provide();
    location >>= n;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator|=(const T& x)
{
    T& location = Provide();
    location |= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator&=(const T& x)
{
    T& location = Provide();
    location &= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator^=(const T& x)
{
    T& location = Provide();
    location ^= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator++()
{
    T& location = Provide();
    ++location;
    T res = location;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator++(int)
{
    T& location = Provide();
    T res = location;
    location++;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator--()
{
    T& location = Provide();
    --location;
    T res = location;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator--(int)
{
    T& location = Provide();
    T res = location;
    location--;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
SparseArray<T>::Interm::operator T() const
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    return master->defval;
}

#endif
Section test02e (10-07)In catalog
MakefileMake / 20 lines
MODULES = complex sparse

SRCMODULES = $(wildcard $(MODULES:=.cpp))
HEADERS = $(wildcard $(MODULES:=.hpp))
OBJMODULES = $(SRCMODULES:.cpp=.o)

PROGRAMS = main

CXXFLAGS = -g -Wall -ansi -pedantic -Wno-long-long -fwrapv

all: $(PROGRAMS)

%.o: %.cpp $(HEADERS)
    $(CXX) $(CXXFLAGS) -c $< -o $@

$(PROGRAMS): %: %.cpp $(OBJMODULES) $(HEADERS)
    $(CXX) $(CXXFLAGS) $(filter-out %.hpp,$^) $(LDLIBS) -o $@

clean:
    rm -f *.o $(PROGRAMS)
complex.cppC++ / 20 lines
#include "complex.hpp"

const Complex& Complex::operator*=(const Complex &c)
{
    double r = re * c.re - im * c.im;
    double i = re * c.im + im * c.re;
    re = r;
    im = i;
    return *this;
}

const Complex& Complex::operator/=(const Complex &c)
{
    double dvs = c.re * c.re + c.im * c.im;
    double r = (re * c.re + im * c.im) / dvs;
    double i = (im * c.re - re * c.im) / dvs;
    re = r;
    im = i;
    return *this;
}
complex.hppC++ / 34 lines
#ifndef COMPLEX_HPP
#define COMPLEX_HPP

#include <math.h>

class Complex {
    double re, im;
public:
    Complex(double a_re = 0, double a_im = 0) : re(a_re), im(a_im) {}

    double GetRe() const { return re; }
    double GetIm() const { return im; }

    double Magnitude() const { return sqrt(re*re + im*im); }
    double Argument() const { return atan2(im, re); }

    const Complex &operator+=(const Complex &c)
        { re += c.re; im += c.im; return *this; }
    const Complex &operator-=(const Complex &c)
        { re -= c.re; im -= c.im; return *this; }
    const Complex &operator*=(const Complex &c);
    const Complex &operator/=(const Complex &c);

    bool operator==(const Complex &c) const
        { return re == c.re && im == c.im; }
    bool operator!=(const Complex &c) const { return !(*this == c); }
};

inline Complex operator+(Complex a, const Complex& b) { return a += b; }
inline Complex operator-(Complex a, const Complex& b) { return a -= b; }
inline Complex operator*(Complex a, const Complex& b) { return a *= b; }
inline Complex operator/(Complex a, const Complex& b) { return a /= b; }

#endif
main.cppC++ / 22 lines
#include <stdio.h>

#include "complex.hpp"
#include "sparse.hpp"

int main()
{
    Complex zero(0, 0), z(1, -2), w(3, 4);
    SparseArray<Complex*> s(&zero);     /* elements are pointers */
    int i;
    s[1] = &z;
    s[4] = &w;

    printf("%g\n", s[4]->Magnitude());
    for (i = 0; i < 6; i++)
        printf("s[%d]: %g%+gi\n", i, s[i]->GetRe(), s[i]->GetIm());
    printf("stored: %d\n", s.NonzeroCount());

    *s[1] += Complex(10, 10);           /* changes z through the pointer */
    printf("z: %g%+gi\n", z.GetRe(), z.GetIm());
    return 0;
}
sparse.hppC++ / 298 lines
#ifndef SPARSE_HPP
#define SPARSE_HPP

template <class T>
class SparseArray {
    struct Item {
        int index;
        T value;
        Item *next;
    };
    Item *first;
    T defval;
public:
    SparseArray(const T &dv) : first(0), defval(dv) {}
    ~SparseArray();
    class Interm {
        friend class SparseArray<T>;
        SparseArray<T> *master;
        int index;
        Interm(SparseArray<T> *a_master, int ind)
            : master(a_master), index(ind) {}
        T& Provide();
        void Remove();
    public:
        operator T() const;
        T operator=(const T& x);
        T operator=(const Interm& x);

        T operator+=(const T& x);
        T operator-=(const T& x);
        T operator*=(const T& x);
        T operator/=(const T& x);
        T operator%=(const T& x);

        T operator<<=(int n);
        T operator>>=(int n);

        T operator|=(const T& x);
        T operator&=(const T& x);
        T operator^=(const T& x);

        T operator++();
        T operator++(int);
        T operator--();
        T operator--(int);

        T operator->() const { return *this; }
    };
    friend class Interm;

    Interm operator[](int idx) { return Interm(this, idx); }
    const T& operator[](int idx) const;

    int NonzeroCount() const;
private:
    SparseArray(const SparseArray<T>&) {}
    void operator=(const SparseArray<T>&) {}
};

template <class T>
SparseArray<T>::~SparseArray()
{
    while (first) {
        Item *tmp = first;
        first = first->next;
        delete tmp;
    }
}

template <class T>
const T& SparseArray<T>::operator[](int idx) const
{
    Item *tmp;
    for (tmp = first; tmp; tmp = tmp->next)
        if (tmp->index == idx)
            return tmp->value;
    return defval;
}

template <class T>
int SparseArray<T>::NonzeroCount() const
{
    int sum = 0;
    for (Item *tmp = first; tmp; tmp = tmp->next)
        sum++;
    return sum;
}

template <class T>
T& SparseArray<T>::Interm::Provide()
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    tmp = new Item;
    tmp->index = index;
    tmp->value = master->defval;
    tmp->next = master->first;
    master->first = tmp;
    return tmp->value;
}

template<class T>
void SparseArray<T>::Interm::Remove()
{
    Item **tmp;
    for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
        if ((*tmp)->index == index) {
            Item *to_delete = *tmp;
            *tmp = (*tmp)->next;
            delete to_delete;
            return;
        }
}

template <class T>
T SparseArray<T>::Interm::operator=(const T &x)
{
    if (x == master->defval)
        Remove();
    else
        Provide() = x;
    return x;
}

template <class T>
T SparseArray<T>::Interm::operator=(const Interm& x)
{
    T value = x;
    return *this = value;
}

template <class T>
T SparseArray<T>::Interm::operator+=(const T& x)
{
    T& location = Provide();
    location += x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator-=(const T& x)
{
    T& location = Provide();
    location -= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator*=(const T& x)
{
    T& location = Provide();
    location *= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator/=(const T& x)
{
    T& location = Provide();
    location /= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator%=(const T& x)
{
    T& location = Provide();
    location %= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator<<=(int n)
{
    T& location = Provide();
    location <<= n;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator>>=(int n)
{
    T& location = Provide();
    location >>= n;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator|=(const T& x)
{
    T& location = Provide();
    location |= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator&=(const T& x)
{
    T& location = Provide();
    location &= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator^=(const T& x)
{
    T& location = Provide();
    location ^= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator++()
{
    T& location = Provide();
    ++location;
    T res = location;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator++(int)
{
    T& location = Provide();
    T res = location;
    location++;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator--()
{
    T& location = Provide();
    --location;
    T res = location;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator--(int)
{
    T& location = Provide();
    T res = location;
    location--;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
SparseArray<T>::Interm::operator T() const
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    return master->defval;
}

#endif
Section test02f (10-07)In catalog
MakefileMake / 20 lines
MODULES = complex sparse

SRCMODULES = $(wildcard $(MODULES:=.cpp))
HEADERS = $(wildcard $(MODULES:=.hpp))
OBJMODULES = $(SRCMODULES:.cpp=.o)

PROGRAMS = main

CXXFLAGS = -g -Wall -ansi -pedantic -Wno-long-long -fwrapv

all: $(PROGRAMS)

%.o: %.cpp $(HEADERS)
    $(CXX) $(CXXFLAGS) -c $< -o $@

$(PROGRAMS): %: %.cpp $(OBJMODULES) $(HEADERS)
    $(CXX) $(CXXFLAGS) $(filter-out %.hpp,$^) $(LDLIBS) -o $@

clean:
    rm -f *.o $(PROGRAMS)
complex.cppC++ / 20 lines
#include "complex.hpp"

const Complex& Complex::operator*=(const Complex &c)
{
    double r = re * c.re - im * c.im;
    double i = re * c.im + im * c.re;
    re = r;
    im = i;
    return *this;
}

const Complex& Complex::operator/=(const Complex &c)
{
    double dvs = c.re * c.re + c.im * c.im;
    double r = (re * c.re + im * c.im) / dvs;
    double i = (im * c.re - re * c.im) / dvs;
    re = r;
    im = i;
    return *this;
}
complex.hppC++ / 35 lines
#ifndef COMPLEX_HPP
#define COMPLEX_HPP

#include <math.h>

class Complex {
    double re, im;
public:
    Complex(double a_re = 0, double a_im = 0) : re(a_re), im(a_im) {}

    double GetRe() const { return re; }
    double GetIm() const { return im; }
    void Set(double a_re, double a_im) { re = a_re; im = a_im; }

    double Magnitude() const { return sqrt(re*re + im*im); }
    double Argument() const { return atan2(im, re); }

    const Complex &operator+=(const Complex &c)
        { re += c.re; im += c.im; return *this; }
    const Complex &operator-=(const Complex &c)
        { re -= c.re; im -= c.im; return *this; }
    const Complex &operator*=(const Complex &c);
    const Complex &operator/=(const Complex &c);

    bool operator==(const Complex &c) const
        { return re == c.re && im == c.im; }
    bool operator!=(const Complex &c) const { return !(*this == c); }
};

inline Complex operator+(Complex a, const Complex& b) { return a += b; }
inline Complex operator-(Complex a, const Complex& b) { return a -= b; }
inline Complex operator*(Complex a, const Complex& b) { return a *= b; }
inline Complex operator/(Complex a, const Complex& b) { return a /= b; }

#endif
main.cppC++ / 30 lines
#include <stdio.h>

#include "complex.hpp"
#include "sparse.hpp"

void show(const char *name, const Complex& c)
{
    printf("%-6s %g%+gi\n", name, c.GetRe(), c.GetIm());
}

int main()
{
    Complex z(1, -2);
    SparseArray<Complex*> s(0);         /* default: no object */
    s[1] = &z;

    s[1]->Set(5, 6);
    show("z:", z);
    try {
        s[9]->Set(100, 100);            /* a missing element */
        printf("not reached\n");
    }
    catch (const NullElement& ex) {
        printf("element %d has no object\n", ex.Index());
    }
    if (s[9] != 0)                      /* or check before using -> */
        s[9]->Set(100, 100);
    printf("stored: %d\n", s.NonzeroCount());
    return 0;
}
sparse.hppC++ / 315 lines
#ifndef SPARSE_HPP
#define SPARSE_HPP

/* thrown by -> when the element holds a null pointer */
class NullElement {
    int index;
public:
    NullElement(int idx) : index(idx) {}
    int Index() const { return index; }
};

template <class T>
class SparseArray {
    struct Item {
        int index;
        T value;
        Item *next;
    };
    Item *first;
    T defval;
public:
    SparseArray(const T &dv) : first(0), defval(dv) {}
    ~SparseArray();
    class Interm {
        friend class SparseArray<T>;
        SparseArray<T> *master;
        int index;
        Interm(SparseArray<T> *a_master, int ind)
            : master(a_master), index(ind) {}
        T& Provide();
        void Remove();
    public:
        operator T() const;
        T operator=(const T& x);
        T operator=(const Interm& x);

        T operator+=(const T& x);
        T operator-=(const T& x);
        T operator*=(const T& x);
        T operator/=(const T& x);
        T operator%=(const T& x);

        T operator<<=(int n);
        T operator>>=(int n);

        T operator|=(const T& x);
        T operator&=(const T& x);
        T operator^=(const T& x);

        T operator++();
        T operator++(int);
        T operator--();
        T operator--(int);

        T operator->() const;
    };
    friend class Interm;

    Interm operator[](int idx) { return Interm(this, idx); }
    const T& operator[](int idx) const;

    int NonzeroCount() const;
private:
    SparseArray(const SparseArray<T>&) {}
    void operator=(const SparseArray<T>&) {}
};

template <class T>
SparseArray<T>::~SparseArray()
{
    while (first) {
        Item *tmp = first;
        first = first->next;
        delete tmp;
    }
}

template <class T>
const T& SparseArray<T>::operator[](int idx) const
{
    Item *tmp;
    for (tmp = first; tmp; tmp = tmp->next)
        if (tmp->index == idx)
            return tmp->value;
    return defval;
}

template <class T>
int SparseArray<T>::NonzeroCount() const
{
    int sum = 0;
    for (Item *tmp = first; tmp; tmp = tmp->next)
        sum++;
    return sum;
}

template <class T>
T& SparseArray<T>::Interm::Provide()
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    tmp = new Item;
    tmp->index = index;
    tmp->value = master->defval;
    tmp->next = master->first;
    master->first = tmp;
    return tmp->value;
}

template<class T>
void SparseArray<T>::Interm::Remove()
{
    Item **tmp;
    for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
        if ((*tmp)->index == index) {
            Item *to_delete = *tmp;
            *tmp = (*tmp)->next;
            delete to_delete;
            return;
        }
}

template <class T>
T SparseArray<T>::Interm::operator=(const T &x)
{
    if (x == master->defval)
        Remove();
    else
        Provide() = x;
    return x;
}

template <class T>
T SparseArray<T>::Interm::operator=(const Interm& x)
{
    T value = x;
    return *this = value;
}

template <class T>
T SparseArray<T>::Interm::operator+=(const T& x)
{
    T& location = Provide();
    location += x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator-=(const T& x)
{
    T& location = Provide();
    location -= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator*=(const T& x)
{
    T& location = Provide();
    location *= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator/=(const T& x)
{
    T& location = Provide();
    location /= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator%=(const T& x)
{
    T& location = Provide();
    location %= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator<<=(int n)
{
    T& location = Provide();
    location <<= n;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator>>=(int n)
{
    T& location = Provide();
    location >>= n;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator|=(const T& x)
{
    T& location = Provide();
    location |= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator&=(const T& x)
{
    T& location = Provide();
    location &= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator^=(const T& x)
{
    T& location = Provide();
    location ^= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator++()
{
    T& location = Provide();
    ++location;
    T res = location;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator++(int)
{
    T& location = Provide();
    T res = location;
    location++;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator--()
{
    T& location = Provide();
    --location;
    T res = location;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator--(int)
{
    T& location = Provide();
    T res = location;
    location--;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator->() const
{
    T p = *this;
    if (!p)
        throw NullElement(index);
    return p;
}

template <class T>
SparseArray<T>::Interm::operator T() const
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    return master->defval;
}

#endif
Section test02g (10-07)In catalog
MakefileMake / 20 lines
MODULES = complex sparse

SRCMODULES = $(wildcard $(MODULES:=.cpp))
HEADERS = $(wildcard $(MODULES:=.hpp))
OBJMODULES = $(SRCMODULES:.cpp=.o)

PROGRAMS = main

CXXFLAGS = -g -Wall -ansi -pedantic -Wno-long-long -fwrapv

all: $(PROGRAMS)

%.o: %.cpp $(HEADERS)
    $(CXX) $(CXXFLAGS) -c $< -o $@

$(PROGRAMS): %: %.cpp $(OBJMODULES) $(HEADERS)
    $(CXX) $(CXXFLAGS) $(filter-out %.hpp,$^) $(LDLIBS) -o $@

clean:
    rm -f *.o $(PROGRAMS)
complex.cppC++ / 20 lines
#include "complex.hpp"

const Complex& Complex::operator*=(const Complex &c)
{
    double r = re * c.re - im * c.im;
    double i = re * c.im + im * c.re;
    re = r;
    im = i;
    return *this;
}

const Complex& Complex::operator/=(const Complex &c)
{
    double dvs = c.re * c.re + c.im * c.im;
    double r = (re * c.re + im * c.im) / dvs;
    double i = (im * c.re - re * c.im) / dvs;
    re = r;
    im = i;
    return *this;
}
complex.hppC++ / 35 lines
#ifndef COMPLEX_HPP
#define COMPLEX_HPP

#include <math.h>

class Complex {
    double re, im;
public:
    Complex(double a_re = 0, double a_im = 0) : re(a_re), im(a_im) {}

    double GetRe() const { return re; }
    double GetIm() const { return im; }
    void Set(double a_re, double a_im) { re = a_re; im = a_im; }

    double Magnitude() const { return sqrt(re*re + im*im); }
    double Argument() const { return atan2(im, re); }

    const Complex &operator+=(const Complex &c)
        { re += c.re; im += c.im; return *this; }
    const Complex &operator-=(const Complex &c)
        { re -= c.re; im -= c.im; return *this; }
    const Complex &operator*=(const Complex &c);
    const Complex &operator/=(const Complex &c);

    bool operator==(const Complex &c) const
        { return re == c.re && im == c.im; }
    bool operator!=(const Complex &c) const { return !(*this == c); }
};

inline Complex operator+(Complex a, const Complex& b) { return a += b; }
inline Complex operator-(Complex a, const Complex& b) { return a -= b; }
inline Complex operator*(Complex a, const Complex& b) { return a *= b; }
inline Complex operator/(Complex a, const Complex& b) { return a /= b; }

#endif
main.cppC++ / 17 lines
#include <stdio.h>

#include "complex.hpp"
#include "sparse.hpp"

int main()
{
    SparseArray<Complex> s(Complex(0, 0));
    const SparseArray<Complex>& c = s;

    printf("%g%+gi\n", c[1].GetRe(), c[1].GetIm());     /* no == needed */
    s[1] = Complex(1, 2);                               /* needs == */
    printf("%g%+gi\n", c[1].GetRe(), c[1].GetIm());
    s[1] = Complex(0, 0);                               /* removes it */
    printf("stored: %d\n", s.NonzeroCount());
    return 0;
}
sparse.hppC++ / 315 lines
#ifndef SPARSE_HPP
#define SPARSE_HPP

/* thrown by -> when the element holds a null pointer */
class NullElement {
    int index;
public:
    NullElement(int idx) : index(idx) {}
    int Index() const { return index; }
};

template <class T>
class SparseArray {
    struct Item {
        int index;
        T value;
        Item *next;
    };
    Item *first;
    T defval;
public:
    SparseArray(const T &dv) : first(0), defval(dv) {}
    ~SparseArray();
    class Interm {
        friend class SparseArray<T>;
        SparseArray<T> *master;
        int index;
        Interm(SparseArray<T> *a_master, int ind)
            : master(a_master), index(ind) {}
        T& Provide();
        void Remove();
    public:
        operator T() const;
        T operator=(const T& x);
        T operator=(const Interm& x);

        T operator+=(const T& x);
        T operator-=(const T& x);
        T operator*=(const T& x);
        T operator/=(const T& x);
        T operator%=(const T& x);

        T operator<<=(int n);
        T operator>>=(int n);

        T operator|=(const T& x);
        T operator&=(const T& x);
        T operator^=(const T& x);

        T operator++();
        T operator++(int);
        T operator--();
        T operator--(int);

        T operator->() const;
    };
    friend class Interm;

    Interm operator[](int idx) { return Interm(this, idx); }
    const T& operator[](int idx) const;

    int NonzeroCount() const;
private:
    SparseArray(const SparseArray<T>&) {}
    void operator=(const SparseArray<T>&) {}
};

template <class T>
SparseArray<T>::~SparseArray()
{
    while (first) {
        Item *tmp = first;
        first = first->next;
        delete tmp;
    }
}

template <class T>
const T& SparseArray<T>::operator[](int idx) const
{
    Item *tmp;
    for (tmp = first; tmp; tmp = tmp->next)
        if (tmp->index == idx)
            return tmp->value;
    return defval;
}

template <class T>
int SparseArray<T>::NonzeroCount() const
{
    int sum = 0;
    for (Item *tmp = first; tmp; tmp = tmp->next)
        sum++;
    return sum;
}

template <class T>
T& SparseArray<T>::Interm::Provide()
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    tmp = new Item;
    tmp->index = index;
    tmp->value = master->defval;
    tmp->next = master->first;
    master->first = tmp;
    return tmp->value;
}

template<class T>
void SparseArray<T>::Interm::Remove()
{
    Item **tmp;
    for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
        if ((*tmp)->index == index) {
            Item *to_delete = *tmp;
            *tmp = (*tmp)->next;
            delete to_delete;
            return;
        }
}

template <class T>
T SparseArray<T>::Interm::operator=(const T &x)
{
    if (x == master->defval)
        Remove();
    else
        Provide() = x;
    return x;
}

template <class T>
T SparseArray<T>::Interm::operator=(const Interm& x)
{
    T value = x;
    return *this = value;
}

template <class T>
T SparseArray<T>::Interm::operator+=(const T& x)
{
    T& location = Provide();
    location += x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator-=(const T& x)
{
    T& location = Provide();
    location -= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator*=(const T& x)
{
    T& location = Provide();
    location *= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator/=(const T& x)
{
    T& location = Provide();
    location /= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator%=(const T& x)
{
    T& location = Provide();
    location %= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator<<=(int n)
{
    T& location = Provide();
    location <<= n;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator>>=(int n)
{
    T& location = Provide();
    location >>= n;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator|=(const T& x)
{
    T& location = Provide();
    location |= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator&=(const T& x)
{
    T& location = Provide();
    location &= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator^=(const T& x)
{
    T& location = Provide();
    location ^= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator++()
{
    T& location = Provide();
    ++location;
    T res = location;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator++(int)
{
    T& location = Provide();
    T res = location;
    location++;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator--()
{
    T& location = Provide();
    --location;
    T res = location;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator--(int)
{
    T& location = Provide();
    T res = location;
    location--;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator->() const
{
    T p = *this;
    if (!p)
        throw NullElement(index);
    return p;
}

template <class T>
SparseArray<T>::Interm::operator T() const
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    return master->defval;
}

#endif
Section test02h (10-07)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
sparse00.cppC++ / 281 lines
#include <stdio.h>

class SparseArrayInt {
    struct Item {
        int index;
        int value;
        Item *next;
    };
    Item *first;
public:
    SparseArrayInt() : first(0) {}
    ~SparseArrayInt();
    class Interm {
        friend class SparseArrayInt;
        SparseArrayInt *master;
        int index;
        Interm(SparseArrayInt *a_master, int ind)
            : master(a_master), index(ind) {}
        int& Provide();
        void Remove();
    public:
        operator int();
        int operator=(int x);

        int operator+=(int x);
        int operator-=(int x);
        int operator*=(int x);
        int operator/=(int x);
        int operator%=(int x);

        int operator<<=(int x);
        int operator>>=(int x);

        int operator|=(int x);
        int operator&=(int x);
        int operator^=(int x);

        int operator++();
        int operator++(int);
        int operator--();
        int operator--(int);
    };

    Interm operator[](int idx) { return Interm(this, idx); };
    int operator[](int idx) const;
private:
    SparseArrayInt(const SparseArrayInt&) {}
    void operator=(const SparseArrayInt&) {}
};

SparseArrayInt::~SparseArrayInt()
{
    while (first) {
        Item *tmp = first;
        first = first->next;
        delete tmp;
    }
}

int SparseArrayInt::operator[](int idx) const
{
    Item *tmp;
    for (tmp = first; tmp; tmp = tmp->next)
        if (tmp->index == idx)
            return tmp->value;
    return 0;
}

int SparseArrayInt::Interm::operator=(int x)
{
    if (x == 0)
        Remove();
    else
        Provide() = x;
    return x;
}

int SparseArrayInt::Interm::operator+=(int x)
{
    int& location = Provide();
    location += x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator-=(int x)
{
    int& location = Provide();
    location -= x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator*=(int x)
{
    int& location = Provide();
    location *= x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator/=(int x)
{
    int& location = Provide();
    location /= x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator%=(int x)
{
    int& location = Provide();
    location %= x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator<<=(int x)
{
    int& location = Provide();
    location <<= x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator>>=(int x)
{
    int& location = Provide();
    location >>= x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator|=(int x)
{
    int& location = Provide();
    location |= x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator&=(int x)
{
    int& location = Provide();
    location &= x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator^=(int x)
{
    int& location = Provide();
    location ^= x;
    int res = location;
    if (res == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator++()
{
    int& location = Provide();
    location++;
    int res = location;
    if (location == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator++(int)
{
    int& location = Provide();
    int res = location;
    location++;
    if (location == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator--()
{
    int& location = Provide();
    location--;
    int res = location;
    if (location == 0)
        Remove();
    return res;
}

int SparseArrayInt::Interm::operator--(int)
{
    int& location = Provide();
    int res = location;
    location--;
    if (location == 0)
        Remove();
    return res;
}

SparseArrayInt::Interm::operator int()
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    return 0;
}

int& SparseArrayInt::Interm::Provide()
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    tmp = new Item;
    tmp->index = index;
    tmp->value = 0;
    tmp->next = master->first;
    master->first = tmp;
    return tmp->value;
}

void SparseArrayInt::Interm::Remove()
{
    Item **tmp;
    for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
        if ((*tmp)->index == index) {
            Item *to_delete = *tmp;
            *tmp = (*tmp)->next;
            delete to_delete;
            return;
        }
}

int main()
{
    SparseArrayInt arr;
    int x;

    x = arr[500];
    printf("Initial arr[500]: %d\n", x);

    arr[300] = 50;
    printf("After arr[300] = 50: %d\n", int(arr[300]));

    arr[200] = 0;
    printf("After arr[200] = 0: %d\n", int(arr[200]));

    arr[15] += 100;
    printf("After arr[15] += 100: %d\n", int(arr[15]));

    x = arr[200]++;
    printf("After arr[200]++: returned %d, stored %d\n",
           x, int(arr[200]));

    arr[300] = 0;
    printf("After removing arr[300]: %d\n", int(arr[300]));

    arr[15] += -100;
    printf("After arr[15] += -100: %d\n", int(arr[15]));

    return 0;
}
sparse01.cppC++ / 311 lines
#include <stdio.h>

template<class T>
class SparseArray {
    struct Item {
        int index;
        T value;
        Item *next;
    };
    Item *first;
    T defval;
public:
    SparseArray(const T &dv) : first(0), defval(dv) {}
    ~SparseArray();
    class Interm {
        friend class SparseArray<T>;
        SparseArray<T> *master;
        int index;
        Interm(SparseArray<T> *a_master, int ind)
            : master(a_master), index(ind) {}
        T& Provide();
        void Remove();
    public:
        operator T();
        T operator=(const T &x);

        T operator+=(const T& x);
        T operator-=(const T& x);
        T operator*=(const T& x);
        T operator/=(const T& x);
        T operator%=(const T& x);

        T operator<<=(int x);
        T operator>>=(int x);

        T operator|=(const T& x);
        T operator&=(const T& x);
        T operator^=(const T& x);

        T operator++();
        T operator++(int);
        T operator--();
        T operator--(int);

        T operator->();
    };

    Interm operator[](int idx) { return Interm(this, idx); };
    const T& operator[](int idx) const;
private:
    SparseArray(const SparseArray<T>&) {}
    void operator=(const SparseArray<T>&) {}
};

template<class T>
SparseArray<T>::~SparseArray()
{
    while (first) {
        Item *tmp = first;
        first = first->next;
        delete tmp;
    }
}

template<class T>
const T& SparseArray<T>::operator[](int idx) const
{
    Item *tmp;
    for (tmp = first; tmp; tmp = tmp->next)
        if (tmp->index == idx)
            return tmp->value;
    return defval;
}

template <class T>
T SparseArray<T>::Interm::operator=(const T& x)
{
    if (x == master->defval)
        Remove();
    else
        Provide() = x;
    return x;
}

template <class T>
T SparseArray<T>::Interm::operator+=(const T& x)
{
    T& location = Provide();
    location += x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator-=(const T& x)
{
    T& location = Provide();
    location -= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator*=(const T& x)
{
    T& location = Provide();
    location *= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator/=(const T& x)
{
    T& location = Provide();
    location /= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator%=(const T& x)
{
    T& location = Provide();
    location %= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator<<=(int x)
{
    T& location = Provide();
    location <<= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator>>=(int x)
{
    T& location = Provide();
    location >>= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator|=(const T& x)
{
    T& location = Provide();
    location |= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator&=(const T& x)
{
    T& location = Provide();
    location &= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator^=(const T& x)
{
    T& location = Provide();
    location ^= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator++()
{
    T& location = Provide();
    location++;
    T res = location;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator++(int)
{
    T& location = Provide();
    T res = location;
    location++;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator--()
{
    T& location = Provide();
    location--;
    T res = location;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator--(int)
{
    T& location = Provide();
    T res = location;
    location--;
    if (location == master->defval)
        Remove();
    return res;
}

template<class T>
SparseArray<T>::Interm::operator T()
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    return master->defval;
}

template<class T>
T SparseArray<T>::Interm::operator->()
{
    return *this;
}

template<class T>
T& SparseArray<T>::Interm::Provide()
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    tmp = new Item;
    tmp->index = index;
    tmp->value = master->defval;
    tmp->next = master->first;
    master->first = tmp;
    return tmp->value;
}

template <class T>
void SparseArray<T>::Interm::Remove()
{
    Item **tmp;
    for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
        if ((*tmp)->index == index) {
            Item *to_delete = *tmp;
            *tmp = (*tmp)->next;
            delete to_delete;
            return;
        }
}

int main()
{
    SparseArray<int> arr(0);
    int x;

    x = arr[500];
    printf("Initial arr[500]: %d\n", x);

    arr[300] = 50;
    printf("After arr[300] = 50: %d\n", int(arr[300]));

    arr[200] = 0;
    printf("After arr[200] = 0: %d\n", int(arr[200]));

    arr[15] += 100;
    printf("After arr[15] += 100: %d\n", int(arr[15]));

    x = arr[200]++;
    printf("After arr[200]++: returned %d, stored %d\n",
           x, int(arr[200]));

    arr[300] = 0;
    printf("After removing arr[300]: %d\n", int(arr[300]));

    arr[15] += -100;
    printf("After arr[15] += -100: %d\n", int(arr[15]));

    return 0;
}
sparse02.cppC++ / 299 lines
#include <stdio.h>

template<class T>
class SparseArray {
    struct Item {
        int index;
        T value;
        Item *next;
    };
    Item *first;
    T defval;
public:
    SparseArray(const T &dv) : first(0), defval(dv) {}
    ~SparseArray();
    class Interm {
        friend class SparseArray<T>;
        SparseArray<T> *master;
        int index;
        Interm(SparseArray<T> *a_master, int ind)
            : master(a_master), index(ind) {}
        T& Provide();
        void Remove();
    public:
        operator T();
        T operator=(const T &x);

        T operator+=(const T& x);
        T operator-=(const T& x);
        T operator*=(const T& x);
        T operator/=(const T& x);
        T operator%=(const T& x);

        T operator<<=(int x);
        T operator>>=(int x);

        T operator|=(const T& x);
        T operator&=(const T& x);
        T operator^=(const T& x);

        T operator++();
        T operator++(int);
        T operator--();
        T operator--(int);

        T operator->();
    };

    Interm operator[](int idx) { return Interm(this, idx); };
    const T& operator[](int idx) const;
private:
    SparseArray(const SparseArray<T>&) {}
    void operator=(const SparseArray<T>&) {}
};

template<class T>
SparseArray<T>::~SparseArray()
{
    while (first) {
        Item *tmp = first;
        first = first->next;
        delete tmp;
    }
}

template<class T>
const T& SparseArray<T>::operator[](int idx) const
{
    Item *tmp;
    for (tmp = first; tmp; tmp = tmp->next)
        if (tmp->index == idx)
            return tmp->value;
    return defval;
}

template <class T>
T SparseArray<T>::Interm::operator=(const T& x)
{
    if (x == master->defval)
        Remove();
    else
        Provide() = x;
    return x;
}

template <class T>
T SparseArray<T>::Interm::operator+=(const T& x)
{
    T& location = Provide();
    location += x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator-=(const T& x)
{
    T& location = Provide();
    location -= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator*=(const T& x)
{
    T& location = Provide();
    location *= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator/=(const T& x)
{
    T& location = Provide();
    location /= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator%=(const T& x)
{
    T& location = Provide();
    location %= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator<<=(int x)
{
    T& location = Provide();
    location <<= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator>>=(int x)
{
    T& location = Provide();
    location >>= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator|=(const T& x)
{
    T& location = Provide();
    location |= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator&=(const T& x)
{
    T& location = Provide();
    location &= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator^=(const T& x)
{
    T& location = Provide();
    location ^= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator++()
{
    T& location = Provide();
    location++;
    T res = location;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator++(int)
{
    T& location = Provide();
    T res = location;
    location++;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator--()
{
    T& location = Provide();
    location--;
    T res = location;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator--(int)
{
    T& location = Provide();
    T res = location;
    location--;
    if (location == master->defval)
        Remove();
    return res;
}

template<class T>
SparseArray<T>::Interm::operator T()
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    return master->defval;
}

template<class T>
T SparseArray<T>::Interm::operator->()
{
    return *this;
}

template<class T>
T& SparseArray<T>::Interm::Provide()
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    tmp = new Item;
    tmp->index = index;
    tmp->value = master->defval;
    tmp->next = master->first;
    master->first = tmp;
    return tmp->value;
}

template <class T>
void SparseArray<T>::Interm::Remove()
{
    Item **tmp;
    for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
        if ((*tmp)->index == index) {
            Item *to_delete = *tmp;
            *tmp = (*tmp)->next;
            delete to_delete;
            return;
        }
}

struct s1 {
    int a;
    int b;
};

int main()
{
    s1 x = { 0, 0 };
    SparseArray<s1*> arr(0);
    arr[0] = &x;
    arr[0]->a = 1;
    arr[0]->b = 2;
    s1 *p = arr[0].operator->();
    printf("%d %d\n", arr[0]->a, arr[0]->b);

    return 0;
}

10.7.3 Template specialization

Specialization replaces a general template implementation for selected arguments, such as comparing string contents instead of pointer addresses. Class templates also permit partial specialization and can change representation for cases such as sparse booleans.

The comparison moves into a helper template, specialized for strings:

template <class T>
bool sort_less(T a, T b)
{
    return a < b;
}

template <>
bool sort_less<const char*>(const char *a, const char *b)
{
    return strcmp(a, b) < 0;
}

Class templates can also be specialized partially:

template <class T>
class Foo {
public:
    static const char *Kind() { return "value"; }
};

template <class T>
class Foo<T*> {                 // any pointer type
public:
    static const char *Kind() { return "pointer"; }
};
const char *k1 = Foo<int>::Kind();      // "value"
const char *k2 = Foo<int*>::Kind();     // "pointer"

Function templates cannot be:

template <class T> void show(T x);
template <class T> void show<T*>(T *x);     // error: partial specialization
Show the complete program
#include <stdio.h>
#include <string.h>

template <class T>
bool sort_less(T a, T b)
{
    return a < b;
}

template <>
bool sort_less<const char*>(const char *a, const char *b)
{
    return strcmp(a, b) < 0;
}

template <class T>
void sort(T *array, int len)
{
    for (int start = 0; start < len - 1; start++) {
        bool swapped = false;
        for (int i = len - 1; i > start; i--) {
            if (sort_less(array[i], array[i-1])) {
                T tmp = array[i];
                array[i] = array[i-1];
                array[i-1] = tmp;
                swapped = true;
            }
        }
        if (!swapped)
            break;
    }
}

int main()
{
    int n[5] = { 42, 7, 19, 3, 25 };
    const char *w[4] = { "pear", "apple", "plum", "fig" };

    sort(n, 5);
    sort(w, 4);
    for (int i = 0; i < 5; i++)
        printf("%d%s", n[i], i < 4 ? " " : "\n");
    for (int i = 0; i < 4; i++)
        printf("%s%s", w[i], i < 3 ? " " : "\n");
    return 0;
}
3 7 19 25 42
apple fig pear plum
Detailed notes - 10.7.3: Template specialization

1

specialization supplies a different implementation for selected arguments

  • use it instead of the general definition in those cases

2

string-pointer sorting needs lexical comparison, not pointer comparison

  • factor comparison into a sort_less helper template
  • ordinary T uses a < b
  • the sorting algorithm stays unchanged

3

explicit specialization begins template<>

  • sort_less<const char*> uses strcmp(a, b) < 0
  • applies to const char* specifically
  • char* is a different template argument and needs appropriate handling

4

class specialization can replace representation as well as operations

  • SparseArray<bool> can store indexes of exceptional bits only
  • with default false, presence means true
  • with a configurable default, presence means the opposite of that default

partial class specialization leaves some parameters variable

  • Cls<X, int> fixes only the second parameter
  • Foo<T*> recognizes pointer arguments and binds the pointed-to type

5

function templates do not permit partial specialization

  • class templates do
  • declare the primary before its specializations and make a needed specialization available before instantiating that case
Tests & experiments (26 files) - 10.7.3: Template specialization
Section test03 (10-07)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
bubble_sort00.cppC++ / 35 lines
#include <stdio.h>

template <class T>
inline void swap(T &x, T &y)
{
    T tmp = x;
    x = y;
    y = tmp;
}

template <class T>
void sort(T *array, int len)
{
    for (int start = 0; ; start++) {
        bool done = true;
        for (int i = len - 2; i >= start; i--)
            if (array[i+1] < array[i]) {
                swap(array[i], array[i+1]);
                done = false;
            }
        if (done)
            break;
    }
}

int main()
{
    int a[] = { 5, 2, 8, 1 };
    double d[] = { 2.5, -1.0, 0.5 };
    sort(a, 4);
    sort(d, 3);
    printf("%d %d %d %d\n", a[0], a[1], a[2], a[3]);
    printf("%g %g %g\n", d[0], d[1], d[2]);
    return 0;
}
bubble_sort01.cppC++ / 66 lines
#include <stdio.h>
#include <string.h>

template <class T>
inline void swap(T &x, T &y)
{
    T tmp = x;
    x = y;
    y = tmp;
}

template <class T>
bool sort_less(T a, T b)
{
    return a < b;
}

template <>
bool sort_less<const char *>(const char *a, const char *b)
{
    return strcmp(a, b) < 0;
}

template <class T>
void sort(T *array, int len)
{
    for (int start = 0; ; start++) {
        bool done = true;
        for (int i = len - 2; i >= start; i--)
            if (sort_less(array[i+1], array[i])) {
                swap(array[i], array[i+1]);
                done = false;
            }
        if (done)
            break;
    }
}

int main()
{
    int a[] = { 5, 2, 8, 1 };
    int len_a = sizeof(a) / sizeof(*a);
    double d[] = { 2.5, -1.0, 0.5 };
    int len_d = sizeof(d) / sizeof(*d);
    const char *s[] = {"hello", "there", "how", "are", "you"};
    int len_s = sizeof(s) / sizeof(*s);

    sort(a, len_a);
    sort(d, len_d);
    sort(s, len_s);

    int i;
    for (i = 0; i < len_a; i++)
        printf("%d ", a[i]);
    printf("\n");

    for (i = 0; i < len_d; i++)
        printf("%g ", d[i]);
    printf("\n");

    for (i = 0; i < len_s; i++)
        printf("%s ", s[i]);
    printf("\n");

    return 0;
}
Section test03b (10-07)In catalog
MakefileMake / 20 lines
MODULES = sparse

SRCMODULES = $(wildcard $(MODULES:=.cpp))
HEADERS = $(wildcard $(MODULES:=.hpp))
OBJMODULES = $(SRCMODULES:.cpp=.o)

PROGRAMS = main

CXXFLAGS = -g -Wall -ansi -pedantic -Wno-long-long -fwrapv

all: $(PROGRAMS)

%.o: %.cpp $(HEADERS)
    $(CXX) $(CXXFLAGS) -c $< -o $@

$(PROGRAMS): %: %.cpp $(OBJMODULES) $(HEADERS)
    $(CXX) $(CXXFLAGS) $(filter-out %.hpp,$^) $(LDLIBS) -o $@

clean:
    rm -f *.o $(PROGRAMS)
main.cppC++ / 15 lines
#include <stdio.h>

#include "sparse.hpp"

int main()
{
    SparseArray<bool> b;

    b[0] = 3;
    b[1] = 25;

    printf("%d\n", (int) b[1]);

    return 0;
}
sparse.hppC++ / 403 lines
#ifndef SPARSE_HPP
#define SPARSE_HPP

class NullElement {
    int index;
public:
    NullElement(int idx) : index(idx) {}
    int Index() const { return index; }
};

template <class T>
class SparseArray {
    struct Item {
        int index;
        T value;
        Item *next;
    };
    Item *first;
    T defval;
public:
    SparseArray(const T &dv) : first(0), defval(dv) {}
    ~SparseArray();
    class Interm {
        friend class SparseArray<T>;
        SparseArray<T> *master;
        int index;
        Interm(SparseArray<T> *a_master, int ind)
            : master(a_master), index(ind) {}
        T& Provide();
        void Remove();
    public:
        operator T() const;
        T operator=(const T& x);
        T operator=(const Interm& x);

        T operator+=(const T& x);
        T operator-=(const T& x);
        T operator*=(const T& x);
        T operator/=(const T& x);
        T operator%=(const T& x);

        T operator<<=(int n);
        T operator>>=(int n);

        T operator|=(const T& x);
        T operator&=(const T& x);
        T operator^=(const T& x);

        T operator++();
        T operator++(int);
        T operator--();
        T operator--(int);

        T operator->() const;
    };
    friend class Interm;

    Interm operator[](int idx) { return Interm(this, idx); }
    const T& operator[](int idx) const;

    int NonzeroCount() const;
private:
    SparseArray(const SparseArray<T>&) {}
    void operator=(const SparseArray<T>&) {}
};

template <class T>
SparseArray<T>::~SparseArray()
{
    while (first) {
        Item *tmp = first;
        first = first->next;
        delete tmp;
    }
}

template <class T>
const T& SparseArray<T>::operator[](int idx) const
{
    Item *tmp;
    for (tmp = first; tmp; tmp = tmp->next)
        if (tmp->index == idx)
            return tmp->value;
    return defval;
}

template <class T>
int SparseArray<T>::NonzeroCount() const
{
    int sum = 0;
    for (Item *tmp = first; tmp; tmp = tmp->next)
        sum++;
    return sum;
}

template <class T>
T& SparseArray<T>::Interm::Provide()
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    tmp = new Item;
    tmp->index = index;
    tmp->value = master->defval;
    tmp->next = master->first;
    master->first = tmp;
    return tmp->value;
}

template<class T>
void SparseArray<T>::Interm::Remove()
{
    Item **tmp;
    for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
        if ((*tmp)->index == index) {
            Item *to_delete = *tmp;
            *tmp = (*tmp)->next;
            delete to_delete;
            return;
        }
}

template <class T>
T SparseArray<T>::Interm::operator=(const T &x)
{
    if (x == master->defval)
        Remove();
    else
        Provide() = x;
    return x;
}

template <class T>
T SparseArray<T>::Interm::operator=(const Interm& x)
{
    T value = x;
    return *this = value;
}

template <class T>
T SparseArray<T>::Interm::operator+=(const T& x)
{
    T& location = Provide();
    location += x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator-=(const T& x)
{
    T& location = Provide();
    location -= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator*=(const T& x)
{
    T& location = Provide();
    location *= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator/=(const T& x)
{
    T& location = Provide();
    location /= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator%=(const T& x)
{
    T& location = Provide();
    location %= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator<<=(int n)
{
    T& location = Provide();
    location <<= n;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator>>=(int n)
{
    T& location = Provide();
    location >>= n;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator|=(const T& x)
{
    T& location = Provide();
    location |= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator&=(const T& x)
{
    T& location = Provide();
    location &= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator^=(const T& x)
{
    T& location = Provide();
    location ^= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator++()
{
    T& location = Provide();
    ++location;
    T res = location;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator++(int)
{
    T& location = Provide();
    T res = location;
    location++;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator--()
{
    T& location = Provide();
    --location;
    T res = location;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator--(int)
{
    T& location = Provide();
    T res = location;
    location--;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator->() const
{
    T p = *this;
    if (!p)
        throw NullElement(index);
    return p;
}

template <class T>
SparseArray<T>::Interm::operator T() const
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    return master->defval;
}

template <>
class SparseArray<bool> {
    int *array;
    int len;
    int capacity;
    int defval;
public:
    SparseArray(int dv = 0, int c = 64) : len(0), capacity(c), defval(dv)
        { array = new int[capacity]; }
    ~SparseArray() { delete[] array; };
    class Interm {
        friend class SparseArray<bool>;
        SparseArray *master;
        int index;
        Interm(SparseArray *a_master, int ind)
            : master(a_master), index(ind) {}
        int& Provide();
        void Remove();
    public:
        operator int() const;
        int operator=(const int& x);
    };
    friend class Interm;

    Interm operator[](int idx) { return Interm(this, idx); }
    const int& operator[](int idx) const;

    int NonzeroCount() const { return len; }
private:
    SparseArray(const SparseArray&) {}
    void operator=(const SparseArray&) {}
};

const int& SparseArray<bool>::operator[](int idx) const
{
    for (int i = 0; i < len; i++)
        if (i == idx)
            return array[i];
    return defval;
}

int& SparseArray<bool>::Interm::Provide()
{
    for (int i = 0; i < master->len; i++)
        if (i == index)
            return master->array[i];

    if (master->len == master->capacity) {
        int new_capacity = 2 * master->capacity;
        int *new_array = new int[new_capacity];
        master->capacity = new_capacity;
        for (int i = 0; i < master->len; i++)
            new_array[i] = master->array[i];
        delete[] master->array;
        master->array = new_array;
    }
    master->array[master->len] = master->defval;
    master->len++;
    return master->array[master->len-1];
}

void SparseArray<bool>::Interm::Remove()
{
    for (int i = 0; i < master->len; i++)
        if (i == index) {
            for (int j = i; j < master->len - 1; j++)
                master->array[j] = master->array[j+1];
            master->array[master->len - 1] = master->defval;
            break;
        }
}

int SparseArray<bool>::Interm::operator=(const int &x)
{
    if (x == master->defval)
        Remove();
    else
        Provide() = x;
    return x;
}

SparseArray<bool>::Interm::operator int() const
{
    for (int i = 0; i < master->len; i++)
        if (i == index)
            return master->array[i];
    return master->defval;
}

#endif
Section test03c (10-07)In catalog
MakefileMake / 20 lines
MODULES = sparse

SRCMODULES = $(wildcard $(MODULES:=.cpp))
HEADERS = $(wildcard $(MODULES:=.hpp))
OBJMODULES = $(SRCMODULES:.cpp=.o)

PROGRAMS = main

CXXFLAGS = -g -Wall -ansi -pedantic -Wno-long-long -fwrapv

all: $(PROGRAMS)

%.o: %.cpp $(HEADERS)
    $(CXX) $(CXXFLAGS) -c $< -o $@

$(PROGRAMS): %: %.cpp $(OBJMODULES) $(HEADERS)
    $(CXX) $(CXXFLAGS) $(filter-out %.hpp,$^) $(LDLIBS) -o $@

clean:
    rm -f *.o $(PROGRAMS)
main.cppC++ / 56 lines
#include <stdio.h>

#include "sparse.hpp"

void show(const char *what, const SparseArray<bool>& c)
{
    printf("%-18s %d %d %d %d   (stored: %d)\n", what, c[0], c[1], c[5],
           c[1000000], c.NonzeroCount());
}

void test_default_false()
{
    SparseArray<bool> b(false);
    show("empty:", b);
    b[5] = true;
    b[1000000] = true;
    b[1] = 25;                          /* any nonzero number is true */
    show("three set:", b);
    b[1] = false;
    show("b[1] = false:", b);
    b[0] = b[5];
    show("b[0] = b[5]:", b);
    b[5] = true;                        /* already there: no duplicate */
    show("b[5] = true again:", b);
}

void test_default_true()
{
    SparseArray<bool> t(true);
    t[5] = false;
    show("default true:", t);
}

void test_growth()
{
    SparseArray<bool> b(false);
    int i, count = 0;
    for (i = 0; i < 1000; i++)
        b[3 * i] = true;
    for (i = 0; i < 3000; i++)
        if (b[i])
            count++;
    printf("%-18s %d of 3000   (stored: %d)\n", "every third:", count,
           b.NonzeroCount());
}

int main()
{
    SparseArray<int> a(0);              /* the general template still works */
    test_default_false();
    test_default_true();
    test_growth();
    a[7] = 42;
    printf("%-18s %d\n", "SparseArray<int>:", (int) a[7]);
    return 0;
}
sparse.hppC++ / 398 lines
#ifndef SPARSE_HPP
#define SPARSE_HPP

class NullElement {
    int index;
public:
    NullElement(int idx) : index(idx) {}
    int Index() const { return index; }
};

template <class T>
class SparseArray {
    struct Item {
        int index;
        T value;
        Item *next;
    };
    Item *first;
    T defval;
public:
    SparseArray(const T &dv) : first(0), defval(dv) {}
    ~SparseArray();
    class Interm {
        friend class SparseArray<T>;
        SparseArray<T> *master;
        int index;
        Interm(SparseArray<T> *a_master, int ind)
            : master(a_master), index(ind) {}
        T& Provide();
        void Remove();
    public:
        operator T() const;
        T operator=(const T& x);
        T operator=(const Interm& x);

        T operator+=(const T& x);
        T operator-=(const T& x);
        T operator*=(const T& x);
        T operator/=(const T& x);
        T operator%=(const T& x);

        T operator<<=(int n);
        T operator>>=(int n);

        T operator|=(const T& x);
        T operator&=(const T& x);
        T operator^=(const T& x);

        T operator++();
        T operator++(int);
        T operator--();
        T operator--(int);

        T operator->() const;
    };
    friend class Interm;

    Interm operator[](int idx) { return Interm(this, idx); }
    const T& operator[](int idx) const;

    int NonzeroCount() const;
private:
    SparseArray(const SparseArray<T>&) {}
    void operator=(const SparseArray<T>&) {}
};

template <class T>
SparseArray<T>::~SparseArray()
{
    while (first) {
        Item *tmp = first;
        first = first->next;
        delete tmp;
    }
}

template <class T>
const T& SparseArray<T>::operator[](int idx) const
{
    Item *tmp;
    for (tmp = first; tmp; tmp = tmp->next)
        if (tmp->index == idx)
            return tmp->value;
    return defval;
}

template <class T>
int SparseArray<T>::NonzeroCount() const
{
    int sum = 0;
    for (Item *tmp = first; tmp; tmp = tmp->next)
        sum++;
    return sum;
}

template <class T>
T& SparseArray<T>::Interm::Provide()
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    tmp = new Item;
    tmp->index = index;
    tmp->value = master->defval;
    tmp->next = master->first;
    master->first = tmp;
    return tmp->value;
}

template<class T>
void SparseArray<T>::Interm::Remove()
{
    Item **tmp;
    for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
        if ((*tmp)->index == index) {
            Item *to_delete = *tmp;
            *tmp = (*tmp)->next;
            delete to_delete;
            return;
        }
}

template <class T>
T SparseArray<T>::Interm::operator=(const T &x)
{
    if (x == master->defval)
        Remove();
    else
        Provide() = x;
    return x;
}

template <class T>
T SparseArray<T>::Interm::operator=(const Interm& x)
{
    T value = x;
    return *this = value;
}

template <class T>
T SparseArray<T>::Interm::operator+=(const T& x)
{
    T& location = Provide();
    location += x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator-=(const T& x)
{
    T& location = Provide();
    location -= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator*=(const T& x)
{
    T& location = Provide();
    location *= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator/=(const T& x)
{
    T& location = Provide();
    location /= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator%=(const T& x)
{
    T& location = Provide();
    location %= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator<<=(int n)
{
    T& location = Provide();
    location <<= n;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator>>=(int n)
{
    T& location = Provide();
    location >>= n;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator|=(const T& x)
{
    T& location = Provide();
    location |= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator&=(const T& x)
{
    T& location = Provide();
    location &= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator^=(const T& x)
{
    T& location = Provide();
    location ^= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator++()
{
    T& location = Provide();
    ++location;
    T res = location;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator++(int)
{
    T& location = Provide();
    T res = location;
    location++;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator--()
{
    T& location = Provide();
    --location;
    T res = location;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator--(int)
{
    T& location = Provide();
    T res = location;
    location--;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator->() const
{
    T p = *this;
    if (!p)
        throw NullElement(index);
    return p;
}

template <class T>
SparseArray<T>::Interm::operator T() const
{
    Item *tmp;
    for (tmp = master->first; tmp; tmp = tmp->next)
        if (tmp->index == index)
            return tmp->value;
    return master->defval;
}

template <>
class SparseArray<bool> {
    int *indices;
    int len, capacity;
    bool defval;
    int Find(int idx) const;
    void Add(int idx);
    void Remove(int idx);
    bool Get(int idx) const;
    void Set(int idx, bool x);
public:
    SparseArray(const bool &dv)
        : indices(0), len(0), capacity(0), defval(dv) {}
    ~SparseArray() { delete[] indices; }
    class Interm {
        friend class SparseArray<bool>;
        SparseArray<bool> *master;
        int index;
        Interm(SparseArray<bool> *a_master, int ind)
            : master(a_master), index(ind) {}
    public:
        operator bool() const { return master->Get(index); }
        bool operator=(bool x) { master->Set(index, x); return x; }
        bool operator=(const Interm& x) { return *this = bool(x); }
    };
    friend class Interm;

    Interm operator[](int idx) { return Interm(this, idx); }
    bool operator[](int idx) const { return Get(idx); }

    int NonzeroCount() const { return len; }
private:
    SparseArray(const SparseArray<bool>&) {}
    void operator=(const SparseArray<bool>&) {}
};

inline int SparseArray<bool>::Find(int idx) const
{
    for (int i = 0; i < len; i++)
        if (indices[i] == idx)
            return i;
    return -1;
}

inline void SparseArray<bool>::Add(int idx)
{
    if (Find(idx) != -1)
        return;
    if (len == capacity) {
        int new_capacity = capacity ? 2 * capacity : 16;
        int *new_indices = new int[new_capacity];
        for (int i = 0; i < len; i++)
            new_indices[i] = indices[i];
        delete[] indices;
        indices = new_indices;
        capacity = new_capacity;
    }
    indices[len] = idx;
    len++;
}

inline void SparseArray<bool>::Remove(int idx)
{
    int pos = Find(idx);
    if (pos == -1)
        return;
    indices[pos] = indices[len - 1];
    len--;
}

inline bool SparseArray<bool>::Get(int idx) const
{
    bool stored = Find(idx) != -1;
    return stored ? !defval : defval;
}

inline void SparseArray<bool>::Set(int idx, bool x)
{
    if (x == defval)
        Remove(idx);
    else
        Add(idx);
}

#endif
Section test03d (10-07)In catalog
MakefileMake / 20 lines
MODULES = sparse

SRCMODULES = $(wildcard $(MODULES:=.cpp))
HEADERS = $(wildcard $(MODULES:=.hpp))
OBJMODULES = $(SRCMODULES:.cpp=.o)

PROGRAMS = main

CXXFLAGS = -g -Wall -ansi -pedantic -Wno-long-long -fwrapv

all: $(PROGRAMS)

%.o: %.cpp $(HEADERS)
    $(CXX) $(CXXFLAGS) -c $< -o $@

$(PROGRAMS): %: %.cpp $(OBJMODULES) $(HEADERS)
    $(CXX) $(CXXFLAGS) $(filter-out %.hpp,$^) $(LDLIBS) -o $@

clean:
    rm -f *.o $(PROGRAMS)
main.cppC++ / 56 lines
#include <stdio.h>

#include "sparse.hpp"

void show(const char *what, const SparseArray<bool>& c)
{
    printf("%-18s %d %d %d %d   (stored: %d)\n", what, c[0], c[1], c[5],
           c[1000000], c.NonzeroCount());
}

void test_default_false()
{
    SparseArray<bool> b(false);
    show("empty:", b);
    b[5] = true;
    b[1000000] = true;
    b[1] = 25;                          /* any nonzero number is true */
    show("three set:", b);
    b[1] = false;
    show("b[1] = false:", b);
    b[0] = b[5];
    show("b[0] = b[5]:", b);
    b[5] = true;                        /* already there: no duplicate */
    show("b[5] = true again:", b);
}

void test_default_true()
{
    SparseArray<bool> t(true);
    t[5] = false;
    show("default true:", t);
}

void test_growth()
{
    SparseArray<bool> b(false);
    int i, count = 0;
    for (i = 0; i < 1000; i++)
        b[3 * i] = true;
    for (i = 0; i < 3000; i++)
        if (b[i])
            count++;
    printf("%-18s %d of 3000   (stored: %d)\n", "every third:", count,
           b.NonzeroCount());
}

int main()
{
    SparseArray<int> a(0);              /* the general template still works */
    test_default_false();
    test_default_true();
    test_growth();
    a[7] = 42;
    printf("%-18s %d\n", "SparseArray<int>:", (int) a[7]);
    return 0;
}
sparse.hppC++ / 413 lines
#ifndef SPARSE_HPP
#define SPARSE_HPP

class NullElement {
    int index;
public:
    NullElement(int idx) : index(idx) {}
    int Index() const { return index; }
};

template <class T>
class SparseArray {
    struct Item {
        int index;
        T value;
        Item *next;
    };
    Item *first;
    T defval;
    T *Find(int idx) const;             /* the stored value, or 0 */
public:
    SparseArray(const T &dv) : first(0), defval(dv) {}
    ~SparseArray();
    class Interm {
        friend class SparseArray<T>;
        SparseArray<T> *master;
        int index;
        Interm(SparseArray<T> *a_master, int ind)
            : master(a_master), index(ind) {}
        T& Push();
        T& Provide();
        void Remove();
    public:
        operator T() const;
        T operator=(const T& x);
        T operator=(const Interm& x);

        T operator+=(const T& x);
        T operator-=(const T& x);
        T operator*=(const T& x);
        T operator/=(const T& x);
        T operator%=(const T& x);

        T operator<<=(int n);
        T operator>>=(int n);

        T operator|=(const T& x);
        T operator&=(const T& x);
        T operator^=(const T& x);

        T operator++();
        T operator++(int);
        T operator--();
        T operator--(int);

        T operator->() const;
    };
    friend class Interm;

    Interm operator[](int idx) { return Interm(this, idx); }
    const T& operator[](int idx) const;

    int NonzeroCount() const;
private:
    SparseArray(const SparseArray<T>&) {}
    void operator=(const SparseArray<T>&) {}
};

template <class T>
T *SparseArray<T>::Find(int idx) const
{
    Item *tmp;
    for (tmp = first; tmp; tmp = tmp->next)
        if (tmp->index == idx)
            return &tmp->value;
    return 0;
}

template <class T>
const T& SparseArray<T>::operator[](int idx) const
{
    T *found = Find(idx);
    if (found)
        return *found;
    return defval;
}

template <class T>
SparseArray<T>::~SparseArray()
{
    while (first) {
        Item *tmp = first;
        first = first->next;
        delete tmp;
    }
}

template <class T>
int SparseArray<T>::NonzeroCount() const
{
    int sum = 0;
    for (Item *tmp = first; tmp; tmp = tmp->next)
        sum++;
    return sum;
}

template <class T>
T& SparseArray<T>::Interm::Push()
{
    Item *tmp = new Item;
    tmp->index = index;
    tmp->value = master->defval;
    tmp->next = master->first;
    master->first = tmp;
    return tmp->value;
}

template <class T>
T& SparseArray<T>::Interm::Provide()
{
    T *found = master->Find(index);
    if (found)
        return *found;
    return Push();
}

template<class T>
void SparseArray<T>::Interm::Remove()
{
    Item **tmp;
    for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
        if ((*tmp)->index == index) {
            Item *to_delete = *tmp;
            *tmp = (*tmp)->next;
            delete to_delete;
            return;
        }
}

template <class T>
T SparseArray<T>::Interm::operator=(const T &x)
{
    if (x == master->defval)
        Remove();
    else
        Provide() = x;
    return x;
}

template <class T>
T SparseArray<T>::Interm::operator=(const Interm& x)
{
    T value = x;
    return *this = value;
}

template <class T>
T SparseArray<T>::Interm::operator+=(const T& x)
{
    T& location = Provide();
    location += x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator-=(const T& x)
{
    T& location = Provide();
    location -= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator*=(const T& x)
{
    T& location = Provide();
    location *= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator/=(const T& x)
{
    T& location = Provide();
    location /= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator%=(const T& x)
{
    T& location = Provide();
    location %= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator<<=(int n)
{
    T& location = Provide();
    location <<= n;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator>>=(int n)
{
    T& location = Provide();
    location >>= n;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator|=(const T& x)
{
    T& location = Provide();
    location |= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator&=(const T& x)
{
    T& location = Provide();
    location &= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator^=(const T& x)
{
    T& location = Provide();
    location ^= x;
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator++()
{
    T& location = Provide();
    ++location;
    T res = location;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator++(int)
{
    T& location = Provide();
    T res = location;
    location++;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator--()
{
    T& location = Provide();
    --location;
    T res = location;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator--(int)
{
    T& location = Provide();
    T res = location;
    location--;
    if (location == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator->() const
{
    T p = *this;
    if (!p)
        throw NullElement(index);
    return p;
}

template <class T>
SparseArray<T>::Interm::operator T() const
{
    T *found = master->Find(index);
    if (found)
        return *found;
    return master->defval;
}

template <>
class SparseArray<bool> {
    int *indices;
    int len, capacity;
    bool defval;
    int Find(int idx) const;
    void Add(int idx);
    void Remove(int idx);
    bool Get(int idx) const;
    void Set(int idx, bool x);
public:
    SparseArray(const bool &dv)
        : indices(0), len(0), capacity(0), defval(dv) {}
    ~SparseArray() { delete[] indices; }
    class Interm {
        friend class SparseArray<bool>;
        SparseArray<bool> *master;
        int index;
        Interm(SparseArray<bool> *a_master, int ind)
            : master(a_master), index(ind) {}
    public:
        operator bool() const { return master->Get(index); }
        bool operator=(bool x) { master->Set(index, x); return x; }
        bool operator=(const Interm& x) { return *this = bool(x); }
    };
    friend class Interm;

    Interm operator[](int idx) { return Interm(this, idx); }
    bool operator[](int idx) const { return Get(idx); }

    int NonzeroCount() const { return len; }
private:
    SparseArray(const SparseArray<bool>&) {}
    void operator=(const SparseArray<bool>&) {}
};

inline int SparseArray<bool>::Find(int idx) const
{
    for (int i = 0; i < len; i++)
        if (indices[i] == idx)
            return i;
    return -1;
}

inline void SparseArray<bool>::Add(int idx)
{
    if (Find(idx) != -1)
        return;
    if (len == capacity) {
        int new_capacity = capacity ? 2 * capacity : 16;
        int *new_indices = new int[new_capacity];
        for (int i = 0; i < len; i++)
            new_indices[i] = indices[i];
        delete[] indices;
        indices = new_indices;
        capacity = new_capacity;
    }
    indices[len] = idx;
    len++;
}

inline void SparseArray<bool>::Remove(int idx)
{
    int pos = Find(idx);
    if (pos == -1)
        return;
    indices[pos] = indices[len - 1];
    len--;
}

inline bool SparseArray<bool>::Get(int idx) const
{
    bool stored = Find(idx) != -1;
    return stored ? !defval : defval;
}

inline void SparseArray<bool>::Set(int idx, bool x)
{
    if (x == defval)
        Remove(idx);
    else
        Add(idx);
}

#endif
Section test03e (10-07)In catalog
MakefileMake / 20 lines
MODULES = sparse

SRCMODULES = $(wildcard $(MODULES:=.cpp))
HEADERS = $(wildcard $(MODULES:=.hpp))
OBJMODULES = $(SRCMODULES:.cpp=.o)

PROGRAMS = main

CXXFLAGS = -g -Wall -ansi -pedantic -Wno-long-long -fwrapv

all: $(PROGRAMS)

%.o: %.cpp $(HEADERS)
    $(CXX) $(CXXFLAGS) -c $< -o $@

$(PROGRAMS): %: %.cpp $(OBJMODULES) $(HEADERS)
    $(CXX) $(CXXFLAGS) $(filter-out %.hpp,$^) $(LDLIBS) -o $@

clean:
    rm -f *.o $(PROGRAMS)
main.cppC++ / 295 lines
#include <stdio.h>

#include "sparse.hpp"

static int checks = 0, failures = 0;

bool check(bool ok, const char *msg)
{
    checks++;
    if (!ok) {
        fprintf(stderr, "wrong %s\n", msg);
        failures++;
    }
    return ok;
}

void check_int(long got, long want, const char *msg)
{
    if (!check(got == want, msg))
        fprintf(stderr, "    got %ld, want %ld\n", got, want);
}

void test_assignment()
{
    SparseArray<int> a(0);
    check_int(a[5], 0, "missing element is the default");
    check_int(a.NonzeroCount(), 0, "empty array stores nothing");
    a[5] = 10;
    a[-3] = 20;
    a[1000000] = 30;
    check_int(a[5], 10, "assigned element");
    check_int(a[-3], 20, "negative index");
    check_int(a[1000000], 30, "large index");
    check_int(a.NonzeroCount(), 3, "count after three assignments");
    a[5] = 11;
    check_int(a[5], 11, "overwritten element");
    check_int(a.NonzeroCount(), 3, "overwriting adds nothing");
    a[5] = 0;
    check_int(a[5], 0, "element assigned the default");
    check_int(a.NonzeroCount(), 2, "assigning the default removes");
    a[77] = 0;
    check_int(a.NonzeroCount(), 2, "default to a missing element");
    check_int(a[8] = 9, 9, "value of an assignment");
}

void test_element_to_element()
{
    SparseArray<int> a(0);
    a[1] = 10;
    a[2] = 20;
    a[1] = a[2];
    check_int(a[1], 20, "a[1] = a[2]");
    a[3] = a[9];
    check_int(a.NonzeroCount(), 2, "a[3] = missing stores nothing");
    a[2] = a[9];
    check_int(a.NonzeroCount(), 1, "a[2] = missing removes a[2]");
    a[1] = a[1];
    check_int(a[1], 20, "a[1] = a[1]");
    a[4] = a[5] = 7;
    check_int(a[4] + a[5], 14, "a[4] = a[5] = 7");
}

/* every operator generated by SPARSE_ASSIGN, on the same start value */
void test_assign_operators()
{
    SparseArray<int> a(0);
    int i;
    for (i = 0; i < 10; i++)
        a[i] = 12;
    check_int(a[0] += 5, 17, "+=");
    check_int(a[1] -= 5, 7, "-=");
    check_int(a[2] *= 5, 60, "*=");
    check_int(a[3] /= 5, 2, "/=");
    check_int(a[4] %= 5, 2, "%=");
    check_int(a[5] |= 3, 15, "|=");
    check_int(a[6] &= 5, 4, "&=");
    check_int(a[7] ^= 5, 9, "^=");
    check_int(a[8] <<= 2, 48, "<<=");
    check_int(a[9] >>= 2, 3, ">>=");
    check_int(a[0] + a[1] + a[2] + a[3] + a[4], 88, "stored: first five");
    check_int(a[5] + a[6] + a[7] + a[8] + a[9], 79, "stored: last five");
}

/* an operator whose result is the default must remove the element */
void test_operators_remove()
{
    SparseArray<int> a(0);
    int i;
    for (i = 0; i < 8; i++)
        a[i] = 12;
    a[0] += -12;
    a[1] -= 12;
    a[2] *= 0;
    a[3] /= 13;
    a[4] %= 12;
    a[5] &= 3;
    a[6] ^= 12;
    a[7] >>= 4;
    check_int(a.NonzeroCount(), 0, "results equal to the default");
    a[9] += 5;
    check_int(a[9], 5, "+= on a missing element");
    a[8] += 0;
    check_int(a.NonzeroCount(), 1, "+= 0 on a missing element");
    a[9] += a[9];
    check_int(a[9], 10, "a[9] += a[9]");
    a[9] -= a[9];
    check_int(a.NonzeroCount(), 0, "a[9] -= a[9]");
}

/* the operators generated by SPARSE_STEP */
void test_steps()
{
    SparseArray<int> a(0);
    a[1] = 5;
    check_int(++a[1], 6, "prefix ++ gives the new value");
    check_int(a[1]++, 6, "postfix ++ gives the old value");
    check_int(a[1], 7, "after two increments");
    check_int(--a[1], 6, "prefix -- gives the new value");
    check_int(a[1]--, 6, "postfix -- gives the old value");
    check_int(a[1], 5, "after two decrements");
    check_int(a[2]++, 0, "postfix ++ on a missing element");
    check_int(a[2], 1, "missing element after ++");
    a[2]--;
    check_int(a.NonzeroCount(), 1, "-- down to the default removes");
    a[3] = -1;
    ++a[3];
    check_int(a.NonzeroCount(), 1, "++ up to the default removes");
}

void test_nonzero_default()
{
    SparseArray<int> a(100);
    check_int(a[5], 100, "missing element, default 100");
    a[5] += 1;
    check_int(a[5], 101, "+= starts from the default");
    a[6] = 0;
    check_int(a.NonzeroCount(), 2, "zero is stored when default is 100");
    a[5]--;
    a[6] = 100;
    check_int(a.NonzeroCount(), 0, "back to the default");
}

void test_const_reference()
{
    SparseArray<int> a(0);
    const SparseArray<int>& c = a;
    int i, sum = 0;
    a[1] = 10;
    a[3] = 30;
    for (i = 0; i < 100; i++)
        sum += c[i];
    check_int(sum, 40, "sum through a const reference");
    check_int(a.NonzeroCount(), 2, "reading creates nothing");
    check(&c[1] == &c[1], "same object for an existing element");
    check(&c[2] == &c[99], "one object for all missing elements");
    check(&c[1] != &c[3], "different objects for different elements");
    const int& r = c[3];
    a[3] = 31;
    check_int(r, 31, "a reference follows its element");
}

void test_double()
{
    SparseArray<double> d(0.5);
    d[1] = 2.0;
    d[1] *= 4;
    d[2] += 1.5;
    d[3] = 0.5;
    check(d[1] == 8.0, "double: *=");
    check(d[2] == 2.0, "double: += from the default");
    check(d[9] == 0.5, "double: missing element");
    check_int(d.NonzeroCount(), 2, "double: count");
    d[2] -= 1.5;
    check_int(d.NonzeroCount(), 1, "double: back to the default");
}

class Money {                   /* has ==, =, copying; nothing else */
    long cents;
public:
    Money(long a_cents = 0) : cents(a_cents) {}
    long Cents() const { return cents; }
    bool operator==(const Money& other) const { return cents == other.cents; }
};

void test_class_element()
{
    SparseArray<Money> m(Money(0));
    const SparseArray<Money>& c = m;
    m[1] = Money(250);
    m[2] = Money(999);
    m[2] = Money(0);
    check_int(c[1].Cents(), 250, "class: stored element");
    check_int(c[2].Cents(), 0, "class: removed element");
    check_int(Money(m[1]).Cents(), 250, "class: conversion to a copy");
    check_int(m.NonzeroCount(), 1, "class: count");
    m[3] = m[1];
    check_int(c[3].Cents(), 250, "class: element to element");
}

struct Point {
    int x, y;
};

void test_pointers()
{
    Point p = { 3, 4 };
    SparseArray<Point*> s(0);
    bool thrown = false;
    s[1] = &p;
    check_int(s[1]->x + s[1]->y, 7, "pointers: reading through ->");
    s[1]->x = 30;
    check_int(p.x, 30, "pointers: changing through ->");
    try {
        s[9]->x = 1;
    }
    catch (const NullElement& ex) {
        thrown = ex.Index() == 9;
    }
    check(thrown, "pointers: NullElement for a missing element");
    check_int(s.NonzeroCount(), 1, "pointers: -> creates nothing");
}

void test_bool()
{
    SparseArray<bool> b(false), t(true);
    const SparseArray<bool>& c = b;
    b[5] = true;
    b[1000000] = true;
    b[1] = 25;
    check(c[5] && c[1000000] && c[1], "bool: elements set");
    check(!c[0] && !c[6], "bool: missing elements are false");
    check_int(c[1], 1, "bool: 25 is stored as true");
    b[5] = true;
    check_int(b.NonzeroCount(), 3, "bool: no duplicate index");
    b[1] = false;
    check_int(b.NonzeroCount(), 2, "bool: false removes");
    b[0] = b[5];
    check(c[0], "bool: element to element");
    t[5] = false;
    check(!t[5] && t[4], "bool: default true");
    check_int(t.NonzeroCount(), 1, "bool: false stored, default true");
}

template <class T>
int count_set(SparseArray<T>& a, int n)
{
    int i, count = 0;
    for (i = 0; i < n; i++)
        if (a[i])
            count++;
    return count;
}

void test_many()
{
    SparseArray<int> a(0);
    SparseArray<bool> b(false);
    int i;
    for (i = 0; i < 1000; i++) {
        a[3 * i] = i + 1;
        b[3 * i] = true;
    }
    check_int(a.NonzeroCount(), 1000, "many: int count");
    check_int(b.NonzeroCount(), 1000, "many: bool count");
    check_int(count_set(a, 3000), 1000, "many: int values");
    check_int(count_set(b, 3000), 1000, "many: bool values");
    for (i = 0; i < 1000; i += 2) {
        a[3 * i] = 0;
        b[3 * i] = false;
    }
    check_int(a.NonzeroCount(), 500, "many: int count after removal");
    check_int(b.NonzeroCount(), 500, "many: bool count after removal");
    check_int(a[3 * 999], 1000, "many: last element intact");
}

int main()
{
    test_assignment();
    test_element_to_element();
    test_assign_operators();
    test_operators_remove();
    test_steps();
    test_nonzero_default();
    test_const_reference();
    test_double();
    test_class_element();
    test_pointers();
    test_bool();
    test_many();
    if (failures)
        fprintf(stderr, "%d of %d checks failed\n", failures, checks);
    else
        printf("all %d checks passed\n", checks);
    return failures != 0;
}
sparse.hppC++ / 275 lines
#ifndef SPARSE_HPP
#define SPARSE_HPP

class NullElement {
    int index;
public:
    NullElement(int idx) : index(idx) {}
    int Index() const { return index; }
};

#define SPARSE_ASSIGN(OP, ARG)                                          \
        T operator OP(ARG x) { T& v = Provide(); v OP x; return Finish(v); }

#define SPARSE_STEP(OP)                                                 \
        T operator OP() { T& v = Provide(); OP v; return Finish(v); }   \
        T operator OP(int)                                              \
            { T& v = Provide(); T old = v; v OP; Finish(v); return old; }

template <class T>
class SparseArray {
    struct Item {
        int index;
        T value;
        Item *next;
    };
    Item *first;
    T defval;
    T *Find(int idx) const;
public:
    SparseArray(const T &dv) : first(0), defval(dv) {}
    ~SparseArray();
    class Interm {
        friend class SparseArray<T>;
        SparseArray<T> *master;
        int index;
        Interm(SparseArray<T> *a_master, int ind)
            : master(a_master), index(ind) {}
        T& Push();
        T& Provide();
        void Remove();
        T Finish(T& location);
    public:
        operator T() const;
        T operator=(const T& x);
        T operator=(const Interm& x);

        SPARSE_ASSIGN(+=, const T&)
        SPARSE_ASSIGN(-=, const T&)
        SPARSE_ASSIGN(*=, const T&)
        SPARSE_ASSIGN(/=, const T&)
        SPARSE_ASSIGN(%=, const T&)
        SPARSE_ASSIGN(|=, const T&)
        SPARSE_ASSIGN(&=, const T&)
        SPARSE_ASSIGN(^=, const T&)
        SPARSE_ASSIGN(<<=, int)
        SPARSE_ASSIGN(>>=, int)
        SPARSE_STEP(++)
        SPARSE_STEP(--)

        T operator->() const;
    };
    friend class Interm;

    Interm operator[](int idx) { return Interm(this, idx); }
    const T& operator[](int idx) const;

    int NonzeroCount() const;
private:
    SparseArray(const SparseArray<T>&) {}
    void operator=(const SparseArray<T>&) {}
};

#undef SPARSE_ASSIGN
#undef SPARSE_STEP

template <class T>
T *SparseArray<T>::Find(int idx) const
{
    Item *tmp;
    for (tmp = first; tmp; tmp = tmp->next)
        if (tmp->index == idx)
            return &tmp->value;
    return 0;
}

template <class T>
const T& SparseArray<T>::operator[](int idx) const
{
    T *found = Find(idx);
    if (found)
        return *found;
    return defval;
}

template <class T>
SparseArray<T>::~SparseArray()
{
    while (first) {
        Item *tmp = first;
        first = first->next;
        delete tmp;
    }
}

template <class T>
int SparseArray<T>::NonzeroCount() const
{
    int sum = 0;
    for (Item *tmp = first; tmp; tmp = tmp->next)
        sum++;
    return sum;
}

template <class T>
T& SparseArray<T>::Interm::Push()
{
    Item *tmp = new Item;
    tmp->index = index;
    tmp->value = master->defval;
    tmp->next = master->first;
    master->first = tmp;
    return tmp->value;
}

template <class T>
T& SparseArray<T>::Interm::Provide()
{
    T *found = master->Find(index);
    if (found)
        return *found;
    return Push();
}

template<class T>
void SparseArray<T>::Interm::Remove()
{
    Item **tmp;
    for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
        if ((*tmp)->index == index) {
            Item *to_delete = *tmp;
            *tmp = (*tmp)->next;
            delete to_delete;
            return;
        }
}

template <class T>
SparseArray<T>::Interm::operator T() const
{
    T *found = master->Find(index);
    if (found)
        return *found;
    return master->defval;
}

template <class T>
T SparseArray<T>::Interm::operator=(const T &x)
{
    if (x == master->defval)
        Remove();
    else
        Provide() = x;
    return x;
}

template <class T>
T SparseArray<T>::Interm::operator=(const Interm& x)
{
    T value = x;
    return *this = value;
}

template <class T>
T SparseArray<T>::Interm::Finish(T& location)
{
    T res = location;
    if (res == master->defval)
        Remove();
    return res;
}

template <class T>
T SparseArray<T>::Interm::operator->() const
{
    T p = *this;
    if (!p)
        throw NullElement(index);
    return p;
}

template <>
class SparseArray<bool> {
    int *indices;
    int len, capacity;
    bool defval;
    int Find(int idx) const;
    void Add(int idx);
    void Remove(int idx);
    bool Get(int idx) const;
    void Set(int idx, bool x);
public:
    SparseArray(const bool &dv)
        : indices(0), len(0), capacity(0), defval(dv) {}
    ~SparseArray() { delete[] indices; }
    class Interm {
        friend class SparseArray<bool>;
        SparseArray<bool> *master;
        int index;
        Interm(SparseArray<bool> *a_master, int ind)
            : master(a_master), index(ind) {}
    public:
        operator bool() const { return master->Get(index); }
        bool operator=(bool x) { master->Set(index, x); return x; }
        bool operator=(const Interm& x) { return *this = bool(x); }
    };
    friend class Interm;

    Interm operator[](int idx) { return Interm(this, idx); }
    bool operator[](int idx) const { return Get(idx); }

    int NonzeroCount() const { return len; }
private:
    SparseArray(const SparseArray<bool>&) {}
    void operator=(const SparseArray<bool>&) {}
};

inline int SparseArray<bool>::Find(int idx) const
{
    for (int i = 0; i < len; i++)
        if (indices[i] == idx)
            return i;
    return -1;
}

inline void SparseArray<bool>::Add(int idx)
{
    if (Find(idx) != -1)
        return;
    if (len == capacity) {
        int new_capacity = capacity ? 2 * capacity : 16;
        int *new_indices = new int[new_capacity];
        for (int i = 0; i < len; i++)
            new_indices[i] = indices[i];
        delete[] indices;
        indices = new_indices;
        capacity = new_capacity;
    }
    indices[len] = idx;
    len++;
}

inline void SparseArray<bool>::Remove(int idx)
{
    int pos = Find(idx);
    if (pos == -1)
        return;
    indices[pos] = indices[len - 1];
    len--;
}

inline bool SparseArray<bool>::Get(int idx) const
{
    bool stored = Find(idx) != -1;
    return stored ? !defval : defval;
}

inline void SparseArray<bool>::Set(int idx, bool x)
{
    if (x == defval)
        Remove(idx);
    else
        Add(idx);
}

#endif
Section test03f-specialization (10-07)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
functions.cppC++ / 28 lines
#include <stdio.h>

template <class T>
void f(T)                               /* A: the general template */
{
    printf("A: f(T)\n");
}

/* changing order of S and B results in different behaviour */

template <>
void f(int*)                            /* S: special case for int* */
{
    printf("S: special case\n");
}

template <class T>
void f(T*)                              /* B: an overload for pointers */
{
    printf("B: f(T*)\n");
}

int main()
{
    int n = 0;
    f<int>(&n);
    return 0;
}
functions01.cppC++ / 28 lines
#include <stdio.h>
#include <string.h>

template <class T>
bool less(T a, T b)                     /* A: anything */
{
    return a < b;
}

template <class T>
bool less(T *a, T *b)                   /* B: pointers, compare targets */
{
    return *a < *b;
}

template <>
bool less(const char *a, const char *b) /* S: strings, by strcmp */
{
    return strcmp(a, b) < 0;
}


int main()
{
    const char *x = "apple", *y = "apricot";
    printf("%d\n", less(x, y));
    return 0;
}
pointer.cppC++ / 39 lines
#include <stdio.h>

template <class Z>
class Foo {                             /* the general version */
    Z value;
public:
    Foo(Z v) : value(v) {}
    Z Get() const { return value; }
    const char *Which() const { return "general"; }
};

template <class T>
class Foo<T*> {                         /* for any pointer type */
    T *ptr;
public:
    Foo(T *p) : ptr(p) {}
    T Get() const { return *ptr; }      /* T is what it points to */
    const char *Which() const { return "for pointers"; }
    unsigned long TargetSize() const { return sizeof(T); }
};

int main()
{
    int n = 5;
    double d = 2.5;
    int *pn = &n;
    Foo<int> a(n);
    Foo<int*> b(&n);
    Foo<double*> c(&d);
    Foo<int**> e(&pn);
    printf("Foo<int>:     %-13s Get() = %d\n", a.Which(), a.Get());
    printf("Foo<int*>:    %-13s Get() = %d, T is %lu bytes\n",
           b.Which(), b.Get(), b.TargetSize());
    printf("Foo<double*>: %-13s Get() = %g, T is %lu bytes\n",
           c.Which(), c.Get(), c.TargetSize());
    printf("Foo<int**>:   %-13s *Get() = %d, T is %lu bytes\n",
           e.Which(), *e.Get(), e.TargetSize());
    return 0;
}
pointer01.cppC++ / 32 lines
#include <stdio.h>

template <class T>
class Foo {
    T value;
public:
    Foo(T v) : value(v) {}
    T Get() const { return value; }
    const char *Which() const { return "general"; }
};

template <class T>
class Foo<T*> {
    T *ptr;
public:
    Foo(T *p) : ptr(p) {}
    T Get() const { return *ptr; }
    const char *Which() const { return "for pointers"; }
    unsigned long TargetSize() const { return sizeof(T); }
};

int main()
{
    int n = 5;
    Foo<int> a(n);
    Foo<int*> b(&n);

    printf("Foo<int>: %s %d\n", a.Which(), a.Get());
    printf("Foo<int*>: %s %d %lu\n", b.Which(), b.Get(), b.TargetSize());

    return 0;
}
sort_less00.cppC++ / 63 lines
#include <stdio.h>

template <class T>
inline void swap(T &x, T &y)
{
    T tmp = x;
    x = y;
    y = tmp;
}

template <class Z>
struct Less {
    static bool Check(Z a, Z b) { return a < b; }
};

template <class T>
struct Less<T*> {
    static bool Check(T *a, T *b) { return *a < *b; }
};

template <class T>
void sort(T *array, int len)
{
    for (int start = 0; ; start++) {
        bool done = true;
        for (int i = len - 2; i >= start; i--)
            if (Less<T>::Check(array[i + 1], array[i])) {
                swap(array[i], array[i+1]);
                done = false;
            }
        if (done)
            break;
    }
}

void print(const int *array, int len)
{
    for (int i = 0; i < len; i++)
        printf("%d ", array[i]);
    printf("\n");
}

int main()
{
    int values[] = { 30, 10, 40, 20 };
    int len = sizeof(values) / sizeof(*values);
    int *pointers[4];
    for (int i = 0; i < len; i++)
        pointers[i] = &values[i];

    sort(pointers, len);
    for (int i = 0; i < len; i++)
        printf("%d ", *pointers[i]);
    printf("\n");

    printf("values untouched: ");
    print(values, len);

    sort(values, len);
    print(values, len);

    return 0;
}
sort_less01.cppC++ / 63 lines
#include <stdio.h>

template <class T>
inline void swap(T &x, T &y)
{
    T tmp = x;
    x = y;
    y = tmp;
}

template <class T>
bool less(T a, T b)                     /* anything: compare the values */
{
    return a < b;
}

template <class T>
bool less(T *a, T *b)                   /* pointers: compare the targets */
{
    return *a < *b;
}

template <class T>
void sort(T *array, int len)
{
    for (int start = 0; ; start++) {
        bool done = true;
        for (int i = len - 2; i >= start; i--)
            if (less(array[i + 1], array[i])) {
                swap(array[i], array[i+1]);
                done = false;
            }
        if (done)
            break;
    }
}

void print(int *array, int len)
{
    for (int i = 0; i < len; i++)
        printf("%d ", array[i]);
    printf("\n");
}

int main()
{
    int values[] = { 30, 10, 40, 20 };
    int len = sizeof(values) / sizeof(*values);
    int *pointers[] = { &values[0], &values[1], &values[2], &values[3] };

    sort(pointers, len);
    for (int i = 0; i < len; i++)
        printf("%d ", *pointers[i]);
    printf("\n");

    printf("values untouched: ");
    print(values, len);

    sort(values, len);
    print(values, len);

    return 0;
}
specialization.cppC++ / 44 lines
#include <stdio.h>

template <class A, class B>             /* the general template */
class Cls {
    A first;
    B second;
public:
    const char *Which() const { return "general"; }
};

template <class X>                      /* the specializing variant */
class Cls<X, int> {
    X first;
    int count;
public:
    Cls() : count(0) {}
    const char *Which() const { return "second is int"; }
    void Count() { count++; }           /* exists only in this variant */
};

template <>                             /* a full specialization */
class Cls<double, int> {
public:
    const char *Which() const { return "exactly double, int"; }
};

int main()
{
    Cls<char, double> a;
    Cls<char, int> b;
    Cls<long, int> c;
    Cls<int, char> d;
    Cls<double, int> e;
    printf("Cls<char, double>:  %s\n", a.Which());
    printf("Cls<char, int>:     %s\n", b.Which());
    printf("Cls<long, int>:     %s\n", c.Which());
    printf("Cls<int, char>:     %s\n", d.Which());
    printf("Cls<double, int>:   %s\n", e.Which());
    b.Count();
#ifdef ERRORS
    a.Count();
#endif
    return 0;
}
Section test03g-sparse (10-07)In catalog
MakefileMake / 20 lines
MODULES = sparse

SRCMODULES = $(wildcard $(MODULES:=.cpp))
HEADERS = $(wildcard $(MODULES:=.hpp))
OBJMODULES = $(SRCMODULES:.cpp=.o)

PROGRAMS = main

CXXFLAGS = -g -Wall -ansi -pedantic -Wno-long-long -fwrapv

all: $(PROGRAMS)

%.o: %.cpp $(HEADERS)
    $(CXX) $(CXXFLAGS) -c $< -o $@

$(PROGRAMS): %: %.cpp $(OBJMODULES) $(HEADERS)
    $(CXX) $(CXXFLAGS) $(filter-out %.hpp,$^) $(LDLIBS) -o $@

clean:
    rm -f *.o $(PROGRAMS)
main.cppC++ / 368 lines
#include <stdio.h>

#include "sparse.hpp"

static int checks = 0, failures = 0;

bool check(bool ok, const char *msg)
{
    checks++;
    if (!ok) {
        fprintf(stderr, "wrong %s\n", msg);
        failures++;
    }
    return ok;
}

void check_int(long got, long want, const char *msg)
{
    if (!check(got == want, msg))
        fprintf(stderr, "    got %ld, want %ld\n", got, want);
}

void test_assignment()
{
    SparseArray<int> a(0);
    check_int(a[5], 0, "missing element is the default");
    check_int(a.NonzeroCount(), 0, "empty array stores nothing");
    a[5] = 10;
    a[-3] = 20;
    a[1000000] = 30;
    check_int(a[5], 10, "assigned element");
    check_int(a[-3], 20, "negative index");
    check_int(a[1000000], 30, "large index");
    check_int(a.NonzeroCount(), 3, "count after three assignments");
    a[5] = 11;
    check_int(a[5], 11, "overwritten element");
    check_int(a.NonzeroCount(), 3, "overwriting adds nothing");
    a[5] = 0;
    check_int(a[5], 0, "element assigned the default");
    check_int(a.NonzeroCount(), 2, "assigning the default removes");
    a[77] = 0;
    check_int(a.NonzeroCount(), 2, "default to a missing element");
    check_int(a[8] = 9, 9, "value of an assignment");
}

void test_element_to_element()
{
    SparseArray<int> a(0);
    a[1] = 10;
    a[2] = 20;
    a[1] = a[2];
    check_int(a[1], 20, "a[1] = a[2]");
    a[3] = a[9];
    check_int(a.NonzeroCount(), 2, "a[3] = missing stores nothing");
    a[2] = a[9];
    check_int(a.NonzeroCount(), 1, "a[2] = missing removes a[2]");
    a[1] = a[1];
    check_int(a[1], 20, "a[1] = a[1]");
    a[4] = a[5] = 7;
    check_int(a[4] + a[5], 14, "a[4] = a[5] = 7");
}

/* every operator generated by SPARSE_ASSIGN, on the same start value */
void test_assign_operators()
{
    SparseArray<int> a(0);
    int i;
    for (i = 0; i < 10; i++)
        a[i] = 12;
    check_int(a[0] += 5, 17, "+=");
    check_int(a[1] -= 5, 7, "-=");
    check_int(a[2] *= 5, 60, "*=");
    check_int(a[3] /= 5, 2, "/=");
    check_int(a[4] %= 5, 2, "%=");
    check_int(a[5] |= 3, 15, "|=");
    check_int(a[6] &= 5, 4, "&=");
    check_int(a[7] ^= 5, 9, "^=");
    check_int(a[8] <<= 2, 48, "<<=");
    check_int(a[9] >>= 2, 3, ">>=");
    check_int(a[0] + a[1] + a[2] + a[3] + a[4], 88, "stored: first five");
    check_int(a[5] + a[6] + a[7] + a[8] + a[9], 79, "stored: last five");
}

/* an operator whose result is the default must remove the element */
void test_operators_remove()
{
    SparseArray<int> a(0);
    int i;
    for (i = 0; i < 8; i++)
        a[i] = 12;
    a[0] += -12;
    a[1] -= 12;
    a[2] *= 0;
    a[3] /= 13;
    a[4] %= 12;
    a[5] &= 3;
    a[6] ^= 12;
    a[7] >>= 4;
    check_int(a.NonzeroCount(), 0, "results equal to the default");
    a[9] += 5;
    check_int(a[9], 5, "+= on a missing element");
    a[8] += 0;
    check_int(a.NonzeroCount(), 1, "+= 0 on a missing element");
    a[9] += a[9];
    check_int(a[9], 10, "a[9] += a[9]");
    a[9] -= a[9];
    check_int(a.NonzeroCount(), 0, "a[9] -= a[9]");
}

/* the operators generated by SPARSE_STEP */
void test_steps()
{
    SparseArray<int> a(0);
    a[1] = 5;
    check_int(++a[1], 6, "prefix ++ gives the new value");
    check_int(a[1]++, 6, "postfix ++ gives the old value");
    check_int(a[1], 7, "after two increments");
    check_int(--a[1], 6, "prefix -- gives the new value");
    check_int(a[1]--, 6, "postfix -- gives the old value");
    check_int(a[1], 5, "after two decrements");
    check_int(a[2]++, 0, "postfix ++ on a missing element");
    check_int(a[2], 1, "missing element after ++");
    a[2]--;
    check_int(a.NonzeroCount(), 1, "-- down to the default removes");
    a[3] = -1;
    ++a[3];
    check_int(a.NonzeroCount(), 1, "++ up to the default removes");
}

void test_nonzero_default()
{
    SparseArray<int> a(100);
    check_int(a[5], 100, "missing element, default 100");
    a[5] += 1;
    check_int(a[5], 101, "+= starts from the default");
    a[6] = 0;
    check_int(a.NonzeroCount(), 2, "zero is stored when default is 100");
    a[5]--;
    a[6] = 100;
    check_int(a.NonzeroCount(), 0, "back to the default");
}

void test_const_reference()
{
    SparseArray<int> a(0);
    const SparseArray<int>& c = a;
    int i, sum = 0;
    a[1] = 10;
    a[3] = 30;
    for (i = 0; i < 100; i++)
        sum += c[i];
    check_int(sum, 40, "sum through a const reference");
    check_int(a.NonzeroCount(), 2, "reading creates nothing");
    check(&c[1] == &c[1], "same object for an existing element");
    check(&c[2] == &c[99], "one object for all missing elements");
    check(&c[1] != &c[3], "different objects for different elements");
    const int& r = c[3];
    a[3] = 31;
    check_int(r, 31, "a reference follows its element");
}

void test_double()
{
    SparseArray<double> d(0.5);
    d[1] = 2.0;
    d[1] *= 4;
    d[2] += 1.5;
    d[3] = 0.5;
    check(d[1] == 8.0, "double: *=");
    check(d[2] == 2.0, "double: += from the default");
    check(d[9] == 0.5, "double: missing element");
    check_int(d.NonzeroCount(), 2, "double: count");
    d[2] -= 1.5;
    check_int(d.NonzeroCount(), 1, "double: back to the default");
}

class Money {                   /* has ==, =, copying; nothing else */
    long cents;
public:
    Money(long a_cents = 0) : cents(a_cents) {}
    long Cents() const { return cents; }
    bool operator==(const Money& other) const { return cents == other.cents; }
};

void test_class_element()
{
    SparseArray<Money> m(Money(0));
    const SparseArray<Money>& c = m;
    m[1] = Money(250);
    m[2] = Money(999);
    m[2] = Money(0);
    check_int(c[1].Cents(), 250, "class: stored element");
    check_int(c[2].Cents(), 0, "class: removed element");
    check_int(Money(m[1]).Cents(), 250, "class: conversion to a copy");
    check_int(m.NonzeroCount(), 1, "class: count");
    m[3] = m[1];
    check_int(c[3].Cents(), 250, "class: element to element");
}

struct Point {
    int x, y;
};

void test_pointers()
{
    Point p = { 3, 4 };
    SparseArray<Point*> s(0);
    bool thrown = false;
    s[1] = &p;
    check_int(s[1]->x + s[1]->y, 7, "pointers: reading through ->");
    s[1]->x = 30;
    check_int(p.x, 30, "pointers: changing through ->");
    try {
        s[9]->x = 1;
    }
    catch (const NullElement& ex) {
        thrown = ex.Index() == 9;
    }
    check(thrown, "pointers: NullElement for a missing element");
    check_int(s.NonzeroCount(), 1, "pointers: -> creates nothing");
}

void test_bool()
{
    SparseArray<bool> b(false), t(true);
    const SparseArray<bool>& c = b;
    b[5] = true;
    b[1000000] = true;
    b[1] = 25;
    check(c[5] && c[1000000] && c[1], "bool: elements set");
    check(!c[0] && !c[6], "bool: missing elements are false");
    check_int(c[1], 1, "bool: 25 is stored as true");
    b[5] = true;
    check_int(b.NonzeroCount(), 3, "bool: no duplicate index");
    b[1] = false;
    check_int(b.NonzeroCount(), 2, "bool: false removes");
    b[0] = b[5];
    check(c[0], "bool: element to element");
    t[5] = false;
    check(!t[5] && t[4], "bool: default true");
    check_int(t.NonzeroCount(), 1, "bool: false stored, default true");
}

void test_bool_operators()
{
    SparseArray<bool> b(false);
    b[1] |= true;
    b[2] |= false;
    check_int(b.NonzeroCount(), 1, "bool: |=");
    b[1] &= false;
    check_int(b.NonzeroCount(), 0, "bool: &=");
    b[3] ^= true;
    b[3] ^= true;
    b[4] ^= true;
    check(!b[3] && b[4], "bool: ^=");
}

struct DivisionByZero {};

class Frac {                    /* /= throws on zero */
    int n;
public:
    Frac(int a_n = 0) : n(a_n) {}
    int Num() const { return n; }
    bool operator==(const Frac& other) const { return n == other.n; }
    Frac& operator/=(const Frac& other);
};

Frac& Frac::operator/=(const Frac& other)
{
    if (other.n == 0)
        throw DivisionByZero();
    n /= other.n;
    return *this;
}

/* an operator that throws must leave the array as it was */
void test_throwing_operator()
{
    SparseArray<Frac> f(Frac(0));
    bool thrown = false;
    f[1] = Frac(8);
    try {
        f[5] /= Frac(0);
    }
    catch (const DivisionByZero&) {
        thrown = true;
    }
    check(thrown, "throwing: the exception gets out");
    check_int(f.NonzeroCount(), 1, "throwing: a failed op stores nothing");
    f[1] /= Frac(2);
    check_int(Frac(f[1]).Num(), 4, "throwing: a good op still works");
}

class Tag {                     /* no default constructor */
    int id;
public:
    Tag(int a_id) : id(a_id) {}
    int Id() const { return id; }
    bool operator==(const Tag& other) const { return id == other.id; }
};

void test_no_default_constructor()
{
    SparseArray<Tag> t(Tag(0));
    const SparseArray<Tag>& c = t;
    t[1] = Tag(7);
    t[2] = t[1];
    check_int(c[2].Id(), 7, "no default constructor: stored");
    check_int(c[9].Id(), 0, "no default constructor: missing");
    check_int(t.NonzeroCount(), 2, "no default constructor: count");
}

template <class T>
int count_set(SparseArray<T>& a, int n)
{
    int i, count = 0;
    for (i = 0; i < n; i++)
        if (a[i])
            count++;
    return count;
}

void test_many()
{
    SparseArray<int> a(0);
    SparseArray<bool> b(false);
    int i;
    for (i = 0; i < 1000; i++) {
        a[3 * i] = i + 1;
        b[3 * i] = true;
    }
    check_int(a.NonzeroCount(), 1000, "many: int count");
    check_int(b.NonzeroCount(), 1000, "many: bool count");
    check_int(count_set(a, 3000), 1000, "many: int values");
    check_int(count_set(b, 3000), 1000, "many: bool values");
    for (i = 0; i < 1000; i += 2) {
        a[3 * i] = 0;
        b[3 * i] = false;
    }
    check_int(a.NonzeroCount(), 500, "many: int count after removal");
    check_int(b.NonzeroCount(), 500, "many: bool count after removal");
    check_int(a[3 * 999], 1000, "many: last element intact");
}

int main()
{
    test_assignment();
    test_element_to_element();
    test_assign_operators();
    test_operators_remove();
    test_steps();
    test_nonzero_default();
    test_const_reference();
    test_double();
    test_class_element();
    test_pointers();
    test_bool();
    test_bool_operators();
    test_throwing_operator();
    test_no_default_constructor();
    test_many();
    if (failures)
        fprintf(stderr, "%d of %d checks failed\n", failures, checks);
    else
        printf("all %d checks passed\n", checks);
    return failures != 0;
}
sparse.hppC++ / 237 lines
#ifndef SPARSE_HPP
#define SPARSE_HPP

class NullElement {
    int index;
public:
    NullElement(int idx) : index(idx) {}
    int Index() const { return index; }
};

#define SPARSE_ASSIGN(TYPE, OP, ARG)                                    \
        TYPE operator OP(ARG x)                                         \
            { TYPE v = *this; v OP x; return *this = v; }

#define SPARSE_STEP(TYPE, OP)                                           \
        TYPE operator OP() { TYPE v = *this; OP v; return *this = v; }  \
        TYPE operator OP(int)                                           \
            { TYPE old = *this; TYPE v = old; v OP; *this = v; return old; }

template <class T>
class SparseArray {
    struct Item {
        int index;
        T value;
        Item *next;
        Item(int idx, const T& val, Item *nxt)
            : index(idx), value(val), next(nxt) {}
    };
    Item *first;
    T defval;
    T *Find(int idx) const;
    void Remove(int idx);
    const T& Get(int idx) const;
    void Set(int idx, const T& x);
public:
    SparseArray(const T& dv) : first(0), defval(dv) {}
    ~SparseArray();
    class Interm {
        friend class SparseArray<T>;
        SparseArray<T> *master;
        int index;
        Interm(SparseArray<T> *a_master, int ind)
            : master(a_master), index(ind) {}
    public:
        operator T() const { return master->Get(index); }
        T operator=(const T& x) { master->Set(index, x); return x; }
        T operator=(const Interm& x) { return *this = T(x); }

        SPARSE_ASSIGN(T, +=, const T&)
        SPARSE_ASSIGN(T, -=, const T&)
        SPARSE_ASSIGN(T, *=, const T&)
        SPARSE_ASSIGN(T, /=, const T&)
        SPARSE_ASSIGN(T, %=, const T&)
        SPARSE_ASSIGN(T, |=, const T&)
        SPARSE_ASSIGN(T, &=, const T&)
        SPARSE_ASSIGN(T, ^=, const T&)
        SPARSE_ASSIGN(T, <<=, int)
        SPARSE_ASSIGN(T, >>=, int)
        SPARSE_STEP(T, ++)
        SPARSE_STEP(T, --)

        T operator->() const;
    };
    friend class Interm;

    Interm operator[](int idx) { return Interm(this, idx); }
    const T& operator[](int idx) const { return Get(idx); }

    int NonzeroCount() const;
private:
    SparseArray(const SparseArray<T>&) {}
    void operator=(const SparseArray<T>&) {}
};

template <class T>
SparseArray<T>::~SparseArray()
{
    while (first) {
        Item *tmp = first;
        first = first->next;
        delete tmp;
    }
}

template <class T>
T *SparseArray<T>::Find(int idx) const
{
    for (Item *tmp = first; tmp; tmp = tmp->next)
        if (tmp->index == idx)
            return &tmp->value;
    return 0;
}

template <class T>
void SparseArray<T>::Remove(int idx)
{
    for (Item **tmp = &first; *tmp; tmp = &(*tmp)->next)
        if ((*tmp)->index == idx) {
            Item *to_delete = *tmp;
            *tmp = to_delete->next;
            delete to_delete;
            return;
        }
}

template <class T>
const T& SparseArray<T>::Get(int idx) const
{
    T *found = Find(idx);
    if (found)
        return *found;
    return defval;
}

template <class T>
void SparseArray<T>::Set(int idx, const T& x)
{
    if (x == defval) {
        Remove(idx);
        return;
    }
    T *found = Find(idx);
    if (found)
        *found = x;
    else
        first = new Item(idx, x, first);
}

template <class T>
int SparseArray<T>::NonzeroCount() const
{
    int sum = 0;
    for (Item *tmp = first; tmp; tmp = tmp->next)
        sum++;
    return sum;
}

template <class T>
T SparseArray<T>::Interm::operator->() const
{
    T p = *this;
    if (!p)
        throw NullElement(index);
    return p;
}

template <>
class SparseArray<bool> {
    int *indices;
    int len, capacity;
    bool defval;
    int Find(int idx) const;
    void Add(int idx);
    void Remove(int idx);
    bool Get(int idx) const;
    void Set(int idx, bool x);
public:
    SparseArray(bool dv) : indices(0), len(0), capacity(0), defval(dv) {}
    ~SparseArray() { delete[] indices; }
    class Interm {
        friend class SparseArray<bool>;
        SparseArray<bool> *master;
        int index;
        Interm(SparseArray<bool> *a_master, int ind)
            : master(a_master), index(ind) {}
    public:
        operator bool() const { return master->Get(index); }
        bool operator=(bool x) { master->Set(index, x); return x; }
        bool operator=(const Interm& x) { return *this = bool(x); }

        SPARSE_ASSIGN(bool, |=, bool)
        SPARSE_ASSIGN(bool, &=, bool)
        SPARSE_ASSIGN(bool, ^=, bool)
    };
    friend class Interm;

    Interm operator[](int idx) { return Interm(this, idx); }
    bool operator[](int idx) const { return Get(idx); }

    int NonzeroCount() const { return len; }
private:
    SparseArray(const SparseArray<bool>&) {}
    void operator=(const SparseArray<bool>&) {}
};

#undef SPARSE_ASSIGN
#undef SPARSE_STEP

inline int SparseArray<bool>::Find(int idx) const
{
    for (int i = 0; i < len; i++)
        if (indices[i] == idx)
            return i;
    return -1;
}

inline void SparseArray<bool>::Add(int idx)
{
    if (Find(idx) != -1)
        return;
    if (len == capacity) {
        int new_capacity = capacity ? 2 * capacity : 16;
        int *new_indices = new int[new_capacity];
        for (int i = 0; i < len; i++)
            new_indices[i] = indices[i];
        delete[] indices;
        indices = new_indices;
        capacity = new_capacity;
    }
    indices[len] = idx;
    len++;
}

inline void SparseArray<bool>::Remove(int idx)
{
    int pos = Find(idx);
    if (pos == -1)
        return;
    indices[pos] = indices[len - 1];
    len--;
}

inline bool SparseArray<bool>::Get(int idx) const
{
    bool stored = Find(idx) != -1;
    return stored ? !defval : defval;
}

inline void SparseArray<bool>::Set(int idx, bool x)
{
    if (x == defval)
        Remove(idx);
    else
        Add(idx);
}

#endif

10.7.4 Example: folding sequences

A position interface with Get, Next, and Empty lets the same fold operate on arrays, lists, or generated sequences. Separating position, element, and result types reveals the reusable structure behind sums and list transformations.

A position type supplies Get, Next and Empty; the folds never learn whether they walk an array or a list:

template <class elem>
class ArrayPosition {
    elem *p;
    int count;
public:
    ArrayPosition(elem *a_p, int a_count) : p(a_p), count(a_count) {}
    elem Get() const { return *p; }
    ArrayPosition Next() const { return ArrayPosition(p + 1, count - 1); }
    bool Empty() const { return count <= 0; }
};

template <class item, class elem>
class ListPosition {
    item *p;
public:
    ListPosition(item *a_p) : p(a_p) {}
    elem Get() const { return p->data; }
    ListPosition Next() const { return ListPosition(p->next); }
    bool Empty() const { return p == 0; }
};

template <class Pos, class Elem, class Res>
Res fold_right(Pos pos, Res (*func)(Elem, Res), Res init)
{
    if (pos.Empty())
        return init;
    return func(pos.Get(), fold_right(pos.Next(), func, init));
}

template <class Pos, class Elem, class Res>
Res fold_left(Pos pos, Res (*func)(Elem, Res), Res init)
{
    if (pos.Empty())
        return init;
    return fold_left(pos.Next(), func, func(pos.Get(), init));
}
Show the complete program
#include <stdio.h>

template <class elem>
class ArrayPosition {
    elem *p;
    int count;
public:
    ArrayPosition(elem *a_p, int a_count) : p(a_p), count(a_count) {}
    elem Get() const { return *p; }
    ArrayPosition Next() const { return ArrayPosition(p + 1, count - 1); }
    bool Empty() const { return count <= 0; }
};

template <class item, class elem>
class ListPosition {
    item *p;
public:
    ListPosition(item *a_p) : p(a_p) {}
    elem Get() const { return p->data; }
    ListPosition Next() const { return ListPosition(p->next); }
    bool Empty() const { return p == 0; }
};

template <class Pos, class Elem, class Res>
Res fold_right(Pos pos, Res (*func)(Elem, Res), Res init)
{
    if (pos.Empty())
        return init;
    return func(pos.Get(), fold_right(pos.Next(), func, init));
}

template <class Pos, class Elem, class Res>
Res fold_left(Pos pos, Res (*func)(Elem, Res), Res init)
{
    if (pos.Empty())
        return init;
    return fold_left(pos.Next(), func, func(pos.Get(), init));
}

struct int_item {
    int data;
    int_item *next;
};

int sum(int x, int acc) { return x + acc; }
int prod(int x, int acc) { return x * acc; }

int_item *make_il(int x, int_item *tail)
{
    int_item *tmp = new int_item;
    tmp->data = x;
    tmp->next = tail;
    return tmp;
}

int *print_int(int x, int *unused)
{
    printf("[%d]", x);
    return unused;
}

int main()
{
    int arr[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    ArrayPosition<int> all(arr, 10);

    printf("%d %d\n", fold_left(all, sum, 0), fold_right(all, prod, 1));

    int_item *list = fold_right(all, make_il, (int_item*)0);
    ListPosition<int_item, int> lp(list);
    printf("%d\n", fold_left(lp, prod, 1));

    fold_left(lp, print_int, (int*)0);      // forward order
    printf("\n");
    fold_right(lp, print_int, (int*)0);     // reverse order
    printf("\n");

    while (list) {
        int_item *tmp = list;
        list = list->next;
        delete tmp;
    }
    return 0;
}
55 3628800
3628800
[1][2][3][4][5][6][7][8][9][10]
[10][9][8][7][6][5][4][3][2][1]
Detailed notes - 10.7.4: Example: folding sequences

1

templates allow the earlier fold idea to apply to several representations

2

sequence elements have a consistent element type for each instantiation

3

a position abstraction must support three actions

  • obtain the current element
  • obtain the next position
  • determine whether the sequence has ended

linked list: a node pointer supplies position; null means empty

4

array position also needs a boundary

  • the example stores an element pointer and remaining count

5

other possible sequences include file input and generated values Pos interface: Get, Next and Empty

  • Next returns a new position value
  • position copying must have suitable semantics
  • do not use Get or Next after Empty reports true

6

ListPosition<item, elem> stores a node pointer

  • Get returns data; Next follows next; Empty checks null

ArrayPosition<elem> stores pointer and remaining count

  • Get dereferences, Next advances/decrements, Empty checks count

generic folds take Pos, Elem and Res template parameters

  • element type and accumulated result type may differ
  • both examples call func(element, accumulated_result)

right fold:

  • recurse over the tail first, then combine the current element

left fold:

  • combine the current element with the accumulator first, then recur
  • empty sequence returns the supplied initial result
  • recursive implementation can consume stack; C++ does not promise tail-call elimination

7

sum and product use corresponding combining functions

  • initial sum = 0; initial product = 1
  • array 1..10 gives 55 and 3628800
  • left/right folds agree here within the arithmetic's valid range

8

make_il takes an integer and a tail pointer, allocates a new head

  • right fold builds a linked list from the array
  • initial result must have pointer type for deduction, e.g. (int_item*)0

9

each result node points to the already constructed tail

  • right fold preserves original element order
  • ownership of the resulting nodes belongs to the resulting list's user

10

the same prod function folds the resulting list

  • only the position adapter changes
  • the combining function does not know whether storage is array or list

11

printing is a side effect, but the example can still use a fold

  • left fold invokes the printing function in forward element order
  • right fold invokes it in reverse order
  • its nominal pointer result only satisfies the fold's accumulator type

other possible folds construct copies, reverse lists, filter or transform

12

these particular tasks may be simpler as direct loops

  • the example demonstrates the paradigm and template abstraction
  • it does not claim that folding is always the best implementation
Examples & tests (8 files) - 10.7.4: Example: folding sequences
Book exampleBook example: reduce.cppIn catalog
reduce.cppC++ / 120 lines
#include <stdio.h>


template <class item, class elem>
class ListPosition {
    item *p;
public:
    ListPosition(item *lst) : p(lst) {}
    ~ListPosition() {}
    ListPosition<item, elem> Next() const
        { return ListPosition(p->next); }
    bool Empty() const { return !p; }
    const elem &Get() const { return p->data; }
};

template <class elem>
class ArrayPosition {
    elem *p;
    int rest_size;
public:
    ArrayPosition(elem *a, int len) : p(a), rest_size(len) {}
    ~ArrayPosition() {}
    ArrayPosition<elem> Next() const
        { return ArrayPosition(p+1, rest_size-1); }
    bool Empty() const { return rest_size < 1; }
    const elem &Get() const { return *p; }
};

class InputStreamPosition {
    FILE *f;
    int c;
public:
    InputStreamPosition(FILE *af) : f(af) { c = fgetc(af); }
    ~InputStreamPosition() {}
    InputStreamPosition Next() const { return InputStreamPosition(f); }
    bool Empty() const { return c == EOF || c == '\n'; }
    int Get() const { return c; }
};

template <class Pos, class Elem, class Res>
Res reduce_right(Res (*func)(Elem, Res), Pos pos, Res init)
{
    return pos.Empty() ? init :
        func(pos.Get(), reduce_right(func, pos.Next(), init));
}

template <class Pos, class Elem, class Res>
Res reduce_left(Res (*func)(Elem, Res), Pos pos, Res init)
{
    return pos.Empty() ? init :
        reduce_left(func, pos.Next(), func(pos.Get(), init));
}

template <class t> t sum(t x, t y) { return x + y; }
template <class t> t prod(t x, t y) { return x * y; }


struct int_item {
    int data;
    struct int_item *next;
};

struct int_item *make_il(int d, struct int_item *rest)
{
    struct int_item *p = new int_item;
    p->data = d;
    p->next = rest;
    return p;
}

void print_ilist(const struct int_item *list)
{
    if(!list) {
        printf("\n");
        return;
    }
    printf("%d ", list->data);
    print_ilist(list->next);
}

struct int_item *print_il(int d, struct int_item *rest)
{
    printf("%d ", d);
    return 0;
}

int main()
{
    {
        int array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        int res1 =
            reduce_left(sum<int>, ArrayPosition<int>(array, 10), 0);
        int res2 =
            reduce_right(sum<int>, ArrayPosition<int>(array, 10), 0);
        printf("%d %d\n", res1, res2);

        int res3 =
            reduce_left(prod<int>, ArrayPosition<int>(array, 10), 1);
        int res4 =
            reduce_right(prod<int>, ArrayPosition<int>(array, 10), 1);
        printf("%d %d\n", res3, res4);

        struct int_item * list =
            reduce_right(make_il, ArrayPosition<int>(array, 10), (int_item*)0);

        print_ilist(list);

        int res5 =
            reduce_left(prod<int>, ListPosition<int_item, int>(list), 1);
        printf("%d\n", res5);

        reduce_left(print_il, ListPosition<int_item, int>(list), (int_item*)0);
        printf("\n");
        reduce_right(print_il, ListPosition<int_item, int>(list), (int_item*)0);
        printf("\n");

    }

    return 0;
}
Section test04 (10-07)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
reduction00.cppC++ / 95 lines
#include <stdio.h>

template <class item, class elem>
class ListPosition {
    item *p;
public:
    ListPosition(item *lst) : p(lst) {}
    ~ListPosition() {}
    ListPosition<item, elem> Next() const
        { return ListPosition(p->next); }
    bool Empty() const { return !p; }
    const elem& Get() const { return p->data; }
};

template <class elem>
class ArrayPosition {
    elem *p;
    int rest_size;
public:
    ArrayPosition(elem *a, int len) : p(a), rest_size(len) {}
    ~ArrayPosition() {}
    ArrayPosition<elem> Next() const
        { return ArrayPosition(p + 1, rest_size - 1); }
    bool Empty() const { return rest_size < 1; }
    const elem& Get() const { return *p; }
};

template <class Pos, class Elem, class Res>
Res reduce_left(Res (*func)(Elem, Res), Pos pos, Res init)
{
    return pos.Empty() ? init :
        reduce_left(func, pos.Next(), func(pos.Get(), init));
}

template <class Pos, class Elem, class Res>
Res reduce_right(Res (*func)(Elem, Res), Pos pos, Res init)
{
    return pos.Empty() ? init :
        func(pos.Get(), reduce_right(func, pos.Next(), init));
}

template <class t>
t sum(t x, t y)
{
    return x + y;
}

template <class t>
t prod(t x, t y)
{
    return x * y;
}

struct int_item {
    int data;
    struct int_item *next;
};

int_item *make_il(int d, int_item *rest)
{
    int_item *p = new int_item;
    p->data = d;
    p->next = rest;
    return p;
}

int_item *print_il(int d, int_item *rest)
{
    printf("%d ", d);
    return 0;
}

int main()
{
    int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int len = sizeof(array)/sizeof(*array);
    int res1 = reduce_left(sum<int>, ArrayPosition<int>(array, len), 0);
    int res2 = reduce_right(sum<int>, ArrayPosition<int>(array, len), 0);
    int res3 = reduce_left(prod<int>, ArrayPosition<int>(array, len), 1);
    int res4 = reduce_right(prod<int>, ArrayPosition<int>(array, len), 1);
    printf("%d %d %d %d\n", res1, res2, res3, res4);

    int_item *list =
        reduce_right(make_il, ArrayPosition<int>(array, len), (int_item*)0);
    int res5 = reduce_left(prod<int>, ListPosition<int_item, int>(list), 1);
    printf("%d\n", res5);

    reduce_left(print_il, ListPosition<int_item, int>(list), (int_item*)0);
    printf("\n");

    reduce_right(print_il, ListPosition<int_item, int>(list), (int_item*)0);
    printf("\n");

    return 0;
}
reduction01.cppC++ / 116 lines
#include <stdio.h>

template <class item, class elem>
class ListPosition {
    item *p;
public:
    ListPosition(item *lst) : p(lst) {}
    ~ListPosition() {}
    ListPosition<item, elem> Next() const
        { return ListPosition(p->next); }
    bool Empty() const { return !p; }
    const elem& Get() const { return p->data; }
};

template <class elem>
class ArrayPosition {
    elem *p;
    int rest_size;
public:
    ArrayPosition(elem *a, int len) : p(a), rest_size(len) {}
    ~ArrayPosition() {}
    ArrayPosition<elem> Next() const
        { return ArrayPosition(p + 1, rest_size - 1); }
    bool Empty() const { return rest_size < 1; }
    const elem& Get() const { return *p; }
};

class InputStreamPosition {
    FILE *f;
    int c;
public:
    InputStreamPosition(FILE *af) : f(af) { c = fgetc(af); }
    ~InputStreamPosition() {}
    InputStreamPosition Next() const { return InputStreamPosition(f); }
    bool Empty() const { return c == EOF || c == '\n'; }
    int Get() const { return c; }
};

template <class Pos, class Elem, class Res>
Res reduce_left(Res (*func)(Elem, Res), Pos pos, Res init)
{
    return pos.Empty() ? init :
        reduce_left(func, pos.Next(), func(pos.Get(), init));
}

template <class Pos, class Elem, class Res>
Res reduce_right(Res (*func)(Elem, Res), Pos pos, Res init)
{
    return pos.Empty() ? init :
        func(pos.Get(), reduce_right(func, pos.Next(), init));
}

template <class t> t sum(t x, t y) { return x + y; }
template <class t> t prod(t x, t y) { return x * y; }

struct int_item {
    int data;
    struct int_item *next;
};

int_item *make_il(int d, int_item *rest)
{
    int_item *p = new int_item;
    p->data = d;
    p->next = rest;
    return p;
}

void print_ilist(const int_item *list)
{
    if (!list) {
        printf("\n");
        return;
    }
    printf("%d ", list->data);
    print_ilist(list->next);
}

int_item *print_il(int d, int_item *rest)
{
    printf("%d ", d);
    return 0;
}

int main()
{
    int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int len = sizeof(array)/sizeof(*array);

    int res1 = reduce_left(sum<int>, ArrayPosition<int>(array, len), 0);
    int res2 = reduce_right(sum<int>, ArrayPosition<int>(array, len), 0);
    printf("%d %d\n", res1, res2);

    int res3 = reduce_left(prod<int>, ArrayPosition<int>(array, len), 1);
    int res4 = reduce_right(prod<int>, ArrayPosition<int>(array, len), 1);
    printf("%d %d\n", res3, res4);

    int_item *list =
        reduce_right(make_il, ArrayPosition<int>(array, len), (int_item*)0);
    print_ilist(list);

    int res5 = reduce_left(prod<int>, ListPosition<int_item, int>(list), 1);
    printf("%d\n", res5);

    reduce_left(print_il, ListPosition<int_item, int>(list), (int_item*)0);
    printf("\n");

    reduce_right(print_il, ListPosition<int_item, int>(list), (int_item*)0);
    printf("\n");

    FILE *f = fopen("reduction01.t", "r");
    int res6 = reduce_left(sum<int>, InputStreamPosition(f), 0);
    printf("%d\n", res6);

    return 0;
}
reduction02.cppC++ / 116 lines
#include <stdio.h>

template <class item, class elem>
class ListPosition {
    item *p;
public:
    ListPosition(item *lst) : p(lst) {}
    ~ListPosition() {}
    ListPosition<item, elem> Next() const
        { return ListPosition(p->next); }
    bool Empty() const { return !p; }
    const elem& Get() const { return p->data; }
};

template <class elem>
class ArrayPosition {
    elem *p;
    int rest_size;
public:
    ArrayPosition(elem *a, int len) : p(a), rest_size(len) {}
    ~ArrayPosition() {}
    ArrayPosition<elem> Next() const
        { return ArrayPosition(p + 1, rest_size - 1); }
    bool Empty() const { return rest_size < 1; }
    const elem& Get() const { return *p; }
};

class InputStreamPosition {
    FILE *f;
    int c;
public:
    InputStreamPosition(FILE *af) : f(af) { c = fgetc(af); }
    ~InputStreamPosition() {}
    InputStreamPosition Next() const { return InputStreamPosition(f); }
    bool Empty() const { return c == EOF || c == '\n'; }
    int Get() const { return c; }
};

template <class Pos, class Elem, class Res>
Res reduce_left(Res (*func)(Elem, Res), Pos pos, Res init)
{
    return pos.Empty() ? init :
        reduce_left(func, pos.Next(), func(pos.Get(), init));
}

template <class Pos, class Elem, class Res>
Res reduce_right(Res (*func)(Elem, Res), Pos pos, Res init)
{
    return pos.Empty() ? init :
        func(pos.Get(), reduce_right(func, pos.Next(), init));
}

template <class t> t sum(t x, t y) { return x + y; }
template <class t> t prod(t x, t y) { return x * y; }

struct int_item {
    int data;
    struct int_item *next;
};

int_item *make_il(int d, int_item *rest)
{
    int_item *p = new int_item;
    p->data = d;
    p->next = rest;
    return p;
}

void print_ilist(const int_item *list)
{
    if (!list) {
        printf("\n");
        return;
    }
    printf("%d ", list->data);
    print_ilist(list->next);
}

int_item *print_il(int d, int_item *rest)
{
    printf("%d ", d);
    return 0;
}

int main()
{
    int array[] = { 10, 20, 30 };
    int len = sizeof(array)/sizeof(*array);

    int res1 = reduce_left(sum<int>, ArrayPosition<int>(array, len), 0);
    int res2 = reduce_right(sum<int>, ArrayPosition<int>(array, len), 0);
    printf("%d %d\n", res1, res2);

    int res3 = reduce_left(prod<int>, ArrayPosition<int>(array, len), 1);
    int res4 = reduce_right(prod<int>, ArrayPosition<int>(array, len), 1);
    printf("%d %d\n", res3, res4);

    int_item *list =
        reduce_right(make_il, ArrayPosition<int>(array, len), (int_item*)0);
    print_ilist(list);

    int res5 = reduce_left(prod<int>, ListPosition<int_item, int>(list), 1);
    printf("%d\n", res5);

    reduce_left(print_il, ListPosition<int_item, int>(list), (int_item*)0);
    printf("\n");

    reduce_right(print_il, ListPosition<int_item, int>(list), (int_item*)0);
    printf("\n");

    FILE *f = fopen("reduction01.t", "r");
    int res6 = reduce_left(sum<int>, InputStreamPosition(f), 0);
    printf("%d\n", res6);

    return 0;
}
reduction03.cppC++ / 118 lines
#include <stdio.h>

template <class item, class elem>
class ListPosition {
    item *p;
public:
    ListPosition(item *lst) : p(lst) {}
    ~ListPosition() {}
    ListPosition<item, elem> Next() const
        { return ListPosition(p->next); }
    bool Empty() const { return !p; }
    const elem& Get() const { return p->data; }
};

template <class elem>
class ArrayPosition {
    elem *p;
    int rest_size;
public:
    ArrayPosition(elem *a, int len) : p(a), rest_size(len) {}
    ~ArrayPosition() {}
    ArrayPosition<elem> Next() const
        { return ArrayPosition(p + 1, rest_size - 1); }
    bool Empty() const { return rest_size < 1; }
    const elem& Get() const { return *p; }
};

template <class Pos, class Elem, class Res>
Res reduce_left(Res (*func)(Elem, Res), Pos pos, Res init)
{
    return pos.Empty() ? init :
        reduce_left(func, pos.Next(), func(pos.Get(), init));
}

template <class Pos, class Elem, class Res>
Res reduce_right(Res (*func)(Elem, Res), Pos pos, Res init)
{
    return pos.Empty() ? init :
        func(pos.Get(), reduce_right(func, pos.Next(), init));
}

template <class t> t sum(t x, t y) { return x + y; }
template <class t> t prod(t x, t y) { return x * y; }

struct int_item {
    int data;
    struct int_item *next;
};

int_item *make_il(int d, int_item *rest)
{
    int_item *p = new int_item;
    p->data = d;
    p->next = rest;
    return p;
}

void print_ilist(const int_item *list)
{
    if (!list) {
        printf("\n");
        return;
    }
    printf("%d ", list->data);
    print_ilist(list->next);
}

int_item *print_il(int d, int_item *rest)
{
    printf("%d ", d);
    return 0;
}

int_item *make_odd_list(int d, int_item *rest)
{
    if (d % 2 == 1) {
        int_item *p = new int_item;
        p->data = d;
        p->next = rest;
        return p;
    } else
        return rest;
}

int main()
{
    int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int len = sizeof(array)/sizeof(*array);

    int res1 = reduce_left(sum<int>, ArrayPosition<int>(array, len), 0);
    int res2 = reduce_right(sum<int>, ArrayPosition<int>(array, len), 0);
    printf("%d %d\n", res1, res2);

    int res3 = reduce_left(prod<int>, ArrayPosition<int>(array, len), 1);
    int res4 = reduce_right(prod<int>, ArrayPosition<int>(array, len), 1);
    printf("%d %d\n", res3, res4);

    int_item *list =
        reduce_right(make_il, ArrayPosition<int>(array, len), (int_item*)0);
    print_ilist(list);

    int res5 = reduce_left(prod<int>, ListPosition<int_item, int>(list), 1);
    printf("%d\n", res5);

    reduce_left(print_il, ListPosition<int_item, int>(list), (int_item*)0);
    printf("\n");

    reduce_right(print_il, ListPosition<int_item, int>(list), (int_item*)0);
    printf("\n");

    int_item *list2 =
        reduce_left(make_odd_list, ListPosition<int_item, int>(list), (int_item*)0);

    reduce_left(print_il, ListPosition<int_item, int>(list2), (int_item*)0);
    printf("\n");

    return 0;
}
reduction04.cppC++ / 157 lines
#include <stdio.h>

template <class item, class elem>
class ListPosition {
    item *p;
public:
    ListPosition(item *lst) : p(lst) {}
    ListPosition<item, elem> Next() const
        { return ListPosition(p->next); }
    bool Empty() const { return !p; }
    const elem& Get() const { return p->data; }
};

template <class elem>
class RangePosition {
    elem cur, last;
public:
    RangePosition(elem from, elem to) : cur(from), last(to) {}
    RangePosition<elem> Next() const { return RangePosition(cur + 1, last); }
    bool Empty() const { return cur > last; }
    elem Get() const { return cur; }
};

class NaturalPosition {
    int cur;
public:
    NaturalPosition(int from = 1) : cur(from) {}
    NaturalPosition Next() const { return NaturalPosition(cur + 1); }
    bool Empty() const { return false; }
    int Get() const { return cur; }
    NaturalPosition operator+(const NaturalPosition &n) { return cur + n.cur; }
    operator int() const { return cur; }
};

template <class elem>
class TakePosition {
    elem cur;
    int n;
public:
    TakePosition(elem from, int a) : cur(from), n(a) {}
    TakePosition<elem> Next() const { return TakePosition(cur + 1, n - 1); }
    bool Empty() const { return n == 0; }
    elem Get() const { return cur; }
};

class StringPosition {
    const char *p;
public:
    StringPosition(const char *a) : p(a) {}
    StringPosition Next() const  { return StringPosition(p + 1); }
    bool Empty() const { return *p == 0; };
    const char& Get() const { return *p; }
};

template <class Pos, class Elem, class Res>
Res reduce_left(Res (*func)(Elem, Res), Pos pos, Res init)
{
    return pos.Empty() ? init :
        reduce_left(func, pos.Next(), func(pos.Get(), init));
}

template <class Pos, class Elem, class Res>
Res reduce_right(Res (*func)(Elem, Res), Pos pos, Res init)
{
    return pos.Empty() ? init :
        func(pos.Get(), reduce_right(func, pos.Next(), init));
}

template <class t> t sum(t x, t y) { return x + y; }
template <class t> t prod(t x, t y) { return x * y; }

struct item {
    int data;
    item *next;
};

item *item_push(int data, item *rest)
{
    item *tmp = new item;
    tmp->data = data;
    tmp->next = rest;
    return tmp;
}

item *item_push_even(int data, item *rest)
{
    if (data % 2 == 0) {
        item *tmp = new item;
        tmp->data = data;
        tmp->next = rest;
        return tmp;
    } else
        return rest;
}

item *item_push_square(int data, item *rest)
{
    item *tmp = new item;
    tmp->data = data * data;
    tmp->next = rest;
    return tmp;
}

item *item_print(int data, item *rest)
{
    printf("%d ", data);
    return 0;
}

template <class elem, class res> res count(elem x, res y) { return y + 1; }

int str2num(char x, int y)
{
    return 10*y + x - '0';
}

int main()
{
    int s = reduce_left(sum<int>, RangePosition<int>(1, 10), 0);
    int p = reduce_left(prod<int>, RangePosition<int>(1, 10), 1);
    printf("%d %d\n", s, p);

    item *list1 = reduce_right(item_push, RangePosition<int>(1, 5), (item*) 0);
    reduce_left(item_print, ListPosition<item, int>(list1), (item*)0);
    printf("\n");

    item *list2 = reduce_left(item_push, RangePosition<int>(1, 5), (item*) 0);
    reduce_left(item_print, ListPosition<item, int>(list2), (item*)0);
    printf("\n");

    item *list3 = reduce_right(item_push, RangePosition<int>(1, 10), (item*) 0);

    item *list4 =
        reduce_right(item_push_even, ListPosition<item, int>(list3), (item*) 0);
    reduce_left(item_print, ListPosition<item, int>(list4), (item*)0);
    printf("\n");

    item *list5 =
        reduce_right(item_push_square, ListPosition<item, int>(list3), (item*) 0);
    reduce_left(item_print, ListPosition<item, int>(list5), (item*)0);
    printf("\n");

    int c = reduce_left(count<char, int>, StringPosition("hello"), 0);
    printf("%d ", c);

    int n1 = reduce_left(str2num, StringPosition("2026"), 0);
    printf("%d ", n1);

    int n2 = reduce_right(str2num, StringPosition("2026"), 0);
    printf("%d\n", n2);

    int s1 = reduce_left(sum<NaturalPosition>, TakePosition<NaturalPosition>(1, 5), (NaturalPosition) 0);
    printf("%d\n", s1);


    return 0;
}
reduction05.cppC++ / 166 lines
#include <stdio.h>

template <class item, class elem>
class ListPosition {
    item *p;
public:
    ListPosition(item *lst) : p(lst) {}
    ListPosition<item, elem> Next() const
        { return ListPosition(p->next); }
    bool Empty() const { return !p; }
    const elem& Get() const { return p->data; }
};

template <class elem>
class RangePosition {
    elem cur, last;
public:
    RangePosition(elem from, elem to) : cur(from), last(to) {}
    RangePosition<elem> Next() const { return RangePosition(cur + 1, last); }
    bool Empty() const { return cur > last; }
    elem Get() const { return cur; }
};

class NaturalPosition {
    int cur;
public:
    NaturalPosition(int from = 1) : cur(from) {}
    NaturalPosition Next() const { return NaturalPosition(cur + 1); }
    bool Empty() const { return false; }
    int Get() const { return cur; }
};

template <class Pos, class Elem>
class TakePosition {
    Pos pos;
    int n;
public:
    TakePosition(Pos a_pos, int a_n) : pos(a_pos), n(a_n) {}
    TakePosition<Pos, Elem> Next() const
        { return TakePosition(pos.Next(), n - 1); }
    bool Empty() const { return n < 1 || pos.Empty(); }
    Elem Get() const { return pos.Get(); }
};

class StringPosition {
    const char *p;
public:
    StringPosition(const char *a) : p(a) {}
    StringPosition Next() const  { return StringPosition(p + 1); }
    bool Empty() const { return *p == 0; };
    const char& Get() const { return *p; }
};

template <class Pos, class Elem, class Res>
Res reduce_left(Res (*func)(Elem, Res), Pos pos, Res init)
{
    return pos.Empty() ? init :
        reduce_left(func, pos.Next(), func(pos.Get(), init));
}

template <class Pos, class Elem, class Res>
Res reduce_right(Res (*func)(Elem, Res), Pos pos, Res init)
{
    return pos.Empty() ? init :
        func(pos.Get(), reduce_right(func, pos.Next(), init));
}

template <class t> t sum(t x, t y) { return x + y; }
template <class t> t prod(t x, t y) { return x * y; }

struct item {
    int data;
    item *next;
};

item *item_push(int data, item *rest)
{
    item *tmp = new item;
    tmp->data = data;
    tmp->next = rest;
    return tmp;
}

item *item_push_even(int data, item *rest)
{
    return data % 2 ? item_push(data, rest) : rest;
}

item *item_push_square(int data, item *rest)
{
    return item_push(data * data, rest);
}

item *item_print(int data, item *rest)
{
    printf("%d ", data);
    return 0;
}

void list_print(item *list)
{
    reduce_left(item_print, ListPosition<item, int>(list), (item*)0);
    printf("\n");
}

void list_delete(item *p)
{
    while (p) {
        item *tmp = p;
        p = p->next;
        delete tmp;
    }
}

template <class elem, class res> res count(elem x, res y) { return y + 1; }

int str2num(char x, int y)
{
    return 10*y + x - '0';
}

void lists()
{
    item *list1 = reduce_right(item_push, RangePosition<int>(1, 5), (item*)0);
    item *list2 = reduce_left(item_push, RangePosition<int>(1, 5), (item*)0);
    item *list3 = reduce_right(item_push, RangePosition<int>(1, 10), (item*)0);
    ListPosition<item, int> pos3(list3);
    item *list4 = reduce_right(item_push_even, pos3, (item*)0);
    item *list5 = reduce_right(item_push_square, pos3, (item*)0);
    list_print(list1);
    list_print(list2);
    list_print(list3);
    list_print(list4);
    list_print(list5);
    list_delete(list1);
    list_delete(list2);
    list_delete(list3);
    list_delete(list4);
    list_delete(list5);
}

void strings()
{
    int c = reduce_left(count<char, int>, StringPosition("hello"), 0);
    int n1 = reduce_left(str2num, StringPosition("2026"), 0);
    int n2 = reduce_right(str2num, StringPosition("2026"), 0);
    printf("%d %d %d\n", c, n1, n2);
}

void takes()
{
    TakePosition<NaturalPosition, int> first5(NaturalPosition(1), 5);
    printf("%d\n", reduce_left(sum<int>, first5, 0));
    TakePosition<StringPosition, char> hel(StringPosition("hello"), 3);
    printf("%d\n", reduce_left(count<char, int>, hel, 0));
    TakePosition<RangePosition<int>, int> all(RangePosition<int>(1, 3), 100);
    printf("%d\n", reduce_left(sum<int>, all, 0));
}

int main()
{
    lists();
    strings();
    takes();
    return 0;
}

10.7.5 Constant template arguments

Compile-time value parameters can control recursively generated structure, as an N-dimensional matrix contains lower-dimensional children. A one-dimensional specialization ends the recursion, while ownership, missing children, and permitted argument types remain explicit constraints.

A constant template argument becomes part of the specialization:

template <class T, int size>
void sort(T *array)
{
    for (int start = 0; start < size - 1; start++) {
        for (int i = size - 1; i > start; i--) {
            if (array[i] < array[i-1]) {
                T tmp = array[i];
                array[i] = array[i-1];
                array[i-1] = tmp;
            }
        }
    }
}
int a[10], b[15];
sort<int, 10>(a);       // two different functions
sort<int, 15>(b);

Both levels of MultiMatrix store their contents in a growing array:

template <class T>
class Array {
public:
    Array(const T &init);
    T& operator[](unsigned int idx);                // grows when needed
    const T& operator[](unsigned int idx) const;    // init when absent
    unsigned int Size() const;
};

MultiMatrix<T, init_val, dim> indexes by returning a matrix of one dimension less; a specialization ends the recursion at dim == 1:

template <class T, T init_val, int dim>
class MultiMatrix {
    typedef MultiMatrix<T, init_val, dim - 1> Child;
    Array<Child*> children;         // null: a missing child region
public:
    MultiMatrix() : children(0) {}
    ~MultiMatrix();
    Child& operator[](unsigned int idx);
    const Child& operator[](unsigned int idx) const;
};

template <class T, T init_val>
class MultiMatrix<T, init_val, 1> : public Array<T> {
public:
    MultiMatrix() : Array<T>(init_val) {}
};
Show the complete program
#include <stdio.h>

template <class T>
class Array {
    T *p;
    T init;
    unsigned int size;
public:
    Array(const T &a_init) : p(0), init(a_init), size(0) {}
    ~Array() { delete [] p; }
    T& operator[](unsigned int idx) {
        if (idx >= size)
            Resize(idx);
        return p[idx];
    }
    const T& operator[](unsigned int idx) const {
        return idx < size ? p[idx] : init;
    }
    unsigned int Size() const { return size; }
private:
    void Resize(unsigned int required_index);
    Array(const Array<T> &);
    void operator=(const Array<T> &);
};

template <class T>
void Array<T>::Resize(unsigned int required_index)
{
    unsigned int new_size = size == 0 ? 8 : size;
    while (new_size <= required_index)
        new_size *= 2;
    T *new_array = new T[new_size];
    for (unsigned int i = 0; i < new_size; i++)
        new_array[i] = i < size ? p[i] : init;
    delete [] p;
    p = new_array;
    size = new_size;
}

template <class T, T init_val, int dim>
class MultiMatrix {
    typedef MultiMatrix<T, init_val, dim - 1> Child;
    Array<Child*> children;
public:
    MultiMatrix() : children(0) {}
    ~MultiMatrix() {
        for (unsigned int i = 0; i < children.Size(); i++)
            delete children[i];
    }
    Child& operator[](unsigned int idx) {
        Child *&child = children[idx];      // grows the array if needed
        if (!child)
            child = new Child;
        return *child;
    }
    const Child& operator[](unsigned int idx) const {
        static const Child empty;           // stands for a missing region
        const Child *child = children[idx];
        return child ? *child : empty;
    }
private:
    MultiMatrix(const MultiMatrix &);
    void operator=(const MultiMatrix &);
};

template <class T, T init_val>
class MultiMatrix<T, init_val, 1> : public Array<T> {
public:
    MultiMatrix() : Array<T>(init_val) {}
};

int main()
{
    MultiMatrix<int, -1, 5> mm;

    mm[3][6][8][2][9] = 193;
    mm[1][0][7][4][3] = 251;
    printf("%d %d %d %d\n", mm[3][6][8][2][9], mm[1][0][7][4][3],
           mm[0][0][0][0][0], mm[5][5][5][5][5]);
    return 0;
}
193 251 -1 -1
Detailed notes - 10.7.5: Constant template arguments

1

templates can accept permitted compile-time values as well as types

  • an array length can become a template argument
  • sort<int, 10> and sort<int, 15> then become distinct specializations
  • choose this only when compile-time distinction is useful

2

MultiMatrix<T, init_val, dim>: an automatically growing N-dimensional array

  • T is the stored element type
  • init_val is the common initial element value
  • dim is the compile-time dimension count

general indexing returns a reference to a matrix of dim-1 dimensions

  • specialize dim == 1 to return an element reference
  • the design requires a positive dimension count

3

store pointers to lower-dimensional matrices

  • create a child only when a mutable access needs it
  • null means that whole child region still has default values

4

Array<T> supplies the common growing one-dimensional storage

  • initially empty, carrying its element initial value
  • mutable indexing grows capacity from 8 by doubling as needed
  • copies old elements and initializes every newly allocated element
  • const indexing returns a const reference to an existing element or init
  • copying/assignment of the owner are disabled

MultiMatrix's general form uses Array<child*> initialized with null

  • mutable indexing creates the child on demand, then returns *child
  • const indexing returns an existing child or an empty dummy
  • dimension recursion happens through distinct template specializations

5

MultiMatrix owns the pointed-to children

  • its destructor deletes each existing child
  • Array's destructor releases only the pointer array
  • both levels of ownership therefore need their cleanup

6

const access must not dereference a null child pointer

  • a static empty dummy represents the missing submatrix
  • return it as const so the caller cannot populate shared dummy state

7

one-dimensional specialization wraps Array<T> initialized with init_val

  • mutable [] returns T&
  • const [] returns const T&
  • constness selects the corresponding underlying Array operation

8

for dim == 1, inheritance from Array<T> can remove forwarding methods

  • the constructor merely supplies init_val
  • higher-dimensional indexing differs because storage contains pointers while the interface returns references to their pointed-to

matrices

9

storing child matrices directly would complicate resizing

  • the current Array implementation assigns its elements
  • child owners deliberately disallow copying/assignment
  • deep-copying their entire trees at each resize would be expensive

10

MultiMatrix<int, -1, 5> demonstration:

  • assign 193 and 251 at two five-index positions
  • those positions read back their assigned values
  • untouched positions read -1
  • output: 193 251 -1 -1
  • mutable reads can allocate missing paths even when the value is default

11

non-type template arguments must obey the selected language version's rules

  • the book emphasizes integer constants and permitted object/function addresses
  • a local runtime address cannot supply a compile-time specialization
  • the example's T and init_val must form a permitted argument pair
  • the book's narrow catalogue and rarity claims reflect its older subset

12

the author again objects to generic containers as a design practice

  • the multidimensional array is an instructional example of templates
  • that objection is his opinion, not a general C++ correctness rule
Examples & tests (20 files) - 10.7.5: Constant template arguments
Book exampleBook example: multimatrix.cppIn catalog
multimatrix.cppC++ / 189 lines
// The MultiMatrix template demo
// Copyright (c) Andrey Vikt. Stolyarov, 2011-2025
// This is just a sample program for a book devoted to C++, see
// http://www.stolyarov.info/books/cppintro for details.
// No rights restricted; do whatever you want with this code,
// if you really want to.


template <class T>
class Array {
    T *p;
    T init;
    unsigned int size;
public:
    Array(T in) : p(0), init(in), size(0) {}
    ~Array() { if(p) delete[] p; }
    T& operator[](unsigned int idx) {
        if(idx >= size)
            Resize(idx);
        return p[idx];
    }
    const T& operator[](unsigned int idx) const {
        return idx >= size ? init : p[idx];
    }
    int Size() const { return size; }
private:
    void Resize(unsigned int required_index) {
        unsigned int new_size = size==0 ? 8 : size;
        while(new_size <= required_index)
            new_size *= 2;
        T *new_array = new T[new_size];
        for(unsigned int i = 0; i < new_size; i++)
            new_array[i] = i < size ? p[i] : init;
        if(p)
            delete[] p;
        p = new_array;
        size = new_size;
    }
    void operator=(const Array<T>& ref) {}
    Array(const Array<T>& ref) {}
};

template <class T, T init_val, int dim>
class MultiMatrix {
    Array<MultiMatrix<T, init_val, dim-1>*> arr;
public:
    MultiMatrix() : arr(0) {}
    ~MultiMatrix() {
        for(int i=0; i < arr.Size(); i++)
            if(arr[i])
                delete arr[i];
    }
    MultiMatrix<T, init_val, dim-1>& operator[](unsigned int idx) {
        if(!arr[idx])
            arr[idx] = new MultiMatrix<T, init_val, dim-1>;
        return *arr[idx];
    }
    const MultiMatrix<T, init_val, dim-1>& operator[](unsigned int idx) const {
        static MultiMatrix<T, init_val, dim-1> dummy;
        return arr[idx] ? *arr[idx] : dummy;
    }
};

#if 1    // this implementation works fine, but there's a simpler approach

template <class T, T init_val>
class MultiMatrix<T, init_val, 1> {
    Array<T> arr;
public:
    MultiMatrix() : arr(init_val) {}
    T& operator[](unsigned int idx) { return arr[idx]; }
    const T& operator[](unsigned int idx) const { return arr[idx]; }
};

#else    // here the simpler approach goes

template <class T, T init_val>
class MultiMatrix<T, init_val, 1> : public Array<T> {
public:
    MultiMatrix() : Array<T>(init_val) {}
};

#endif


/* **************************************************************

Please note that this "simplified" approach with inheritance instead of
composition works ONLY for the dim==1 case, because on higher levels
the Array-based object is supposed to hold _pointers_ to "dim-1" objects,
while the operator[] must return a _reference_ to that object, hence
there's an extra dereference in the operator[]'s body.

Attempt to do smth. like this

template <class T, T init_val, int dim>
class MultiMatrix : public Array<MultiMatrix<T, init_val, dim-1>*> {
public:
    MultiMatrix() : Array<MultiMatrix<T, init_val, dim-1>*>(0) {}
};

will therefore fail, effectively meaning that we'll have to provide our own
versions of operator[] anyway, but their bodies will look very ugly as
we'll have to mention the base class explicitly, several times, and, heh,
just take a look at it (that "Array<MultiMatrix<T, init_val, dim-1>*>"
thing).

There's also a temptation to hold objects, not pointers, within the arrays,
so it will be smth. like

template <class T, T init_val, int dim>
class MultiMatrix : public Array<MultiMatrix<T, init_val, dim-1> > {
public:
    MultiMatrix() {}
};

Holding an object instead of a pointer is not good as the object is
notably larger, but this may be considered a minor issue not preventing us
from implementing the thing that way.  However, there are more problems.

Such an implementation requires a default constructor for the Array
template (which is okay), but this also requires the assignment operator
for the Array<...> classes to be visible (and properly implemented), as it
is used within the Resize method.  Yes, this is still possible, but it
effectively means every resize will _copy_ all lower-dimension data.  Some
people believe such things are okay.  We don't.

************************************************************** */


#if 0  // this is a simple test as it is shown in the book

#include <stdio.h>

int main()
{
    MultiMatrix<int, -1, 5> mm;
    mm[3][4][5][2][7] = 193;
    mm[2][2][2][2][2] = 251;
    printf("%d %d %d %d\n",
        mm[3][4][5][2][7],
        mm[2][2][2][2][2],
        mm[0][1][2][3][4],
        mm[1][2][3][2][1]);
    return 0;
}

#else  // this version of the test is more sophisticated

#include <stdio.h>

typedef MultiMatrix<int, -1, 5> MMi5;

static int get_mm5(const MMi5 &mm, int i1, int i2, int i3, int i4, int i5)
{
    return mm[i1][i2][i3][i4][i5];
}

int main()
{
    MultiMatrix<int, -1, 5> mm;
        // this uses the non-const operator[]'s version
    mm[3][4][5][2][7] = 193;
    mm[2][2][2][2][2] = 251;

        // this _still_ uses the non-const operator[]'s version
    printf("%d %d %d %d\n",
        mm[3][4][5][2][7],
        mm[2][2][2][2][2],
        mm[0][1][2][3][4],
        mm[1][2][3][2][1]);

        // and this uses the const operator[]'s version
    printf("%d %d %d %d\n",
        get_mm5(mm, 3, 4, 5, 2, 7),
        get_mm5(mm, 2, 2, 2, 2, 2),
        get_mm5(mm, 0, 1, 2, 3, 4),
        get_mm5(mm, 1, 2, 3, 2, 1));
    return 0;
}


#endif






Section test05 (10-07)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
matrix.cppC++ / 72 lines
#include <stdio.h>

template <class T, int rows, int cols>
class Matrix {
    T data[rows][cols];
public:
    Matrix();
    T& At(int row, int col) { return data[row][col]; }
    const T& At(int row, int col) const { return data[row][col]; }
    void Print(const char *fmt) const;
};

template<class T, int rows, int cols>
Matrix<T, rows, cols>::Matrix()
{
    for (int i = 0; i < rows; i++)
        for (int j = 0; j < cols; j++)
            data[i][j] = 0;
}

template<class T, int a, int b, int c>
Matrix<T, a, c> operator*(const Matrix<T, a, b> &x, const Matrix<T, b, c> &y)
{
    Matrix<T, a, c> z;
    for (int i = 0; i < a; i++)
        for (int j = 0; j < c; j++)
            for (int k = 0; k < b; k++)
                z.At(i, j) += x.At(i, k) * y.At(k, j);
    return z;
}

template<class T, int rows, int cols>
void Matrix<T, rows, cols>::Print(const char *fmt) const
{
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++)
            printf(fmt, data[i][j]);
        printf("\n");
    }
}

int main()
{
    int i, j, k;
    Matrix<int, 2, 3> x;
    Matrix<int, 3, 2> y;
    Matrix<int, 2, 2> z;
    Matrix<int, 3, 3> u;

    k = 1;
    for (i = 0; i < 2; i++)
        for (j = 0; j < 3; j++) {
            x.At(i, j) = k;
            k++;
        }

    for (i = 0; i < 3; i++)
        for (j = 0; j < 2; j++) {
            y.At(i, j) = k;
            k++;
        }

    z = x * y;
    z.Print("%3d ");

    u = y * x;
    u.Print("%3d ");

    // x * x;

    return 0;
}
multimatrix00.cppC++ / 81 lines
#include <stdio.h>

template <class T>
class Array {
    T *p;
    T init;
    unsigned int size;
public:
    Array(T in) : p(0), init(in), size(0) {}
    ~Array() { if (p) delete[] p; }
    T& operator[](unsigned int idx) {
        if (idx >= size)
            Resize(idx);
        return p[idx];
    }
    const T& operator[](unsigned int idx) const {
        return idx >= size ? init : p[idx];
    }
    int Size() const { return size; }
private:
    void Resize(unsigned int required_index) {
        unsigned int new_size = size == 0 ? 8 : size;
        while (new_size <= required_index)
            new_size *= 2;
        T *new_array = new T[new_size];
        for (unsigned int i = 0; i < new_size; i++)
            new_array[i] = i < size ? p[i] : init;
        if (p)
            delete[] p;
        p = new_array;
        size = new_size;
    }
    void operator=(const Array<T>& ref) {}
    Array(const Array<T>& ref) {}
};

template <class T, T init_val, int dim>
class MultiMatrix {
    Array<MultiMatrix<T, init_val, dim-1>*> arr;
public:
    MultiMatrix() : arr(0) {}
    ~MultiMatrix() {
        for (int i = 0; i < arr.Size(); i++)
            if (arr[i])
                delete arr[i];
    }
    MultiMatrix<T, init_val, dim-1>&
    operator[](unsigned int idx) {
        if (!arr[idx])
            arr[idx] = new MultiMatrix<T, init_val, dim-1>;
        return *arr[idx];
    }
    const MultiMatrix<T, init_val, dim-1>&
    operator[](unsigned int idx) const {
        static MultiMatrix<T, init_val, dim-1> dummy;
        return arr[idx] ? *arr[idx] : dummy;
    }

};

template <class T, T init_val>
class MultiMatrix<T, init_val, 1> {
    Array<T> arr;
public:
    MultiMatrix() : arr(init_val) {}
    T& operator[](unsigned int idx)
        { return arr[idx]; }
    const T& operator[](unsigned int idx) const
        { return arr[idx]; }
};

int main()
{
    MultiMatrix<int, -1, 5> mm;
    mm[3][4][5][2][7] = 193;
    mm[2][2][2][2][2] = 251;
    printf("%d %d %d %d\n",
           mm[3][4][5][2][7], mm[2][2][2][2][2],
           mm[0][1][2][3][4], mm[1][2][3][2][1]);
    return 0;
}
multimatrix01-inheritance.cppC++ / 82 lines
#include <stdio.h>

template <class T>
class Array {
    T *p;
    T init;
    unsigned int size;
public:
    Array(T in) : p(0), init(in), size(0) {}
    ~Array() { if (p) delete[] p; }
    T& operator[](unsigned int idx)
    {
        if (idx >= size)
            Resize(idx);
        return p[idx];
    }
    const T& operator[](unsigned int idx) const
    {
        return idx >= size ? init : p[idx];
    }
    int Size() const { return size; }
private:
    void Resize(unsigned int required_index);
    void operator=(const Array<T>&) {}
    Array(const Array<T>&) {}
};

template <class T>
void Array<T>::Resize(unsigned int required_index)
{
    unsigned int new_size = size == 0 ? 8 : size;
    while (new_size <= required_index)
        new_size *= 2;
    T *new_array = new T[new_size];
    for (unsigned int i = 0; i < new_size; i++)
        new_array[i] = i < size ? p[i] : init;
    if (p)
        delete[] p;
    p = new_array;
    size = new_size;
}

template <class T, T iv, int dim>
class MultiMatrix : public Array<MultiMatrix<T, iv, dim-1>*> {
    typedef MultiMatrix<T, iv, dim-1> Sub;
    typedef Array<Sub*> Base;
public:
    MultiMatrix() : Base(0) {}
    ~MultiMatrix() {
        for (int i = 0; i < Base::Size(); i++)
            delete Base::operator[](i);
    }
    Sub& operator[](unsigned int idx) {
        Sub*& slot = Base::operator[](idx);
        if (!slot)
            slot = new Sub;
        return *slot;
    }
    const Sub& operator[](unsigned int idx) const {
        static Sub dummy;
        Sub *slot = Base::operator[](idx);
        return slot ? *slot : dummy;
    }
};

template <class T, T iv>
class MultiMatrix<T, iv, 1> : public Array<T> {
public:
    MultiMatrix() : Array<T>(iv) {}
};

int main()
{
    MultiMatrix<int, -1, 5> mm;
    const MultiMatrix<int, -1, 5>& c = mm;
    mm[3][4][5][2][7] = 193;
    mm[2][2][2][2][2] = 251;
    printf("%d %d %d %d\n",
           mm[3][4][5][2][7], mm[2][2][2][2][2],
           c[0][1][2][3][4], c[1][2][3][2][1]);
    return 0;
}
multimatrix02.cppC++ / 72 lines
#include <stdio.h>

template <class T>
class Array {
    T *p;
    T init;
    unsigned int size;
public:
    Array(T in) : p(0), init(in), size(0) {}
    ~Array() { if (p) delete[] p; }
    T& operator[](unsigned int idx) {
        if (idx >= size)
            Resize(idx);
        return p[idx];
    }
    const T& operator[](unsigned int idx) const {
        return idx >= size ? init : p[idx];
    }
    int Size() const { return size; }
private:
    void Resize(unsigned int required_index) {
        unsigned int new_size = size == 0 ? 8 : size;
        while (new_size <= required_index)
            new_size *= 2;
        T *new_array = new T[new_size];
        for (unsigned int i = 0; i < new_size; i++)
            new_array[i] = i < size ? p[i] : init;
        if (p)
            delete[] p;
        p = new_array;
        size = new_size;
    }
    void operator=(const Array<T>& ref) {}
    Array(const Array<T>& ref) {}
};

template <class T, T init_val, int dim>
class MultiMatrix {
    Array<MultiMatrix<T, init_val, dim-1>*> arr;
public:
    MultiMatrix() : arr(0) {}
    ~MultiMatrix() {
        for (int i = 0; i < arr.Size(); i++)
            if (arr[i])
                delete arr[i];
    }
    MultiMatrix<T, init_val, dim-1>&
    operator[](unsigned int idx) {
        if (!arr[idx])
            arr[idx] = new MultiMatrix<T, init_val, dim-1>;
        return *arr[idx];
    }
    const MultiMatrix<T, init_val, dim-1>&
    operator[](unsigned int idx) const {
        static MultiMatrix<T, init_val, dim-1> dummy;
        return arr[idx] ? *arr[idx] : dummy;
    }

};

template <class T, T init_val>
class MultiMatrix<T, init_val, 1> : public Array<T> {
public:
    MultiMatrix() : Array<T>(init_val) {}
};

int main()
{
    MultiMatrix<int, -1, 3> mm;
    mm[0][1][2] = 123;
    return 0;
}
multimatrix03.cppC++ / 89 lines
#include <stdio.h>

template <class T>
class Array {
    T *p;
    T init;
    unsigned int size;
public:
    Array(T in) : p(0), init(in), size(0) {}
    ~Array() { if (p) delete[] p; }
    T& operator[](unsigned int idx) {
        if (idx >= size)
            Resize(idx);
        return p[idx];
    }
    const T& operator[](unsigned int idx) const {
        return idx >= size ? init : p[idx];
    }
    unsigned int Size() const { return size; }
private:
    void Resize(unsigned int required_index) {
        unsigned int new_size = size == 0 ? 8 : size;
        while (new_size <= required_index)
            new_size *= 2;
        T *new_array = new T[new_size];
        for (unsigned int i = 0; i < new_size; i++)
            new_array[i] = i < size ? p[i] : init;
        if (p)
            delete[] p;
        p = new_array;
        size = new_size;
    }
    void operator=(const Array<T>& ref) {}
    Array(const Array<T>& ref) {}
};

template <class T, T init_val, int dim>
class MultiMatrix {
    Array<MultiMatrix<T, init_val, dim-1>*> arr;
public:
    MultiMatrix() : arr(0) {}
    ~MultiMatrix() {
        for (unsigned int i = 0; i < arr.Size(); i++)
            if (arr[i])
                delete arr[i];
    }
    MultiMatrix<T, init_val, dim-1>&
    operator[](unsigned int idx) {
        if (!arr[idx])
            arr[idx] = new MultiMatrix<T, init_val, dim-1>;
        return *arr[idx];
    }
    const MultiMatrix<T, init_val, dim-1>&
    operator[](unsigned int idx) const {
        static MultiMatrix<T, init_val, dim-1> dummy;
        return arr[idx] ? *arr[idx] : dummy;
    }
    unsigned long Cells() const {
        unsigned long total = 0;
        for (unsigned int i = 0; i < arr.Size(); i++)
            if (arr[i])
                total += arr[i]->Cells();
        return total;
    }
};

template <class T, T init_val>
class MultiMatrix<T, init_val, 1> : public Array<T> {
public:
    MultiMatrix() : Array<T>(init_val) {}
    unsigned long Cells() const { return this->Size(); }
};

int main()
{
    MultiMatrix<int, -1, 3> m;
    const MultiMatrix<int, -1, 3>& c = m;
    printf("%lu\n", m.Cells());
    m[0][0][0] = 1;
    m[0][0][20] = 2;
    m[0][5][3] = 3;
    m[9][0][0] = 4;
    printf("%lu\n", m.Cells());
    int x = c[4][4][4];
    printf("%d %lu\n", x, m.Cells());
    int y = m[4][4][4];
    printf("%d %lu\n", y, m.Cells());
    return 0;
}
multimatrix04.cppC++ / 75 lines
#include <stdio.h>

template <class T>
class Array {
    T *p;
    T init;
    unsigned int size;
public:
    Array(T in) : p(0), init(in), size(0) {}
    ~Array() { if (p) delete[] p; }
    T& operator[](unsigned int idx) {
        if (idx >= size)
            Resize(idx);
        return p[idx];
    }
    const T& operator[](unsigned int idx) const {
        return idx >= size ? init : p[idx];
    }
    unsigned int Size() const { return size; }
private:
    void Resize(unsigned int required_index) {
        unsigned int new_size = size == 0 ? 8 : size;
        while (new_size <= required_index)
            new_size *= 2;
        T *new_array = new T[new_size];
        for (unsigned int i = 0; i < new_size; i++)
            new_array[i] = i < size ? p[i] : init;
        if (p)
            delete[] p;
        p = new_array;
        size = new_size;
    }
    void operator=(const Array<T>& ref) {}
    Array(const Array<T>& ref) {}
};

template <class T, T init_val, int dim>
class MultiMatrix {
    typedef MultiMatrix<T, init_val, dim-1> Sub;
    Array<Sub*> arr;
public:
    MultiMatrix() : arr(0) {}
    ~MultiMatrix() {
        for (unsigned int i = 0; i < arr.Size(); i++)
            delete arr[i];
    }
    Sub& operator[](unsigned int idx) {
        if (!arr[idx])
            arr[idx] = new Sub;
        return *arr[idx];
    }
    const Sub& operator[](unsigned int idx) const {
        static Sub dummy;
        return arr[idx] ? *arr[idx] : dummy;
    }
};

template <class T, T init_val>
class MultiMatrix<T, init_val, 1> : public Array<T> {
public:
    MultiMatrix() : Array<T>(init_val) {}
};

int main()
{
    MultiMatrix<int, -1, 3> m;
    const MultiMatrix<int, -1, 3>& c = m;
    m[0][0][0] = 1;
    m[0][0][20] = 2;
    m[0][5][3] = 3;
    m[9][0][0] = 4;
    printf("%d %d %d %d\n", m[0][0][0], m[0][0][20], m[0][5][3], m[9][0][0]);
    printf("%d %d\n", c[4][4][4], m[4][4][4]);
    return 0;
}
multimatrix05.cppC++ / 100 lines
#include <stdio.h>

template <class T>
class Array {
    T *p;
    T init;
    unsigned int size;
public:
    Array(T in) : p(0), init(in), size(0) {}
    ~Array() { if (p) delete[] p; }
    T& operator[](unsigned int idx);
    const T& operator[](unsigned int idx) const;
    unsigned int Size() const { return size; }
private:
    void Resize(unsigned int required_index);
    void operator=(const Array<T>& ref) {}
    Array(const Array<T>& ref) {}
};

template <class T, T init_val, int dim>
class MultiMatrix {
    Array<MultiMatrix<T, init_val, dim-1>*> arr;
public:
    MultiMatrix() : arr(0) {}
    ~MultiMatrix();
    MultiMatrix<T, init_val, dim-1>& operator[](unsigned int idx);
    const MultiMatrix<T, init_val, dim-1>& operator[](unsigned int idx) const;
};

template <class T, T init_val>
class MultiMatrix<T, init_val, 1> : public Array<T> {
public:
    MultiMatrix() : Array<T>(init_val) {}
};

template <class T>
T& Array<T>::operator[](unsigned int idx)
{
    if (idx >= size)
        Resize(idx);
    return p[idx];
}

template <class T>
const T& Array<T>::operator[](unsigned int idx) const
{
    return idx >= size ? init : p[idx];
}

template <class T>
void Array<T>::Resize(unsigned int required_index)
{
    unsigned int new_size = size == 0 ? 8 : size;
    while (new_size <= required_index)
        new_size *= 2;
    T *new_array = new T[new_size];
    for (unsigned int i = 0; i < new_size; i++)
        new_array[i] = i < size ? p[i] : init;
    if (p)
        delete[] p;
    p = new_array;
    size = new_size;
}

template <class T, T init_val, int dim>
MultiMatrix<T, init_val, dim>::~MultiMatrix()
{
    for (unsigned int i = 0; i < arr.Size(); i++)
        delete arr[i];
}

template <class T, T init_val, int dim>
MultiMatrix<T, init_val, dim-1>&
MultiMatrix<T, init_val, dim>::operator[](unsigned int idx)
{
    if (!arr[idx])
        arr[idx] = new MultiMatrix<T, init_val, dim-1>;
    return *arr[idx];
}

template <class T, T init_val, int dim>
const MultiMatrix<T, init_val, dim-1>&
MultiMatrix<T, init_val, dim>::operator[](unsigned int idx) const
{
    static MultiMatrix<T, init_val, dim-1> dummy;
    return arr[idx] ? *arr[idx] : dummy;
}

int main()
{
    MultiMatrix<int, -1, 3> m;
    const MultiMatrix<int, -1, 3>& c = m;
    m[0][0][0] = 1;
    m[0][0][20] = 2;
    m[0][5][3] = 3;
    m[9][0][0] = 4;
    printf("%d %d %d %d\n", m[0][0][0], m[0][0][20], m[0][5][3], m[9][0][0]);
    printf("%d %d\n", c[4][4][4], m[4][4][4]);
    return 0;
}
multimatrix06.cppC++ / 98 lines
#include <stdio.h>

template <class T>
class Array {
    T *p;
    T init;
    unsigned int size;
public:
    Array(T in) : p(0), init(in), size(0) {}
    ~Array() { if (p) delete[] p; }
    T& operator[](unsigned int idx);
    const T& operator[](unsigned int idx) const;
    unsigned int Size() const { return size; }
private:
    void Resize(unsigned int required_index);
    void operator=(const Array<T>& ref) {}
    Array(const Array<T>& ref) {}
};

template <class T, T init_val, int dim>
class MultiMatrix {
    Array<MultiMatrix<T, init_val, dim-1>*> arr;
public:
    MultiMatrix() : arr(0) {}
    ~MultiMatrix();
    MultiMatrix<T, init_val, dim-1>& operator[](unsigned int idx);
    const MultiMatrix<T, init_val, dim-1>& operator[](unsigned int idx) const;
};

template <class T, T init_val>
class MultiMatrix<T, init_val, 1> : public Array<T> {
public:
    MultiMatrix() : Array<T>(init_val) {}
};

template <class T>
T& Array<T>::operator[](unsigned int idx)
{
    if (idx >= size)
        Resize(idx);
    return p[idx];
}

template <class T>
const T& Array<T>::operator[](unsigned int idx) const
{
    return idx >= size ? init : p[idx];
}

template <class T>
void Array<T>::Resize(unsigned int required_index)
{
    unsigned int new_size = size == 0 ? 8 : size;
    while (new_size <= required_index)
        new_size *= 2;
    T *new_array = new T[new_size];
    for (unsigned int i = 0; i < new_size; i++)
        new_array[i] = i < size ? p[i] : init;
    if (p)
        delete[] p;
    p = new_array;
    size = new_size;
}

template <class T, T init_val, int dim>
MultiMatrix<T, init_val, dim>::~MultiMatrix()
{
    for (unsigned int i = 0; i < arr.Size(); i++)
        delete arr[i];
}

template <class T, T init_val, int dim>
MultiMatrix<T, init_val, dim-1>&
MultiMatrix<T, init_val, dim>::operator[](unsigned int idx)
{
    if (!arr[idx])
        arr[idx] = new MultiMatrix<T, init_val, dim-1>;
    return *arr[idx];
}

template <class T, T init_val, int dim>
const MultiMatrix<T, init_val, dim-1>&
MultiMatrix<T, init_val, dim>::operator[](unsigned int idx) const
{
    static MultiMatrix<T, init_val, dim-1> dummy;
    return arr[idx] ? *arr[idx] : dummy;
    // return *arr[idx];
}

int main()
{
    MultiMatrix<int, -1, 3> m;
    const MultiMatrix<int, -1, 3>& c = m;
    m[0][0][0] = 1;
    printf("%d\n", c[0][0][0]);          /* exists */
    printf("%d\n", c[4][4][4]);          /* was never created */
    return 0;
}
multimatrix07-live.cppC++ / 98 lines
#include <stdio.h>

template <class T>
class Array {
    T *p;
    T init;
    unsigned int size;
public:
    Array(const T& in) : p(0), init(in), size(0) {}
    Array(const Array<T>& other);               /* allowed again */
    ~Array() { delete[] p; }
    Array<T>& operator=(const Array<T>& other); /* allowed again */
    T& operator[](unsigned int idx);
    const T& operator[](unsigned int idx) const;
    unsigned int Size() const { return size; }
private:
    void Resize(unsigned int required_index);
};

template <class T>
Array<T>::Array(const Array<T>& other) : p(0), init(other.init), size(0)
{
    *this = other;
}

/* a deep copy: every element is assigned, and an element may be a matrix */
template <class T>
Array<T>& Array<T>::operator=(const Array<T>& other)
{
    if (this == &other)
        return *this;
    T *copy = other.size ? new T[other.size] : 0;
    for (unsigned int i = 0; i < other.size; i++)
        copy[i] = other.p[i];
    delete[] p;
    p = copy;
    init = other.init;
    size = other.size;
    return *this;
}

template <class T>
T& Array<T>::operator[](unsigned int idx)
{
    if (idx >= size)
        Resize(idx);
    return p[idx];
}

template <class T>
const T& Array<T>::operator[](unsigned int idx) const
{
    return idx >= size ? init : p[idx];
}

template <class T>
void Array<T>::Resize(unsigned int required_index)
{
    unsigned int new_size = size == 0 ? 8 : size;
    while (new_size <= required_index)
        new_size *= 2;
    T *new_array = new T[new_size];             /* default constructor */
    for (unsigned int i = 0; i < new_size; i++)
        new_array[i] = i < size ? p[i] : init;  /* assignment */
    delete[] p;
    p = new_array;
    size = new_size;
}

template <class T, T init_val, int dim>
class MultiMatrix {
    Array<MultiMatrix<T, init_val, dim-1> > arr;
public:
    MultiMatrix() : arr(MultiMatrix<T, init_val, dim-1>()) {}
    MultiMatrix<T, init_val, dim-1>& operator[](unsigned int idx)
        { return arr[idx]; }
    const MultiMatrix<T, init_val, dim-1>& operator[](unsigned int idx) const
        { return arr[idx]; }
};

template <class T, T init_val>
class MultiMatrix<T, init_val, 1> : public Array<T> {
public:
    MultiMatrix() : Array<T>(init_val) {}
};

int main()
{
    MultiMatrix<int, -1, 3> m;
    const MultiMatrix<int, -1, 3>& c = m;

    for (int j = 0; j < 1000; j++)
        m[0][j][0] = j;                 /* 1000 rows inside m[0] */
    m[8][0][0] = 5;                     /* the top level grows: 8 -> 16 */
    printf("%d %d %d %d\n", c[0][0][0], c[0][999][0], c[8][0][0],
           c[3][3][3]);
    return 0;
}
multimatrix08.cppC++ / 69 lines
#include <stdio.h>

template <class T>
class Array {
    T *p;
    T init;
    unsigned int size;
public:
    Array(T in) : p(0), init(in), size(0) {}
    ~Array() { if (p) delete[] p; }
    T& operator[](unsigned int idx)
        { if (idx >= size) Resize(idx); return p[idx]; }
    const T& operator[](unsigned int idx) const
        { return idx >= size ? init : p[idx]; }
    int Size() const { return size; }
private:
    void Resize(unsigned int required_index) {
        unsigned int new_size = size == 0 ? 8 : size;
        while (new_size <= required_index)
            new_size *= 2;
        T *new_array = new T[new_size];
        for (unsigned int i = 0; i < new_size; i++)
            new_array[i] = i < size ? p[i] : init;
        if (p)
            delete[] p;
        p = new_array;
        size = new_size;
    }
    void operator=(const Array<T>& ref) {}
    Array(const Array<T>& ref) {}
};

template <class T, T init_val, int dim>
class MultiMatrix {
    Array<MultiMatrix<T, init_val, dim-1>*> arr;
public:
    MultiMatrix() : arr(0) {}
    ~MultiMatrix()
        { for (int i = 0; i < arr.Size(); i++) delete arr[i]; }
    MultiMatrix<T, init_val, dim-1>&
    operator[](unsigned int idx) {
        if (!arr[idx])
            arr[idx] = new MultiMatrix<T, init_val, dim-1>;
        return *arr[idx];
    }
    const MultiMatrix<T, init_val, dim-1>&
    operator[](unsigned int idx) const {
        static MultiMatrix<T, init_val, dim-1> dummy;
        return arr[idx] ? *arr[idx] : dummy;
    }

};

template <class T, T init_val>
class MultiMatrix<T, init_val, 1> : public Array<T> {
public:
    MultiMatrix() : Array<T>(init_val) {}
};

int main()
{
    MultiMatrix<int, -1, 5> mm;
    mm[3][4][5][2][7] = 193;
    mm[2][2][2][2][2] = 251;
    printf("%d %d %d %d\n",
           mm[3][4][5][2][7], mm[2][2][2][2][2],
           mm[0][1][2][3][4], mm[1][2][3][2][1]);
    return 0;
}
multimatrix09-comparisson.cppC++ / 182 lines
/* three.cpp: three ways to build MultiMatrix on top of Array
 *
 *   -DKIND=1   a field with pointers to the smaller matrices (the book)
 *   -DKIND=2   inherited from the array of pointers
 *   -DKIND=3   a field with the smaller matrices themselves ("live")
 *   -DGROW     adds one assignment that makes the top level grow
 *   -DTIME     runs the time test instead of the allocation test
 *
 *   g++ -Wall -Wextra -ansi -pedantic -DKIND=1 three.cpp -o three
 *   valgrind ./three 2>&1 | grep 'heap usage'
 *
 *   g++ -Wall -Wextra -ansi -pedantic -O2 -DKIND=1 -DTIME three.cpp -o three
 *   ./three
 */
#include <stdio.h>
#include <time.h>

#ifndef KIND
#define KIND 1
#endif

template <class T>
class Array {
    T *p;
    T init;
    unsigned int size;
public:
    Array(const T& in) : p(0), init(in), size(0) {}
    ~Array() { delete[] p; }
    T& operator[](unsigned int idx) {
        if (idx >= size)
            Resize(idx);
        return p[idx];
    }
    const T& operator[](unsigned int idx) const {
        return idx >= size ? init : p[idx];
    }
    unsigned int Size() const { return size; }
#if KIND == 3                           /* live: copying must really work */
    Array(const Array<T>& other) : p(0), init(other.init), size(0)
        { *this = other; }
    Array<T>& operator=(const Array<T>& other) {
        if (this == &other)
            return *this;
        T *copy = other.size ? new T[other.size] : 0;
        for (unsigned int i = 0; i < other.size; i++)
            copy[i] = other.p[i];
        delete[] p;
        p = copy;
        init = other.init;
        size = other.size;
        return *this;
    }
#endif
private:
    void Resize(unsigned int required_index) {
        unsigned int new_size = size == 0 ? 8 : size;
        while (new_size <= required_index)
            new_size *= 2;
        T *new_array = new T[new_size];
        for (unsigned int i = 0; i < new_size; i++)
            new_array[i] = i < size ? p[i] : init;
        delete[] p;
        p = new_array;
        size = new_size;
    }
#if KIND != 3                           /* pointers: copying stays forbidden */
    void operator=(const Array<T>&) {}
    Array(const Array<T>&) {}
#endif
};

#if KIND == 1           /* ---- a field with pointers (the book) ---- */

template <class T, T init_val, int dim>
class MultiMatrix {
    typedef MultiMatrix<T, init_val, dim-1> Sub;
    Array<Sub*> arr;
public:
    MultiMatrix() : arr(0) {}
    ~MultiMatrix() {
        for (unsigned int i = 0; i < arr.Size(); i++)
            delete arr[i];
    }
    Sub& operator[](unsigned int idx) {
        if (!arr[idx])
            arr[idx] = new Sub;
        return *arr[idx];
    }
    const Sub& operator[](unsigned int idx) const {
        static Sub dummy;
        return arr[idx] ? *arr[idx] : dummy;
    }
};

#elif KIND == 2         /* ---- inherited from the array of pointers ---- */

template <class T, T init_val, int dim>
class MultiMatrix : public Array<MultiMatrix<T, init_val, dim-1>*> {
    typedef MultiMatrix<T, init_val, dim-1> Sub;
    typedef Array<Sub*> Base;
public:
    MultiMatrix() : Base(0) {}
    ~MultiMatrix() {
        for (unsigned int i = 0; i < Base::Size(); i++)
            delete Base::operator[](i);
    }
    Sub& operator[](unsigned int idx) {
        if (!Base::operator[](idx))
            Base::operator[](idx) = new Sub;
        return *Base::operator[](idx);
    }
    const Sub& operator[](unsigned int idx) const {
        static Sub dummy;
        return Base::operator[](idx) ? *Base::operator[](idx) : dummy;
    }
};

#else                   /* ---- a field with the matrices themselves ---- */

template <class T, T init_val, int dim>
class MultiMatrix {
    typedef MultiMatrix<T, init_val, dim-1> Sub;
    Array<Sub> arr;
public:
    MultiMatrix() : arr(Sub()) {}
    Sub& operator[](unsigned int idx) { return arr[idx]; }
    const Sub& operator[](unsigned int idx) const { return arr[idx]; }
};

#endif

template <class T, T init_val>
class MultiMatrix<T, init_val, 1> : public Array<T> {
public:
    MultiMatrix() : Array<T>(init_val) {}
};

/* count the allocations of this one with valgrind, with and without GROW */
void alloc_test()
{
    MultiMatrix<int, -1, 3> m;
    const MultiMatrix<int, -1, 3>& c = m;

    for (int j = 0; j < 1000; j++)
        m[0][j][0] = j;                 /* 1000 rows inside m[0] */
#ifdef GROW
    m[8][0][0] = 5;                     /* the top level grows: 8 -> 16 */
#endif
    printf("%d %d %d %d\n", c[0][0][0], c[0][999][0], c[8][0][0],
           c[3][3][3]);
}

/* ten growths of the top level, with side x side ints stored below it */
void time_test(int side)
{
    MultiMatrix<int, -1, 3> m;
    clock_t start, mid, end;

    start = clock();
    for (int j = 0; j < side; j++)
        for (int k = 0; k < side; k++)
            m[0][j][k] = j + k;
    mid = clock();
    for (int i = 8; i <= 4096; i *= 2)
        m[i][0][0] = i;                 /* 8 -> 16 -> ... -> 8192 slots */
    end = clock();
    printf("fill %d x %d: %.1f ms\n", side, side,
           (mid - start) * 1000.0 / CLOCKS_PER_SEC);
    printf("ten growths:      %.1f ms\n",
           (end - mid) * 1000.0 / CLOCKS_PER_SEC);
}

int main()
{
#ifdef TIME
    time_test(2000);
#else
    alloc_test();
#endif
    return 0;
}
params.cppC++ / 88 lines
#include <stdio.h>

/* ---- 1. a constant of any integer type ---- */

template <char c, unsigned long n>
void line()
{
    for (unsigned long i = 0; i < n; i++)
        putchar(c);
    putchar('\n');
}

template <bool loud>
void say(const char *msg)
{
    printf(loud ? "%s!!!\n" : "%s\n", msg);
}

/* ---- 2. ... known at compile time ---- */

const int width = 4;
enum { height = 3 };

/* ---- 3. the address of a global variable: &var ---- */

int apples = 0;
int pears = 0;

template <int *counter>
struct Counted {
    Counted() { ++*counter; }
};

/* ---- 4. the address of a function: &f or just f ---- */

void to_stdout(const char *msg) { printf("stdout: %s\n", msg); }
void to_stderr(const char *msg) { fprintf(stderr, "stderr: %s\n", msg); }

template <void (*report)(const char *)>
void work()
{
    report("done");
}

/* ---- for 5 and 7 ---- */

int numbers[3] = { 10, 20, 30 };
int *apples_ptr = &apples;
char greeting[] = "hello";

template <char *name>
void hello()
{
    printf("%s\n", name);
}

int main()
{
    line<'-', 10>();                    /* 1: char and unsigned long */
    say<true>("one");                   /* 1: bool */
    say<false>("two");

    line<'=', width * height + 1>();    /* 2: an expression of constants */
    line<'.', sizeof(int)>();

    Counted<&apples> a1, a2;            /* 3: &var */
    Counted<&pears> p1;
    printf("%d %d\n", apples, pears);

    work<&to_stdout>();                 /* 4: &f */
    work<to_stderr>();                  /* 4: f */

    hello<greeting>();                  /* 7: what works instead */
#if BAD == 1
    int n = 10;
    line<'-', n>();                     /* 2: not known at compile time */
#elif BAD == 2
    Counted<&numbers[1]> bad;           /* 5: a complex address expression */
#elif BAD == 3
    Counted<apples_ptr> bad;            /* 5: the value of a pointer */
#elif BAD == 4
    int local = 0;
    Counted<&local> bad;                /* 6: a local variable */
#elif BAD == 5
    hello<"hello">();                   /* 7: a string literal */
#endif
    return 0;
}
power.cppC++ / 21 lines
#include <stdio.h>

template <int base, int exp>
struct Power {
    static int value;
    Power() { value = base * Power<base, exp-1>::value; }
};

template <int base>
struct Power<base, 0> {
    static int value;
};

template <int base>
int Power<base, 0>::value = 1;

int main()
{
    // printf("%d\n", Power<2, 10>::value);
    return 0;
}
power01.cppC++ / 23 lines
#include <stdio.h>

template <int base, int exp>
struct Power {
    static int value;
};

template <int base, int exp>
int Power<base, exp>::value = base * Power<base, exp-1>::value;

template <int base>
struct Power<base, 0> {
    static int value;
};

template <int base>
int Power<base, 0>::value = 1;

int main()
{
    printf("%d\n", Power<2, 10>::value);
    return 0;
}
power02.cppC++ / 25 lines
#include <stdio.h>

template <int base, int exp>
struct Power {
    static int value;
};

template <int base, int exp>
int Power<base, exp>::value = base * Power<base, exp-1>::value;

template <int base>
struct Power<base, 0> {
    static int value;
};

template <int base>
int Power<base, 0>::value = 1;

int main()
{
    // int table[Power<2, 5>::value];
    // printf("%d %d %d %d\n", (int)Power<2, 10>::value, (int)Power<3, 4>::value,
    //        (int)Power<7, 0>::value, (int)(sizeof(table) / sizeof(*table)));
    return 0;
}
power03.cppC++ / 19 lines
#include <stdio.h>

template <int base, int exp>
struct Power {
    enum { value = base * Power<base, exp-1>::value };
};

template <int base>
struct Power<base, 0> {
    enum { value = 1 };
};

int main()
{
    int table[Power<2, 5>::value];
    printf("%d %d %d %d\n", (int)Power<2, 10>::value, (int)Power<3, 4>::value,
           (int)Power<7, 0>::value, (int)(sizeof(table) / sizeof(*table)));
    return 0;
}
resize_array.cppC++ / 76 lines
#include <stdio.h>

typedef void (*funcptr)(unsigned int, unsigned int);

static unsigned int resizes = 0;

template <class T, funcptr F>
class Array {
    T *p;
    T init;
    unsigned int size;
public:
    Array(T in) : p(0), init(in), size(0) {}
    ~Array() { if (p) delete[] p; }
    T& operator[](unsigned int idx);
    const T& operator[](unsigned int idx) const;
    unsigned int Size() const { return size; }
private:
    void Resize(unsigned int required_index);
    void operator=(const Array<T, F>& ref) {}
    Array(const Array<T, F>& ref) {}
};

template <class T, funcptr F>
T& Array<T, F>::operator[](unsigned int idx)
{
    if (idx >= size)
        Resize(idx);
    return p[idx];
}

template <class T, funcptr F>
const T& Array<T, F>::operator[](unsigned int idx) const
{
    return idx >= size ? init : p[idx];
}

template <class T, funcptr F>
void Array<T, F>::Resize(unsigned int required_index)
{
    unsigned int new_size = size == 0 ? 8 : size;
    while (new_size <= required_index)
        new_size *= 2;
    T *new_array = new T[new_size];
    for (unsigned int i = 0; i < new_size; i++)
        new_array[i] = i < size ? p[i] : init;
    if (p)
        delete[] p;
    p = new_array;
    (*F)(size, new_size);
    size = new_size;
}

void report(unsigned int old_size, unsigned int new_size)
{
    printf("resize: %u -> %u\n", old_size, new_size);
}

void count(unsigned int old_size, unsigned int new_size)
{
    resizes++;
}

int main()
{
    Array<int, &report> a(0);
    Array<int, count> b(0);
    a[0] = 1;
    a[7] = 1;
    a[8] = 1;
    a[100] = 1;
    for (int i = 0; i < 1000; i++)
        b[i] = i;
    printf("%d\n", resizes);
    return 0;
}
stack.cppC++ / 60 lines
#include <stdio.h>

template <class T, int cap>
class Stack {
    T data[cap];
    int len;
public:
    Stack() : len(0) {}
    bool Push(const T& d);
    bool Pop(T& d);
    bool Empty() const { return len == 0; }
};

template<class T, int cap>
bool Stack<T, cap>::Push(const T& d)
{
    if (len < cap) {
        data[len] = d;
        len++;
        return true;
    } else
        return false;
}

template<class T, int cap>
bool Stack<T, cap>::Pop(T& d)
{
    if (len > 0) {
        len--;
        d = data[len];
        return true;
    } else
        return false;
}

int main()
{
    int i;
    bool ok = true;
    Stack<int, 4> s;

    for (i = 1; i <= 6; i++) {
        ok = s.Push(i);
        printf("%d", ok);
    }
    printf("\n");

    while ((ok = s.Pop(i)))
        printf("%d ", i);
    printf("\n");

    Stack<int, 4> small;
    Stack<int, 8> big;
    printf("%ld %ld\n", sizeof(small), sizeof(big));

    // big = small;
    // const int n = 4; Stack<int, n> t;

    return 0;
}

10.8 Returning to programming paradigms

The language mechanisms can now be grouped by the models they support: object messages, abstract values, exceptions, and generic definitions. A feature's presence does not prescribe a single way to organize the program.

Detailed notes - 10.8: Returning to programming paradigms

1

organize the language mechanisms just studied by the ways of thinking they support

10.8.1 C++ and the range of paradigms

C++ strongly encourages imperative programming while providing direct support for ADTs, OOP, exceptions, and templates. Other paradigms may remain expressible with more effort; practical encouragement differs from requiring or prohibiting a style.

Detailed notes - 10.8.1: C++ and the range of paradigms

1

apply the earlier seven-level scale of language/paradigm compatibility

2

the author argues that C++ strictly imposes few programming styles

  • considers compilation its assumed execution model
  • this is the book's model, not a requirement to use a particular ahead-of-time implementation for every C++ environment

3

C++ strongly encourages imperative programming in practice

  • avoiding assignments entirely is possible but often inconvenient

4

the author classifies several paradigms as actively rewarded

  • OOP and abstract data types
  • exceptions
  • generic programming through templates

5

ordinary preprocessing is supported, though not preferred in this account

6

many additional paradigms can be expressed with suitable effort or libraries

  • no complete list of paradigms establishes an exhaustive answer

7

the author gives no definite example of an entirely prohibited paradigm

  • that is not proof that all paradigms fit equally well

10.8.2 OOP and ADTs

ADTs emphasize abstract values and their creation, conversion, copying, and operations; OOP emphasizes objects responding through interfaces. Access control and lifetime mechanisms serve both, while the book's fuller object model adds inheritance and virtual dispatch.

The same operation, as a message to an object and as an ADT operation:

class Complex {
    double re, im;
public:
    Complex(double a_re = 0, double a_im = 0) { re = a_re; im = a_im; }
    Complex Plus(const Complex &b) const        // a asks itself: a.Plus(b)
        { return Complex(re + b.re, im + b.im); }
    friend Complex operator+(const Complex &a, const Complex &b);
};

Complex operator+(const Complex &a, const Complex &b)     // a + b
{
    return Complex(a.re + b.re, a.im + b.im);
}
Detailed notes - 10.8.2: OOP and ADTs

1

distinguish support for objects/messages from support for abstract values

2

shared mechanisms:

  • access control, constructors and destructors

ADT-oriented mechanisms in the author's classification:

  • control over default construction, conversion, copying and assignment
  • operator notation for user-defined values

these help an abstract type behave naturally beside built-in types

3

methods make the object/message interpretation explicit

  • ADT operations could instead be appropriately privileged free functions
  • the author considers methods important when teaching OOP thinking

4

the author's fuller OOP model adds inheritance and virtual dispatch

  • related objects respond through a shared message interface
  • this classification explains intended uses; features can participate in designs that mix several paradigms
Tests & experiments (2 files) - 10.8.2: OOP and ADTs
Section test02 (10-08)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
adt.cppC++ / 67 lines
/* kinds.cpp: what the three kinds of constructors are for
 *   g++ -Wall -Wextra -ansi -pedantic kinds.cpp -o kinds && ./kinds
 */
#include <stdio.h>

/* ---- an abstract data type: a value, like double ---- */

class Complex {
    double re, im;
public:
    Complex() : re(0), im(0) { printf("  default\n"); }
    Complex(double r) : re(r), im(0) { printf("  conversion\n"); }
    Complex(const Complex& c) : re(c.re), im(c.im) { printf("  copy\n"); }
    Complex(double r, double i) : re(r), im(i) {}
    double Re() const { return re; }
    double Im() const { return im; }
};

Complex operator+(const Complex& a, const Complex& b)
{
    return Complex(a.Re() + b.Re(), a.Im() + b.Im());
}

double modulus2(Complex c)              /* by value */
{
    return c.Re() * c.Re() + c.Im() * c.Im();
}

/* ---- objects in the OOP sense ---- */

class Animal {
public:
    virtual ~Animal() {}
    virtual const char *Voice() const { return "..."; }
};

class Dog : public Animal {
public:
    virtual const char *Voice() const { return "woof"; }
};

void by_address(const Animal& a) { printf("  %s\n", a.Voice()); }
void by_value(Animal a) { printf("  %s\n", a.Voice()); }

int main()
{
    printf("Complex a;\n");
    Complex a;
    printf("Complex b = 2.5;\n");
    Complex b = 2.5;
    printf("Complex c = b;\n");
    Complex c = b;
    printf("Complex z[3];\n");
    Complex z[3];
    printf("b + 1\n");
    Complex d = b + 1;
    printf("modulus2(d)\n");
    double m = modulus2(d);
    printf("%g %g %g\n", a.Re() + c.Re() + z[0].Re(), d.Re(), m);

    Dog dog;
    printf("by_address(dog)\n");
    by_address(dog);
    printf("by_value(dog)\n");
    by_value(dog);
    return 0;
}

10.8.3 Polymorphism without mystification

Polymorphism can describe accepting several types or selecting type-dependent operations. The useful distinctions are when selection occurs and how cases are expressed: runtime virtual dispatch, explicit overloads, or type-parameterized templates.

The three mechanisms of this chapter, by when the choice is made:

// ad hoc static polymorphism: overloads chosen during compilation
void print(int n);
void print(const char *s);

// parametric static polymorphism: one template, many types
template <class T>
T max_of(T a, T b)
{
    return a < b ? b : a;
}

// dynamic polymorphism: chosen at run time by the object's actual type
class Shape {
public:
    virtual ~Shape() {}
    virtual double Area() const = 0;
};

double total_area(Shape **shapes, int n)
{
    double sum = 0;
    for (int i = 0; i < n; i++)
        sum += shapes[i]->Area();
    return sum;
}
Detailed notes - 10.8.3: Polymorphism without mystification

1

two common descriptions of polymorphism:

  • one operation accepts several types
  • one notation selects different operations according to type

2

  • illustrates the second description naturally
  • integer addition, floating-point addition, matrix addition and string concatenation may have unrelated implementations

3

the narrower operation-selection definition omits ordinary base conversion

  • a derived object can satisfy a base interface without changing the implementation of a non-virtual operation

4

the author accepts both uses of polymorphism

  • interpret the term using the surrounding technical context

5

crucial distinction: when selection occurs

  • static polymorphism: selected during compilation
  • dynamic polymorphism: selection depends on runtime information

6

virtual methods provide the chapter's runtime dispatch mechanism

  • the actual object's type determines the applicable override

7

ordinary function/operator overloading is ad hoc static polymorphism

  • explicitly supplied implementations cover particular argument cases
  • adding a new case requires an appropriate declaration or conversion

8

templates provide parametric static polymorphism

  • one definition accepts an open set of suitable argument types
  • the type-dependent operations determine which types are suitable

9

base pointer/reference conversion also belongs to the author's static category when using his broader definition of polymorphism

10.8.4 Inheritance as set inclusion

A substitutable subclass represents a subset of the objects described by its superclass. Physical containment runs the other way: the derived object's storage contains its base subobject, so conceptual classification and layout must remain distinct.

Detailed notes - 10.8.4: Inheritance as set inclusion

1

method call and message sending describe the same interaction at different

levels of explanation

2

view a class as a set of objects satisfying its conditions

  • a substitutable derived class describes a subset
  • every instance in that subset also satisfies the base interface
  • the converse need not hold

3

inheritance specializes a general case

  • superclass names the containing conceptual set
  • subclass names the more restricted conceptual set

4

implementation containment points in the opposite direction

  • the derived object contains its base subobject
  • the conceptual derived class is contained in the base class's set

5

keep these two models separate

  • subclass/superclass: classification of objects
  • base subobject/derived storage: physical implementation relationship
  • both are useful, but mixing them creates apparent contradictions

10.9 Formatting C++ code

Consistent naming, access-label indentation, and compact interfaces make C++ declarations easier to read. Constructor initializer lists and short in-class definitions need formatting that exposes their structure without hiding actual initialization rules.

10.9.1 Naming conventions

The book distinguishes ordinary lowercase names from mixed-case class and method names. These are conventions rather than language requirements; consistent treatment of categories matters more than any single capitalization scheme.

#define BUFFER_SIZE 4096                    // macros: uppercase

int line_count_in_file(const char *name);  // functions, variables: lowercase
static int max_line_length = 1023;

class SparseArrayInt {                      // classes and methods:
public:                                     // UpperCamelCase
    int Count() const;
    void AddItem(int index, int value);
};
Detailed notes - 10.9.1: Naming conventions

1

the book distinguishes C-style entities from class-related names

  • C tradition uses lowercase words and underscores
  • its classes and methods use mixed-case names with word boundaries marked by capitals
  • these are conventions, not language syntax requirements

2

ordinary functions and variables retain lowercase_with_underscores

  • macros use uppercase to stand out
  • the author prefers language facilities over macros where practical
  • include guards and conditional compilation remain preprocessing uses
  • the source's use of 0 for null belongs to its older C++ convention

3

one cited convention uses UpperCamelCase for classes

  • lowerCamelCase with at least two words for ordinary methods
  • lowercase_with_underscores for data members

4

the author instead uses UpperCamelCase for both classes and methods

  • accommodates single-word methods
  • constructor/destructor names already follow their class names
  • consistency within the chosen convention is the practical objective

10.9.2 Formatting class definitions

Access labels change visibility without introducing a nested scope. Aligning them with class braces and indenting all members equally keeps equally nested declarations at the same visual depth.

Access labels line up with the class braces; every member has the same indentation:

class Complex {
    double re, im;
public:
    Complex(double a_re, double a_im) : re(a_re), im(a_im) {}
    double GetRe() const { return re; }
private:
    void Normalize();
};

Indented labels make equally nested members look nested at different depths:

class Complex {
    private:
        double re, im;
    public:
        double GetRe() const { return re; }
};
Detailed notes - 10.9.2: Formatting class definitions

1

access labels add a formatting choice

  • the author aligns public:, private: and protected: with class braces
  • all member declarations receive the same single indentation level

avoid making equally nested members appear at different depths

  • changing access does not introduce another containing scope

10.9.3 Formatting constructor declarations and definitions

Constructor initializer lists should wrap consistently and make each base or member initializer visible. Their displayed order should follow actual construction order rather than imply that rearranging the list changes member initialization.

class Rectangle {
    int x, y, width, height;
    const char *label;
public:
    Rectangle(int a_x, int a_y, int a_width, int a_height,
              const char *a_label);
};

Rectangle::Rectangle(int a_x, int a_y, int a_width, int a_height,
                     const char *a_label)
    : x(a_x), y(a_y), width(a_width), height(a_height),
    label(a_label)
{
}

The compact alternative aligns the colon with the leading commas:

Rectangle::Rectangle(int a_x, int a_y, int a_width, int a_height,
                     const char *a_label)
    : x(a_x), y(a_y)
    , width(a_width), height(a_height)
    , label(a_label)
{
}
Detailed notes - 10.9.3: Formatting constructor declarations and definitions

1

initializer lists distinguish constructor formatting from ordinary functions

  • decide where the list begins and how long lists wrap

2

usual out-of-class style: initializer list starts on its own indented line

  • colon can begin that line
  • several alternatives are stylistically possible

keep continuation indentation regular

  • do not create arbitrary depths merely to align a name after punctuation

one compact option: align a leading colon and subsequent leading commas

  • each initializer occupies a clearly marked line

long horizontal lists can wrap at sensible boundaries

  • grouping base and member initializers can improve readability
  • preserve the actual declaration/construction order
  • formatting must not suggest that writing order changes member order

10.9.4 Method bodies inside class definitions

Short in-class method bodies can keep simple accessors clear, while longer implementations obscure the available interface. Moving longer bodies outside preserves scanability; inline status still does not force machine-code substitution.

class Complex {
    double re, im;
public:
    double GetRe() const { return re; }         // one line
    double Magnitude() const
        { return sqrt(re*re + im*im); }         // a short body below
    void Scale(double k) {
        re *= k;
        im *= k;
    }
    Complex Conjugate() const;                  // longer: defined outside
};
Detailed notes - 10.9.4: Method bodies inside class definitions

1

member bodies may be inside or outside the class definition

  • in-class definitions are inline under the book's model
  • machine-code substitution is still an optimizer decision

2

keep the class's visible interface compact

  • readers should quickly see its available operations
  • longer implementation bodies belong outside the class definition
  • the author suggests usually one line, occasionally two or three inside

header bodies can increase compilation work across modules

  • inline rules do not imply every translation unit contributes a permanently separate final executable copy

3

short accessor bodies can share a line with their declaration

  • a short body can instead occupy one indented following line
  • a small multiline body may put { on the declaration line
  • compactness can justify limited departures from ordinary function style

if compression obscures the code, move the definition outside the class

  • explicit inline remains available where its definition rules fit

10.10 Example: TCP chat server

The chat server separates descriptor readiness selection from listening and client-session objects. Sessions buffer incomplete lines and track protocol stage; robust output also needs queued nonblocking writes, since one write may block or send only part of a message.

The lower layer knows only descriptors and events:

#include <sys/select.h>

class FdHandler {
    int fd;
    bool own_fd;
public:
    FdHandler(int a_fd, bool own = true) : fd(a_fd), own_fd(own) {}
    virtual ~FdHandler() { if (own_fd) close(fd); }
    virtual void Handle(bool r, bool w) = 0;
    int GetFd() const { return fd; }
    virtual bool WantRead() const { return true; }
    virtual bool WantWrite() const { return false; }
};

class EventSelector {
    FdHandler **fd_array;
    int fd_array_len;
    int max_fd;
    bool quit_flag;
public:
    EventSelector()
        : fd_array(0), fd_array_len(0), max_fd(-1), quit_flag(false) {}
    ~EventSelector() { delete [] fd_array; }    // not the handlers
    void Add(FdHandler *h);
    bool Remove(FdHandler *h);
    void BreakLoop() { quit_flag = true; }
    void Run();
};

The main loop asks each handler what it waits for, then dispatches:

void EventSelector::Run()
{
    quit_flag = false;
    do {
        int i;
        fd_set rds, wrs;
        FD_ZERO(&rds);
        FD_ZERO(&wrs);
        for (i = 0; i <= max_fd; i++) {
            if (!fd_array[i])
                continue;
            if (fd_array[i]->WantRead())
                FD_SET(i, &rds);
            if (fd_array[i]->WantWrite())
                FD_SET(i, &wrs);
        }
        int res = select(max_fd + 1, &rds, &wrs, 0, 0);
        if (res < 0) {
            if (errno == EINTR)
                continue;
            break;
        }
        for (i = 0; i <= max_fd; i++) {
            if (!fd_array[i])
                continue;
            bool r = FD_ISSET(i, &rds);
            bool w = FD_ISSET(i, &wrs);
            if (r || w)
                fd_array[i]->Handle(r, w);
        }
    } while (!quit_flag);
}

The chat layer consists of two kinds of handlers. Only ChatServer may create, use and destroy sessions:

enum {
    max_line_length = 1023,
    qlen_for_listen = 16
};

class ChatServer;

class ChatSession : public FdHandler {
    friend class ChatServer;

    char buffer[max_line_length + 1];
    int buf_used;
    bool ignoring;
    char *name;
    ChatServer *the_master;

    ChatSession(ChatServer *a_master, int fd);
    ~ChatSession();

    void Send(const char *msg);
    virtual void Handle(bool r, bool w);

    void ReadAndIgnore();
    void ReadAndCheck();
    void CheckLines();
    void ProcessLine(const char *str);
    void Leave();
};

class ChatServer : public FdHandler {
    EventSelector *the_selector;
    struct item {
        ChatSession *s;
        item *next;
    };
    item *first;

    ChatServer(EventSelector *sel, int fd);
public:
    ~ChatServer();
    static ChatServer *Start(EventSelector *sel, int port);
    void RemoveSession(ChatSession *s);
    void SendAll(const char *msg, ChatSession *except = 0);
private:
    virtual void Handle(bool r, bool w);
};

A session cuts complete lines out of its buffer and keeps the unfinished rest:

void ChatSession::CheckLines()
{
    int i = 0;
    while (i < buf_used) {
        if (buffer[i] != '\n') {
            i++;
            continue;
        }
        buffer[i] = 0;
        if (i > 0 && buffer[i-1] == '\r')
            buffer[i-1] = 0;
        ProcessLine(buffer);
        int rest = buf_used - i - 1;
        memmove(buffer, buffer + i + 1, rest);
        buf_used = rest;
        i = 0;
    }
}
Show the complete program
#include <errno.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <unistd.h>

class FdHandler {
    int fd;
    bool own_fd;
public:
    FdHandler(int a_fd, bool own = true) : fd(a_fd), own_fd(own) {}
    virtual ~FdHandler() { if (own_fd) close(fd); }
    virtual void Handle(bool r, bool w) = 0;
    int GetFd() const { return fd; }
    virtual bool WantRead() const { return true; }
    virtual bool WantWrite() const { return false; }
};

class EventSelector {
    FdHandler **fd_array;
    int fd_array_len;
    int max_fd;
    bool quit_flag;
public:
    EventSelector()
        : fd_array(0), fd_array_len(0), max_fd(-1), quit_flag(false) {}
    ~EventSelector() { delete [] fd_array; }
    void Add(FdHandler *h);
    bool Remove(FdHandler *h);
    void BreakLoop() { quit_flag = true; }
    void Run();
};

void EventSelector::Add(FdHandler *h)
{
    int i;
    int fd = h->GetFd();
    if (!fd_array) {
        fd_array_len = fd > 15 ? fd + 1 : 16;
        fd_array = new FdHandler*[fd_array_len];
        for (i = 0; i < fd_array_len; i++)
            fd_array[i] = 0;
    }
    if (fd_array_len <= fd) {
        FdHandler **tmp = new FdHandler*[fd + 1];
        for (i = 0; i <= fd; i++)
            tmp[i] = i < fd_array_len ? fd_array[i] : 0;
        delete [] fd_array;
        fd_array = tmp;
        fd_array_len = fd + 1;
    }
    if (fd > max_fd)
        max_fd = fd;
    fd_array[fd] = h;
}

bool EventSelector::Remove(FdHandler *h)
{
    int fd = h->GetFd();
    if (fd >= fd_array_len || fd_array[fd] != h)
        return false;
    fd_array[fd] = 0;
    while (max_fd >= 0 && !fd_array[max_fd])
        max_fd--;
    return true;
}

void EventSelector::Run()
{
    quit_flag = false;
    do {
        int i;
        fd_set rds, wrs;
        FD_ZERO(&rds);
        FD_ZERO(&wrs);
        for (i = 0; i <= max_fd; i++) {
            if (!fd_array[i])
                continue;
            if (fd_array[i]->WantRead())
                FD_SET(i, &rds);
            if (fd_array[i]->WantWrite())
                FD_SET(i, &wrs);
        }
        int res = select(max_fd + 1, &rds, &wrs, 0, 0);
        if (res < 0) {
            if (errno == EINTR)
                continue;
            break;
        }
        for (i = 0; i <= max_fd; i++) {
            if (!fd_array[i])
                continue;
            bool r = FD_ISSET(i, &rds);
            bool w = FD_ISSET(i, &wrs);
            if (r || w)
                fd_array[i]->Handle(r, w);
        }
    } while (!quit_flag);
}

enum {
    max_line_length = 1023,
    qlen_for_listen = 16
};

class ChatServer;

class ChatSession : public FdHandler {
    friend class ChatServer;

    char buffer[max_line_length + 1];
    int buf_used;
    bool ignoring;
    char *name;
    ChatServer *the_master;

    ChatSession(ChatServer *a_master, int fd);
    ~ChatSession();

    void Send(const char *msg);
    virtual void Handle(bool r, bool w);

    void ReadAndIgnore();
    void ReadAndCheck();
    void CheckLines();
    void ProcessLine(const char *str);
    void Leave();
};

class ChatServer : public FdHandler {
    EventSelector *the_selector;
    struct item {
        ChatSession *s;
        item *next;
    };
    item *first;

    ChatServer(EventSelector *sel, int fd);
public:
    ~ChatServer();
    static ChatServer *Start(EventSelector *sel, int port);
    void RemoveSession(ChatSession *s);
    void SendAll(const char *msg, ChatSession *except = 0);
private:
    virtual void Handle(bool r, bool w);
};

ChatServer *ChatServer::Start(EventSelector *sel, int port)
{
    int ls, opt, res;
    struct sockaddr_in addr;

    ls = socket(AF_INET, SOCK_STREAM, 0);
    if (ls == -1)
        return 0;
    opt = 1;
    res = setsockopt(ls, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    if (res == -1) {
        close(ls);
        return 0;
    }
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    addr.sin_port = htons(port);
    res = bind(ls, (struct sockaddr *) &addr, sizeof(addr));
    if (res == -1) {
        close(ls);
        return 0;
    }
    res = listen(ls, qlen_for_listen);
    if (res == -1) {
        close(ls);
        return 0;
    }
    return new ChatServer(sel, ls);
}

ChatServer::ChatServer(EventSelector *sel, int fd)
    : FdHandler(fd, true), the_selector(sel), first(0)
{
    the_selector->Add(this);
}

ChatServer::~ChatServer()
{
    while (first) {
        item *tmp = first;
        first = first->next;
        the_selector->Remove(tmp->s);
        delete tmp->s;
        delete tmp;
    }
    the_selector->Remove(this);
}

void ChatServer::Handle(bool r, bool w)
{
    if (!r)
        return;
    struct sockaddr_in addr;
    socklen_t len = sizeof(addr);
    int sd = accept(GetFd(), (struct sockaddr *) &addr, &len);
    if (sd == -1)
        return;
    item *p = new item;
    p->next = first;
    p->s = new ChatSession(this, sd);
    first = p;
    the_selector->Add(p->s);
}

void ChatServer::RemoveSession(ChatSession *s)
{
    the_selector->Remove(s);
    item **p;
    for (p = &first; *p; p = &(*p)->next) {
        if ((*p)->s == s) {
            item *tmp = *p;
            *p = tmp->next;
            delete tmp->s;
            delete tmp;
            return;
        }
    }
}

void ChatServer::SendAll(const char *msg, ChatSession *except)
{
    for (item *p = first; p; p = p->next)
        if (p->s != except)
            p->s->Send(msg);
}

ChatSession::ChatSession(ChatServer *a_master, int fd)
    : FdHandler(fd, true), buf_used(0), ignoring(false),
    name(0), the_master(a_master)
{
    Send("Your name please: ");
}

ChatSession::~ChatSession()
{
    delete [] name;
}

void ChatSession::Send(const char *msg)
{
    write(GetFd(), msg, strlen(msg));   // may block or write only a part
}

void ChatSession::Handle(bool r, bool w)
{
    if (!r)
        return;
    if (buf_used >= (int) sizeof(buffer)) {     // no line end in sight
        buf_used = 0;
        ignoring = true;
    }
    if (ignoring)
        ReadAndIgnore();
    else
        ReadAndCheck();
}

void ChatSession::ReadAndIgnore()
{
    int rc = read(GetFd(), buffer, sizeof(buffer));
    if (rc < 1) {
        Leave();
        return;                 // this object no longer exists
    }
    for (int i = 0; i < rc; i++) {
        if (buffer[i] == '\n') {
            int rest = rc - i - 1;
            memmove(buffer, buffer + i + 1, rest);
            buf_used = rest;
            ignoring = false;
            CheckLines();
            return;
        }
    }
}

void ChatSession::ReadAndCheck()
{
    int rc = read(GetFd(), buffer + buf_used, sizeof(buffer) - buf_used);
    if (rc == -1 && errno == EINTR)
        return;
    if (rc < 1) {
        Leave();
        return;                 // this object no longer exists
    }
    buf_used += rc;
    CheckLines();
}

void ChatSession::CheckLines()
{
    int i = 0;
    while (i < buf_used) {
        if (buffer[i] != '\n') {
            i++;
            continue;
        }
        buffer[i] = 0;
        if (i > 0 && buffer[i-1] == '\r')
            buffer[i-1] = 0;
        ProcessLine(buffer);
        int rest = buf_used - i - 1;
        memmove(buffer, buffer + i + 1, rest);
        buf_used = rest;
        i = 0;
    }
}

void ChatSession::ProcessLine(const char *str)
{
    int len = strlen(str);
    if (!name) {
        name = new char[len + 1];
        strcpy(name, str);
        char *wmsg = new char[len + 100];
        sprintf(wmsg, "Welcome, %s!\n", name);
        Send(wmsg);
        sprintf(wmsg, "%s has joined the chat\n", name);
        the_master->SendAll(wmsg, this);
        delete [] wmsg;
        return;
    }
    char *msg = new char[strlen(name) + len + 5];
    sprintf(msg, "<%s> %s\n", name, str);
    the_master->SendAll(msg);
    delete [] msg;
}

void ChatSession::Leave()
{
    if (name) {
        char *lmsg = new char[strlen(name) + 30];
        sprintf(lmsg, "%s has left the chat\n", name);
        the_master->SendAll(lmsg, this);
        delete [] lmsg;
    }
    the_master->RemoveSession(this);    // deletes this object
}

static int port = 7777;

int main()
{
    EventSelector *selector = new EventSelector;
    ChatServer *serv = ChatServer::Start(selector, port);
    if (!serv) {
        perror("server");
        return 1;
    }
    selector->Run();
    return 0;
}
Detailed notes - 10.10: Example: TCP chat server

1

objects are a natural option when a task is organized around events

  • events identify responsibilities that different objects can implement

2

example: select-based TCP chat server

  • ask each connected client for a name
  • broadcast later lines with that name to connected participants
  • simulations and network event loops both motivate event-oriented designs

3

example omits command features such as rename, list users, and leave

  • focuses on object organization
  • a command prefix such as / could distinguish commands from chat text

4

one object owns the event-selection loop

  • other objects receive and handle events
  • separates waiting/dispatch from application-specific reactions

5

lower layer supports descriptor readability and writability

  • chat example uses readable events only
  • a handler object records the associated descriptor

6

timeout and signal events would need additional abstractions

  • their interfaces differ from descriptor-ready notifications
  • author cites his Sue library as a larger example of the overall design

7

first layer:

  • FdHandler: descriptor and event-handling interface
  • EventSelector: registration, readiness selection, main loop

8

application layer:

  • ChatServer represents the listening socket and connected sessions
  • ChatSession represents an accepted client connection
  • both specialize FdHandler
  • server coordinates broadcasts between session objects

9

FdHandler describes how to react to descriptor events

  • concrete behavior belongs to a derived class
  • design this interface without embedding chat-specific responsibilities

10

selector and derived handlers need access to the descriptor

  • supply it through the constructor
  • GetFd exposes its value
  • no setter: changing it behind the selector would invalidate registration

11

ownership is explicit

  • own_fd indicates whether destroying the handler must close the descriptor
  • supports either owned or borrowed descriptors

12

interest in readiness can change during operation

  • WantRead defaults to true
  • WantWrite defaults to false
  • normally request writable events only while output is queued
  • virtual queries let derived handlers choose their policy

13

Handle(read_ready, write_ready) is pure virtual

  • FdHandler is abstract
  • virtual destructor closes fd only when own_fd is true
  • GetFd is a const observer
  • trivial methods can be defined directly in the class

EventSelector registration storage:

  • array indexed by descriptor number contains FdHandler pointers
  • allocate lazily on the first registration
  • retain capacity and maximum registered descriptor
  • selector manages registrations, not the handlers' application lifetimes

14

BreakLoop requests orderly loop termination

  • sets quit_flag instead of terminating the process directly
  • Run clears the flag when starting
  • caller can regain control for cleanup after Run returns

15

EventSelector interface: Add, Remove, BreakLoop, Run

  • destructor releases the pointer array, not the registered objects

Add:

  • initial capacity is at least 16 and must include the descriptor index
  • initialize unused entries to null
  • grow and copy entries when necessary; clear new unused positions
  • update max_fd and register the handler

Remove:

  • verify that the indexed entry is the requested handler
  • clear it; if it was max_fd, scan backward to the last occupied slot

Run:

  • rebuild read/write sets from each handler's current interests
  • select(max_fd+1, ...) waits for readiness
  • EINTR retries; other select errors end this simplified loop
  • dispatch Handle for registered descriptors reported ready
  • stop when quit_flag is set

Implementation conditions:

  • descriptor indices must fit FD_SETSIZE when using fd_set
  • initialize/guard empty-selector state before running or removing
  • registration changes during callbacks require careful lifetime handling

Upper-layer ownership:

  • ChatServer accepts connections and creates ChatSession objects
  • retains a list of live sessions for broadcast and deletion
  • a disconnected session asks the server to remove it

16

ChatServer is the application-level manager of each ChatSession

  • make session operations private and declare ChatServer a friend
  • EventSelector sees only the FdHandler interface
  • private overrides can still implement public virtual dispatch

17

server needs a prepared listening descriptor before construction

  • private constructor prevents creating an unprepared server
  • static Start performs socket/bind/listen setup
  • failure returns a null pointer; success returns a server object

18

session's name field also identifies its protocol stage

  • initially null -> next line is the chosen name
  • later lines are chat messages
  • welcome new user; notify others about arrivals and departures

19

SendAll(message, except) broadcasts to the session list

  • null except means include everyone
  • session Send sends text to one client

20

named limits in the example:

  • max_line_length = 1023
  • listen queue request = 16

Session helpers:

  • ReadAndIgnore discards the rest of an overlong input line
  • ReadAndCheck appends new bytes to the current input buffer
  • CheckLines extracts all complete lines, retaining an unfinished suffix
  • ProcessLine applies the name/chat protocol

Server startup:

  • socket(AF_INET, SOCK_STREAM, 0)
  • set SO_REUSEADDR; bind the chosen port on INADDR_ANY
  • listen, then construct/register ChatServer
  • close the socket if setup fails
  • complete code must check setsockopt/listen and allocation failures too

Server lifetime:

  • constructor initializes the session list and registers itself
  • destructor unregisters/deletes each session and list node
  • unregister itself; base destructor closes its owned listening socket

Accept handling:

  • readable listening socket -> accept a client
  • construct a session and list entry, then register the session
  • peer address could be retained for logging/administration

21

RemoveSession:

  • unregister the handler before destroying it
  • locate its list entry through a pointer to the incoming link
  • unlink and delete both session and entry

SendAll:

  • traverse live sessions, skipping except

Session Send:

  • sample calls write once for the whole message
  • this can block or write partially; a robust event loop queues output and uses nonblocking writable events as described earlier

Session lifetime:

  • constructor clears buffer state, starts with no name, and sends prompt
  • destructor releases the name; base destructor closes the owned socket

Handle:

  • if buffer filled without a complete line, reset it and enter ignoring mode
  • choose ReadAndIgnore or ReadAndCheck

ReadAndIgnore:

  • read a chunk and search for the next newline
  • discard everything through it; retain any following bytes
  • leave ignoring mode and process any now-complete lines

ReadAndCheck:

  • append into unused buffer capacity
  • on successful read, update buf_used and call CheckLines
  • EOF/fatal error: announce departure if named, then request removal
  • distinguish retryable read errors from disconnect in complete code
  • after removal, return without accessing the destroyed object

CheckLines:

  • locate newline, replace it with zero
  • remove a preceding CR when present
  • process the line, shift remaining bytes with memmove
  • repeat for every complete line; preserve final fragment

ProcessLine:

  • first line becomes an owned copy of the name
  • send personal welcome and broadcast arrival to the other sessions
  • later line becomes "<name> text\n" and is broadcast to everyone
  • temporary message arrays are deleted after use

Program entry:

  • create selector; Start server on the example's fixed port 7777
  • report startup failure; otherwise call Run
  • complete application also arranges shutdown/cleanup and output errors
  • source archive places the implementation in cpp_chat modules
Descriptor readiness selects a handler; each session retains its own partially received line.
One event selector dispatches many client sessions. Open full size - Editable SVG
Examples & tests (17 files) - 10.10: Example: TCP chat server
Book exampleBook example: cpp_chat/In catalog
cpp_chat/MakefileMake / 19 lines
CXX = g++
CXXFLAGS = -g -Wall -O2


chat: sockets.o chat.o main.o
    $(CXX) $^ -o $@

%.o: %.cpp
    $(CXX) $(CXXFLAGS) -c $<

clean:
    rm -f *.o *~ deps.mk chat

deps.mk: $(wildcard *.cpp) Makefile
    $(CXX) -MM $(wildcard *.cpp) > $@

ifneq (clean, $(MAKECMDGOALS))
-include deps.mk
endif
cpp_chat/chat.cppC++ / 220 lines
#include <stdio.h>  // for sprintf
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#include "chat.hpp"

static const char welcome_msg[] =
    "Welcome to the chat, you are known as ";
static const char entered_msg[] = " has entered the chat";
static const char left_msg[] = " has left the chat";



ChatSession::ChatSession(ChatServer *a_master, int fd)
    : FdHandler(fd, true), buf_used(0), ignoring(false),
    name(0), the_master(a_master)
{
    Send("Your name please: ");
}

ChatSession::~ChatSession()
{
    if(name)
        delete[] name;
}

void ChatSession::Send(const char *msg)
{
    write(GetFd(), msg, strlen(msg));
}

void ChatSession::Handle(bool r, bool w)
{
    if(!r)   // should never happen, we only request ready-to-read events
        return;
    if(buf_used >= (int)sizeof(buffer)) {
        buf_used = 0;
        ignoring = true;
    }
    if(ignoring)
        ReadAndIgnore();
    else
        ReadAndCheck();
}

void ChatSession::ReadAndIgnore()
{
    int rc = read(GetFd(), buffer, sizeof(buffer));
    if(rc < 1) {
        the_master->RemoveSession(this);
        return;
    }
    int i;
    for(i = 0; i < rc; i++)
        if(buffer[i] == '\n') {   // stop ignoring!
            int rest = rc - i - 1;
            if(rest > 0)
                memmove(buffer, buffer + i + 1, rest);
            buf_used = rest;
            ignoring = false;
            CheckLines();
            return;
        }
}

void ChatSession::ReadAndCheck()
{
    int rc = read(GetFd(), buffer+buf_used, sizeof(buffer)-buf_used);
    if(rc < 1) {
        if(name) {
            int len = strlen(name);
            char *lmsg = new char[len + sizeof(left_msg) + 2];
            sprintf(lmsg, "%s%s\n", name, left_msg);
            the_master->SendAll(lmsg, this);
            delete[] lmsg;
        }
        the_master->RemoveSession(this);
        return;
    }
    buf_used += rc;
    CheckLines();
}

void ChatSession::CheckLines()
{
    if(buf_used <= 0)
        return;
    int i;
    for(i = 0; i < buf_used; i++) {
        if(buffer[i] == '\n') {
            buffer[i] = 0;
            if(i > 0 && buffer[i-1] == '\r')
                buffer[i-1] = 0;
            ProcessLine(buffer);
            int rest = buf_used - i - 1;
            memmove(buffer, buffer + i + 1, rest);
            buf_used = rest;
            CheckLines();
            return;
        }
    }
}

void ChatSession::ProcessLine(const char *str)
{
    int len = strlen(str);
    if(!name) {
        name = new char[len+1];
        strcpy(name, str);

        char *wmsg = new char[len + sizeof(welcome_msg) + 2];
        sprintf(wmsg, "%s%s\n", welcome_msg, name);
        Send(wmsg);
        delete[] wmsg;

        char *emsg = new char[len + sizeof(entered_msg) + 2];
        sprintf(emsg, "%s%s\n", name, entered_msg);
        the_master->SendAll(emsg, this);
        delete[] emsg;

        return;
    }
    int nl = strlen(name);
    char *msg = new char[nl + len + 5];
    sprintf(msg, "<%s> %s\n", name, str);
    the_master->SendAll(msg);
    delete[] msg;
}

//////////////////////////////////////////////////////////////////////

ChatServer::ChatServer(EventSelector *sel, int fd)
    : FdHandler(fd, true), the_selector(sel), first(0)
{
    the_selector->Add(this);
}

ChatServer::~ChatServer()
{
    while(first) {
        item *tmp = first;
        first = first->next;
        the_selector->Remove(tmp->s);
        delete tmp->s;
        delete tmp;
    }
    the_selector->Remove(this);
}

ChatServer *ChatServer::Start(EventSelector *sel, int port)
{
    int ls, opt, res;
    struct sockaddr_in addr;

    ls = socket(AF_INET, SOCK_STREAM, 0);
    if(ls == -1)
        return 0;

    opt = 1;
    setsockopt(ls, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    addr.sin_port = htons(port);
    res = bind(ls, (struct sockaddr*) &addr, sizeof(addr));
    if(res == -1) {
        close(ls);
        return 0;
    }

    listen(ls, qlen_for_listen);

    return new ChatServer(sel, ls);
}

void ChatServer::RemoveSession(ChatSession *s)
{
    the_selector->Remove(s);
    item **p;
    for(p = &first; *p; p = &((*p)->next)) {
        if((*p)->s == s) {
            item *tmp = *p;
            *p = tmp->next;
            delete tmp->s;
            delete tmp;
            return;
        }
    }
}

void ChatServer::SendAll(const char *msg, ChatSession *except)
{
    item *p;
    for(p = first; p; p = p->next)
        if(p->s != except)
            p->s->Send(msg);
}

void ChatServer::Handle(bool r, bool w)
{
    if(!r)       // must not happen, ever!
        return;

    int sd;
    struct sockaddr_in addr;
    socklen_t len = sizeof(addr);
    sd = accept(GetFd(), (struct sockaddr*) &addr, &len);
    if(sd == -1)
        return;

    item *p = new item;
    p->next = first;
    p->s = new ChatSession(this, sd);
    first = p;

    the_selector->Add(p->s);
}
cpp_chat/chat.hppC++ / 58 lines
#ifndef CHAT_HPP_SENTRY
#define CHAT_HPP_SENTRY

#include "sockets.hpp"

enum {
    max_line_length = 1023,
    qlen_for_listen = 16
};

class ChatServer;

class ChatSession : FdHandler {
    friend class ChatServer;

    char buffer[max_line_length+1];
    int buf_used;
    bool ignoring;

    char *name;

    ChatServer *the_master;

    ChatSession(ChatServer *a_master, int fd);
    ~ChatSession();

    void Send(const char *msg);

    virtual void Handle(bool r, bool w);

    void ReadAndIgnore();
    void ReadAndCheck();
    void CheckLines();
    void ProcessLine(const char *str);
};

class ChatServer : public FdHandler {
    EventSelector *the_selector;
    struct item {
        ChatSession *s;
        item *next;
    };
    item *first;

    ChatServer(EventSelector *sel, int fd);
public:
    ~ChatServer();

    static ChatServer *Start(EventSelector *sel, int port);

    void RemoveSession(ChatSession *s);
    void SendAll(const char *msg, ChatSession *except = 0);

private:
    virtual void Handle(bool r, bool w);
};

#endif
cpp_chat/deps.mkMake / 3 lines
chat.o: chat.cpp chat.hpp sockets.hpp
main.o: main.cpp chat.hpp sockets.hpp
sockets.o: sockets.cpp sockets.hpp
cpp_chat/main.cppC++ / 16 lines
#include <stdio.h>
#include "chat.hpp"

static int port = 7777;

int main()
{
    EventSelector *selector = new EventSelector;
    ChatServer *serv = ChatServer::Start(selector, port);
    if(!serv) {
        perror("server");
        return 1;
    }
    selector->Run();
    return 0;
}
cpp_chat/sockets.cppC++ / 96 lines
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>


#include "sockets.hpp"

EventSelector::~EventSelector()
{
    if(fd_array)
        delete[] fd_array;
}

void EventSelector::Add(FdHandler *h)
{
    int i;
    int fd = h->GetFd();
    if(!fd_array) {
        fd_array_len = fd > 15 ? fd + 1 : 16;
        fd_array = new FdHandler*[fd_array_len];
        for(i = 0; i < fd_array_len; i++)
            fd_array[i] = 0;
        max_fd = -1;
    }
    if(fd_array_len <= fd) {
        FdHandler **tmp = new FdHandler*[fd+1];
        for(i = 0; i <= fd ; i++)
            tmp[i] = i < fd_array_len ? fd_array[i] : 0;
        fd_array_len = fd + 1;
        delete[] fd_array;
        fd_array = tmp;
    }
    if(fd > max_fd)
        max_fd = fd;
    fd_array[fd] = h;
}

bool EventSelector::Remove(FdHandler *h)
{
    int fd = h->GetFd();
    if(fd >= fd_array_len || fd_array[fd] != h)
        return false;
    fd_array[fd] = 0;
    if(fd == max_fd) {
        while(max_fd >= 0 && !fd_array[max_fd])
            max_fd--;
    }
    return true;
}

void EventSelector::Run()
{
    quit_flag = false;
    do {
        int i;
        fd_set rds, wrs;
        FD_ZERO(&rds);
        FD_ZERO(&wrs);
        for(i = 0; i <= max_fd; i++) {
            if(fd_array[i]) {
                if(fd_array[i]->WantRead())
                    FD_SET(i, &rds);
                if(fd_array[i]->WantWrite())
                    FD_SET(i, &wrs);
            }
        }

        int res = select(max_fd+1, &rds, &wrs, 0, 0);
        if(res < 0) {
            if(errno == EINTR)
                continue;
            else
                break;
        }

        if(res > 0) {
            for(i = 0; i <= max_fd; i++) {
                if(!fd_array[i])
                    continue;
                bool r = FD_ISSET(i, &rds);
                bool w = FD_ISSET(i, &wrs);
                if(r || w)
                    fd_array[i]->Handle(r, w);
            }
        }
    } while(!quit_flag);
}


FdHandler::~FdHandler()
{
    if(own_fd)
        close(fd);
}

cpp_chat/sockets.hppC++ / 39 lines
#ifndef SOCKETS_HPP_SENTRY
#define SOCKETS_HPP_SENTRY

class FdHandler;

class EventSelector {
    FdHandler **fd_array;
    int fd_array_len;
    int max_fd;

    bool quit_flag;
public:
    EventSelector() : fd_array(0), quit_flag(false) {}
    ~EventSelector();

    void Add(FdHandler *h);
    bool Remove(FdHandler *h);

    void BreakLoop() { quit_flag = true; }

    void Run();
};

class FdHandler {
    int fd;               // can NOT be changed "in flight"
    bool own_fd;
public:
    FdHandler(int a_fd, bool own) : fd(a_fd), own_fd(own) {}
    virtual ~FdHandler();
    virtual void Handle(bool r, bool w) = 0;

    int GetFd() const { return fd; }

    virtual bool WantRead() const { return true; }
    virtual bool WantWrite() const { return false; }
};


#endif
Section test00 (10-10)In catalog
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
chat00.cppC++ / 365 lines
#include <unistd.h>
#include <sys/select.h>
#include <errno.h>
#include <netinet/in.h>
#include <string.h>
#include <stdio.h>

class FdHandler {
    int fd;
    bool own_fd;
public:
    FdHandler(int a_fd, bool own)
        : fd(a_fd), own_fd(own) {}
    virtual ~FdHandler();
    virtual void Handle(bool r, bool w) = 0;
    int GetFd() const { return fd; }
    virtual bool WantRead() const { return true; }
    virtual bool WantWrite() const { return false; }
};

FdHandler::~FdHandler()
{
    if (own_fd)
        close(fd);
}

class EventSelector {
    FdHandler **fd_array;
    int fd_array_len;
    int max_fd;
    bool quit_flag;
public:
    EventSelector() : fd_array(0), quit_flag(false) {}
    ~EventSelector();
    void Add(FdHandler *h);
    bool Remove(FdHandler *h);
    void BreakLoop() { quit_flag = true; }
    void Run();
};

EventSelector::~EventSelector()
{
    if (fd_array)
        delete[] fd_array;
}

void EventSelector::Add(FdHandler *h)
{
    int i;
    int fd = h->GetFd();
    if (!fd_array) {
        fd_array_len = fd > 15 ? fd + 1 : 16;
        fd_array = new FdHandler*[fd_array_len];
        for (i = 0; i < fd_array_len; i++)
            fd_array[i] = 0;
        max_fd = -1;
    }
    if (fd_array_len <= fd) {
        FdHandler **tmp = new FdHandler*[fd+1];
        for(i = 0; i <= fd; i++)
            tmp[i] = i < fd_array_len ? fd_array[i] : 0;
        fd_array_len = fd + 1;
        delete[] fd_array;
        fd_array = tmp;
    }
    if (fd > max_fd)
        max_fd = fd;
    fd_array[fd] = h;
}

bool EventSelector::Remove(FdHandler *h)
{
    int fd = h->GetFd();
    if (fd >= fd_array_len || fd_array[fd] != h)
        return false;
    fd_array[fd] = 0;
    if (fd == max_fd)
        while (max_fd >= 0 && !fd_array[max_fd])
            max_fd--;
    return true;
}

void EventSelector::Run()
{
    quit_flag = false;
    do {
        int i;
        fd_set rds, wrs;
        FD_ZERO(&rds);
        FD_ZERO(&wrs);
        for (int i = 0; i <= max_fd; i++) {
            if (fd_array[i]) {
                if (fd_array[i]->WantRead())
                    FD_SET(i, &rds);
                if (fd_array[i]->WantWrite())
                    FD_SET(i, &wrs);
            }
        }
        int res = select(max_fd + 1, &rds, &wrs, 0, 0);
        if (res < 0) {
            if (errno == EINTR)
                continue;
            else
                break;
        }
        if (res > 0)
            for (i = 0; i <= max_fd; i++) {
                if (!fd_array[i])
                    continue;
                bool r = FD_ISSET(i, &rds);
                bool w = FD_ISSET(i, &wrs);
                if (r || w)
                    fd_array[i]->Handle(r, w);
            }
    } while (!quit_flag);
}

enum {
    max_line_length = 1024,
    qlen_for_listen = 16
};

class ChatServer;

class ChatSession : FdHandler {
    friend class ChatServer;
    char buffer[max_line_length+1];
    int buf_used;
    bool ignoring;
    char *name;
    ChatServer *the_master;

    ChatSession(ChatServer *a_master, int fd);
    ~ChatSession();
    void Send(const char *msg);
    virtual void Handle(bool r, bool w);
    void ReadAndIgnore();
    void ReadAndCheck();
    void CheckLines();
    void ProcessLine(const char *str);
};

class ChatServer : public FdHandler {
    EventSelector *the_selector;
    struct item {
        ChatSession *s;
        item *next;
    };
    item *first;
    ChatServer(EventSelector *sel, int fd);
public:
    ~ChatServer();
    static ChatServer *Start(EventSelector *sel, int port);
    void RemoveSession(ChatSession *s);
    void SendAll(const char *msg, ChatSession *except = 0);
private:
    virtual void Handle(bool r, bool w);
};

ChatServer *ChatServer::Start(EventSelector *sel, int port)
{
    int ls, opt, res;
    struct sockaddr_in addr;
    ls = socket(AF_INET, SOCK_STREAM, 0);
    if (ls == -1)
        return 0;
    opt = 1;
    setsockopt(ls, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    addr.sin_port = htons(port);
    res = bind(ls, (struct sockaddr*) &addr, sizeof(addr));
    if (res == -1) {
        close(ls);
        return 0;
    }
    listen(ls, qlen_for_listen);
    return new ChatServer(sel, ls);
}

ChatServer::ChatServer(EventSelector *sel, int fd)
    : FdHandler(fd, true), the_selector(sel), first(0)
{
    the_selector->Add(this);
}

ChatServer::~ChatServer()
{
    while(first) {
        item *tmp = first;
        first = first->next;
        the_selector->Remove(tmp->s);
        delete tmp->s;
        delete tmp;
    }
    the_selector->Remove(this);
}

void ChatServer::Handle(bool r, bool w)
{
    if (!r)
        return;
    int sd;
    struct sockaddr_in addr;
    socklen_t len = sizeof(addr);
    sd = accept(GetFd(), (struct sockaddr*) &addr, &len);
    if (sd == -1)
        return;
    item *p = new item;
    p->next = first;
    p->s = new ChatSession(this, sd);
    first = p;
    the_selector->Add(p->s);
}

void ChatServer::RemoveSession(ChatSession *s)
{
    the_selector->Remove(s);
    item **p;
    for (p = &first; *p; p = &((*p)->next))
        if ((*p)->s == s) {
            item *tmp = *p;
            *p = tmp->next;
            delete tmp->s;
            delete tmp;
            return;
        }
}

void ChatServer::SendAll(const char *msg, ChatSession *except)
{
    item *p;
    for (p = first; p; p = p->next)
        if (p->s != except)
            p->s->Send(msg);
}

void ChatSession::Send(const char *msg)
{
    write(GetFd(), msg, strlen(msg));
}

ChatSession::ChatSession(ChatServer *a_master, int fd)
    : FdHandler(fd, true), buf_used(0), ignoring(false),
    name(0), the_master(a_master)
{
    Send("You name please: ");
}

ChatSession::~ChatSession()
{
    if (name)
        delete[] name;
}

static const char welcome_msg[] =
    "Welcome to the chat, you are known as ";
static const char entered_msg[] = " has entered the chat";
static const char left_msg[] = " has left the chat";

void ChatSession::Handle(bool r, bool w)
{
    if (!r)
        return;
    if (buf_used >= (int) sizeof(buffer)) {
        buf_used = 0;
        ignoring = true;
    }
    if (ignoring)
        ReadAndIgnore();
    else
        ReadAndCheck();
}

void ChatSession::ReadAndIgnore()
{
    int rc = read(GetFd(), buffer, sizeof(buffer));
    if (rc < 1) {
        the_master->RemoveSession(this);
        return;
    }
    for (int i = 0; i < rc; i++)
        if (buffer[i] == '\n') {
            int rest = rc - i - 1;
            if (rest > 0)
                memmove(buffer, buffer + i + 1, rest);
            buf_used = rest;
            ignoring = false;
            CheckLines();
            return;
        }
}

void ChatSession::ReadAndCheck()
{
    int rc = read(GetFd(), buffer + buf_used, sizeof(buffer)- buf_used);
    if (rc < 1) {
        if (name) {
            int len = strlen(name);
            char *lmsg = new char[len + sizeof(left_msg) + 2];
            sprintf(lmsg, "%s%s\n", name, left_msg);
            the_master->SendAll(lmsg, this);
            delete[] lmsg;
        }
        the_master->RemoveSession(this);
        return;
    }
    buf_used += rc;
    CheckLines();
}

void ChatSession::CheckLines()
{
    if (buf_used <= 0)
        return;
    for (int i = 0; i < buf_used; i++)
        if (buffer[i] == '\n') {
            buffer[i] = 0;
            if (i > 0 && buffer[i-1] == '\r')
                buffer[i-1] = 0;
            ProcessLine(buffer);
            int rest = buf_used - i - 1;
            memmove(buffer, buffer + i + 1, rest);
            buf_used = rest;
            CheckLines();
            return;
        }
}

void ChatSession::ProcessLine(const char *str)
{
    int len = strlen(str);
    if (!name) {
        name = new char[len+1];
        strcpy(name, str);
        char *wmsg = new char[len + sizeof(welcome_msg) + 2];
        sprintf(wmsg, "%s%s\n", welcome_msg, name);
        Send(wmsg);
        delete[] wmsg;
        char *emsg = new char[len + sizeof(entered_msg) + 2];
        sprintf(emsg, "%s%s\n", name, entered_msg);
        the_master->SendAll(emsg, this);
        delete[] emsg;
        return;
    }
    int nl = strlen(name);
    char *msg = new char[nl + len + 5];
    sprintf(msg, "<%s> %s\n", name, str);
    the_master->SendAll(msg);
    delete[] msg;
}

static int port = 7777;

int main()
{
    EventSelector *select = new EventSelector;
    ChatServer *serv = ChatServer::Start(select, port);
    if (!serv) {
        perror("server");
        return 1;
    }
    select->Run();
    return 0;
}
chat01.cppC++ / 338 lines
#include <unistd.h>
#include <sys/select.h>
#include <errno.h>
#include <netinet/in.h>
#include <string.h>
#include <stdio.h>

class FdHandler {
    int fd;
public:
    FdHandler(int a_fd) : fd(a_fd) {}
    virtual ~FdHandler() { close(fd); }
    virtual void Handle() = 0;
    int GetFd() const { return fd; }
};

class EventSelector {
    FdHandler **fd_array;
    int fd_array_len;
    int max_fd;
public:
    EventSelector() : fd_array(0) {}
    ~EventSelector() { if (fd_array) delete[] fd_array; }
    void Add(FdHandler *h);
    bool Remove(FdHandler *h);
    void Run();
};

void EventSelector::Add(FdHandler *h)
{
    int i;
    int fd = h->GetFd();
    if (!fd_array) {
        fd_array_len = fd > 15 ? fd + 1 : 16;
        fd_array = new FdHandler*[fd_array_len];
        for (i = 0; i < fd_array_len; i++)
            fd_array[i] = 0;
        max_fd = -1;
    }
    if (fd_array_len <= fd) {
        FdHandler **tmp = new FdHandler*[fd+1];
        for(i = 0; i <= fd; i++)
            tmp[i] = i < fd_array_len ? fd_array[i] : 0;
        fd_array_len = fd + 1;
        delete[] fd_array;
        fd_array = tmp;
    }
    if (fd > max_fd)
        max_fd = fd;
    fd_array[fd] = h;
}

bool EventSelector::Remove(FdHandler *h)
{
    int fd = h->GetFd();
    if (fd >= fd_array_len || fd_array[fd] != h)
        return false;
    fd_array[fd] = 0;
    if (fd == max_fd)
        while (max_fd >= 0 && !fd_array[max_fd])
            max_fd--;
    return true;
}

void EventSelector::Run()
{
    while (1) {
        int i;
        fd_set rds;
        FD_ZERO(&rds);
        for (i = 0; i <= max_fd; i++)
            if (fd_array[i])
                FD_SET(i, &rds);
        int res = select(max_fd + 1, &rds, 0, 0, 0);
        if (res < 0) {
            if (errno == EINTR)
                continue;
            else
                break;
        }
        if (res > 0)
            for (i = 0; i <= max_fd; i++)
                if (fd_array[i] && FD_ISSET(i, &rds))
                    fd_array[i]->Handle();
    }
}

enum {
    max_line_length = 1024,
    qlen_for_listen = 16
};

class ChatServer;

class ChatSession : FdHandler {
    friend class ChatServer;
    char buffer[max_line_length+1];
    int buf_used;
    bool ignoring;
    char *name;
    ChatServer *the_master;

    ChatSession(ChatServer *a_master, int fd);
    ~ChatSession();
    void Send(const char *msg);
    virtual void Handle();
    void ReadAndIgnore();
    void ReadAndCheck();
    void CheckLines();
    void ProcessLine(const char *str);
    static void ShiftBuffer(char *buffer, int& buf_used, int i);
};

class ChatServer : public FdHandler {
    EventSelector *the_selector;
    struct item {
        ChatSession *s;
        item *next;
    };
    item *first;
    ChatServer(EventSelector *sel, int fd);
public:
    ~ChatServer();
    static ChatServer *Start(EventSelector *sel, int port);
    void RemoveSession(ChatSession *s);
    void SendAll(const char *msg, ChatSession *except = 0);
private:
    virtual void Handle();
};

ChatServer *ChatServer::Start(EventSelector *sel, int port)
{
    int ls, opt, res;
    struct sockaddr_in addr;
    ls = socket(AF_INET, SOCK_STREAM, 0);
    if (ls == -1)
        return 0;
    opt = 1;
    setsockopt(ls, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    addr.sin_port = htons(port);
    res = bind(ls, (struct sockaddr*) &addr, sizeof(addr));
    if (res == -1) {
        close(ls);
        return 0;
    }
    listen(ls, qlen_for_listen);
    return new ChatServer(sel, ls);
}

ChatServer::ChatServer(EventSelector *sel, int fd)
    : FdHandler(fd), the_selector(sel), first(0)
{
    the_selector->Add(this);
}

ChatServer::~ChatServer()
{
    while(first) {
        item *tmp = first;
        first = first->next;
        the_selector->Remove(tmp->s);
        delete tmp->s;
        delete tmp;
    }
    the_selector->Remove(this);
}

void ChatServer::Handle()
{
    int sd;
    struct sockaddr_in addr;
    socklen_t len = sizeof(addr);
    sd = accept(GetFd(), (struct sockaddr*) &addr, &len);
    if (sd == -1)
        return;
    item *p = new item;
    p->next = first;
    p->s = new ChatSession(this, sd);
    first = p;
    the_selector->Add(p->s);
}

void ChatServer::RemoveSession(ChatSession *s)
{
    the_selector->Remove(s);
    item **p;
    for (p = &first; *p; p = &((*p)->next))
        if ((*p)->s == s) {
            item *tmp = *p;
            *p = tmp->next;
            delete tmp->s;
            delete tmp;
            return;
        }
}

void ChatServer::SendAll(const char *msg, ChatSession *except)
{
    item *p;
    for (p = first; p; p = p->next)
        if (p->s != except)
            p->s->Send(msg);
}

void ChatSession::Send(const char *msg)
{
    write(GetFd(), msg, strlen(msg));
}

ChatSession::ChatSession(ChatServer *a_master, int fd)
    : FdHandler(fd), buf_used(0), ignoring(false),
    name(0), the_master(a_master)
{
    Send("You name please: ");
}

ChatSession::~ChatSession()
{
    if (name)
        delete[] name;
}

static const char welcome_msg[] =
    "Welcome to the chat, you are known as ";
static const char entered_msg[] = " has entered the chat";
static const char left_msg[] = " has left the chat";

void ChatSession::Handle()
{
    if (buf_used >= (int) sizeof(buffer)) {
        buf_used = 0;
        ignoring = true;
    }
    if (ignoring)
        ReadAndIgnore();
    else
        ReadAndCheck();
}

void ChatSession::ShiftBuffer(char *buffer, int& buf_used, int i)
{
    buf_used -= (i + 1);
    if (buf_used > 0)
        memmove(buffer, buffer + i + 1, buf_used);
}

void ChatSession::ReadAndIgnore()
{
    int rc = read(GetFd(), buffer, sizeof(buffer));
    if (rc < 1) {
        the_master->RemoveSession(this);
        return;
    }
    for (int i = 0; i < rc; i++)
        if (buffer[i] == '\n') {
            buf_used = rc;
            ShiftBuffer(buffer, buf_used, i);
            ignoring = false;
            CheckLines();
            return;
        }
}

void ChatSession::ReadAndCheck()
{
    int rc = read(GetFd(), buffer + buf_used, sizeof(buffer) - buf_used);
    if (rc < 1) {
        if (name) {
            int len = strlen(name);
            char *lmsg = new char[len + sizeof(left_msg) + 2];
            sprintf(lmsg, "%s%s\n", name, left_msg);
            the_master->SendAll(lmsg, this);
            delete[] lmsg;
        }
        the_master->RemoveSession(this);
        return;
    }
    buf_used += rc;
    CheckLines();
}

void ChatSession::CheckLines()
{
    if (buf_used <= 0)
        return;
    for (int i = 0; i < buf_used; i++)
        if (buffer[i] == '\n') {
            buffer[i] = 0;
            if (i > 0 && buffer[i-1] == '\r')
                buffer[i-1] = 0;
            ProcessLine(buffer);
            ShiftBuffer(buffer, buf_used, i);
            CheckLines();
            return;
        }
}

void ChatSession::ProcessLine(const char *str)
{
    int len = strlen(str);
    if (!name) {
        name = new char[len + 1];
        strcpy(name, str);

        char *wmsg = new char[len + sizeof(welcome_msg) + 2];
        sprintf(wmsg, "%s%s\n", welcome_msg, name);
        Send(wmsg);
        delete[] wmsg;

        char *emsg = new char[len + sizeof(entered_msg) + 2];
        sprintf(emsg, "%s%s\n", name, entered_msg);
        the_master->SendAll(emsg, this);
        delete[] emsg;

        return;
    }
    int nl = strlen(name);
    char *msg = new char[nl + len + 5];
    sprintf(msg, "<%s> %s\n", name, str);
    the_master->SendAll(msg);
    delete[] msg;
}

static int port = 7777;

int main()
{
    EventSelector *select = new EventSelector;
    ChatServer *serv = ChatServer::Start(select, port);
    if (!serv) {
        perror("server");
        return 1;
    }
    select->Run();
    return 0;
}
Section test01 (10-10)In catalog
MakefileMake / 15 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic

chat: sockets.o chat.o main.o
    $(CXX) $^ -o $@

clean:
    rm -f *.o *~ deps.mk chat

deps.mk: $(wildcard *.cpp) Makefile
    $(CXX) -MM $(wildcard *.cpp) > $@

ifneq (clean, $(MAKECMDGOALS))
-include deps.mk
endif

chat.cppC++ / 204 lines
#include <unistd.h>
#include <netinet/in.h>
#include <string.h>
#include <stdio.h>

#include "chat.hpp"

static const char welcome_msg[] =
    "Welcome to the chat, you are known as ";
static const char entered_msg[] = " has entered the chat";
static const char left_msg[] = " has left the chat";

ChatServer *ChatServer::Start(EventSelector *sel, int port)
{
    int ls, opt, res;
    struct sockaddr_in addr;
    ls = socket(AF_INET, SOCK_STREAM, 0);
    if (ls == -1)
        return 0;
    opt = 1;
    setsockopt(ls, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    addr.sin_port = htons(port);
    res = bind(ls, (struct sockaddr*) &addr, sizeof(addr));
    if (res == -1) {
        close(ls);
        return 0;
    }
    listen(ls, qlen_for_listen);
    return new ChatServer(sel, ls);
}

ChatServer::ChatServer(EventSelector *sel, int fd)
    : FdHandler(fd), the_selector(sel), first(0)
{
    the_selector->Add(this);
}

ChatServer::~ChatServer()
{
    while(first) {
        item *tmp = first;
        first = first->next;
        the_selector->Remove(tmp->s);
        delete tmp->s;
        delete tmp;
    }
    the_selector->Remove(this);
}

void ChatServer::Handle()
{
    int sd;
    struct sockaddr_in addr;
    socklen_t len = sizeof(addr);
    sd = accept(GetFd(), (struct sockaddr*) &addr, &len);
    if (sd == -1)
        return;
    item *p = new item;
    p->next = first;
    p->s = new ChatSession(this, sd);
    first = p;
    the_selector->Add(p->s);
}

void ChatServer::RemoveSession(ChatSession *s)
{
    the_selector->Remove(s);
    item **p;
    for (p = &first; *p; p = &((*p)->next))
        if ((*p)->s == s) {
            item *tmp = *p;
            *p = tmp->next;
            delete tmp->s;
            delete tmp;
            return;
        }
}

void ChatServer::SendAll(const char *msg, ChatSession *except)
{
    item *p;
    for (p = first; p; p = p->next)
        if (p->s != except)
            p->s->Send(msg);
}

//////////////////////////////////////////////////////////////////////

void ChatSession::Send(const char *msg)
{
    write(GetFd(), msg, strlen(msg));
}

ChatSession::ChatSession(ChatServer *a_master, int fd)
    : FdHandler(fd), buf_used(0), ignoring(false),
    name(0), the_master(a_master)
{
    Send("You name please: ");
}

ChatSession::~ChatSession()
{
    if (name)
        delete[] name;
}

void ChatSession::Handle()
{
    if (buf_used >= (int) sizeof(buffer)) {
        buf_used = 0;
        ignoring = true;
    }
    if (ignoring)
        ReadAndIgnore();
    else
        ReadAndCheck();
}

void ChatSession::ShiftBuffer(char *buffer, int& buf_used, int i)
{
    buf_used -= (i + 1);
    if (buf_used > 0)
        memmove(buffer, buffer + i + 1, buf_used);
}

void ChatSession::ReadAndIgnore()
{
    int rc = read(GetFd(), buffer, sizeof(buffer));
    if (rc < 1) {
        the_master->RemoveSession(this);
        return;
    }
    for (int i = 0; i < rc; i++)
        if (buffer[i] == '\n') {
            buf_used = rc;
            ShiftBuffer(buffer, buf_used, i);
            ignoring = false;
            CheckLines();
            return;
        }
}

void ChatSession::ReadAndCheck()
{
    int rc = read(GetFd(), buffer + buf_used, sizeof(buffer) - buf_used);
    if (rc < 1) {
        if (name) {
            int len = strlen(name);
            char *lmsg = new char[len + sizeof(left_msg) + 2];
            sprintf(lmsg, "%s%s\n", name, left_msg);
            the_master->SendAll(lmsg, this);
            delete[] lmsg;
        }
        the_master->RemoveSession(this);
        return;
    }
    buf_used += rc;
    CheckLines();
}

void ChatSession::CheckLines()
{
    if (buf_used <= 0)
        return;
    for (int i = 0; i < buf_used; i++)
        if (buffer[i] == '\n') {
            buffer[i] = 0;
            if (i > 0 && buffer[i-1] == '\r')
                buffer[i-1] = 0;
            ProcessLine(buffer);
            ShiftBuffer(buffer, buf_used, i);
            CheckLines();
            return;
        }
}

void ChatSession::ProcessLine(const char *str)
{
    int len = strlen(str);
    if (!name) {
        name = new char[len + 1];
        strcpy(name, str);

        char *wmsg = new char[len + sizeof(welcome_msg) + 2];
        sprintf(wmsg, "%s%s\n", welcome_msg, name);
        Send(wmsg);
        delete[] wmsg;

        char *emsg = new char[len + sizeof(entered_msg) + 2];
        sprintf(emsg, "%s%s\n", name, entered_msg);
        the_master->SendAll(emsg, this);
        delete[] emsg;

        return;
    }
    int nl = strlen(name);
    char *msg = new char[nl + len + 5];
    sprintf(msg, "<%s> %s\n", name, str);
    the_master->SendAll(msg);
    delete[] msg;
}

chat.hppC++ / 49 lines
#ifndef CHAT_HPP
#define CHAT_HPP

#include "sockets.hpp"

enum {
    max_line_length = 1024,
    qlen_for_listen = 16
};

class ChatServer;

class ChatSession : FdHandler {
    friend class ChatServer;
    char buffer[max_line_length+1];
    int buf_used;
    bool ignoring;
    char *name;
    ChatServer *the_master;

    ChatSession(ChatServer *a_master, int fd);
    ~ChatSession();
    void Send(const char *msg);
    virtual void Handle();
    void ReadAndIgnore();
    void ReadAndCheck();
    void CheckLines();
    void ProcessLine(const char *str);
    static void ShiftBuffer(char *buffer, int& buf_used, int i);
};

class ChatServer : public FdHandler {
    EventSelector *the_selector;
    struct item {
        ChatSession *s;
        item *next;
    };
    item *first;
    ChatServer(EventSelector *sel, int fd);
public:
    ~ChatServer();
    static ChatServer *Start(EventSelector *sel, int port);
    void RemoveSession(ChatSession *s);
    void SendAll(const char *msg, ChatSession *except = 0);
private:
    virtual void Handle();
};

#endif
deps.mkMake / 3 lines
chat.o: chat.cpp chat.hpp sockets.hpp
main.o: main.cpp sockets.hpp chat.hpp
sockets.o: sockets.cpp sockets.hpp
main.cppC++ / 18 lines
#include <stdio.h>

#include "sockets.hpp"
#include "chat.hpp"

static int port = 7777;

int main()
{
    EventSelector *select = new EventSelector;
    ChatServer *serv = ChatServer::Start(select, port);
    if (!serv) {
        perror("server");
        return 1;
    }
    select->Run();
    return 0;
}
sockets.cppC++ / 72 lines
#include <unistd.h>
#include <sys/select.h>
#include <errno.h>

#include "sockets.hpp"

FdHandler::~FdHandler()
{
    close(fd);
}

/////////////////////////////////////////////////////////////////////

void EventSelector::Add(FdHandler *h)
{
    int i;
    int fd = h->GetFd();
    if (!fd_array) {
        fd_array_len = fd > 15 ? fd + 1 : 16;
        fd_array = new FdHandler*[fd_array_len];
        for (i = 0; i < fd_array_len; i++)
            fd_array[i] = 0;
        max_fd = -1;
    }
    if (fd_array_len <= fd) {
        FdHandler **tmp = new FdHandler*[fd+1];
        for(i = 0; i <= fd; i++)
            tmp[i] = i < fd_array_len ? fd_array[i] : 0;
        fd_array_len = fd + 1;
        delete[] fd_array;
        fd_array = tmp;
    }
    if (fd > max_fd)
        max_fd = fd;
    fd_array[fd] = h;
}

bool EventSelector::Remove(FdHandler *h)
{
    int fd = h->GetFd();
    if (fd >= fd_array_len || fd_array[fd] != h)
        return false;
    fd_array[fd] = 0;
    if (fd == max_fd)
        while (max_fd >= 0 && !fd_array[max_fd])
            max_fd--;
    return true;
}

void EventSelector::Run()
{
    while (1) {
        int i;
        fd_set rds;
        FD_ZERO(&rds);
        for (i = 0; i <= max_fd; i++)
            if (fd_array[i])
                FD_SET(i, &rds);
        int res = select(max_fd + 1, &rds, 0, 0, 0);
        if (res < 0) {
            if (errno == EINTR)
                continue;
            else
                break;
        }
        if (res > 0)
            for (i = 0; i <= max_fd; i++)
                if (fd_array[i] && FD_ISSET(i, &rds))
                    fd_array[i]->Handle();
    }
}

sockets.hppC++ / 25 lines
#ifndef SOCKETS_HPP
#define SOCKETS_HPP

class FdHandler {
    int fd;
public:
    FdHandler(int a_fd) : fd(a_fd) {}
    virtual ~FdHandler();
    virtual void Handle() = 0;
    int GetFd() const { return fd; }
};

class EventSelector {
    FdHandler **fd_array;
    int fd_array_len;
    int max_fd;
public:
    EventSelector() : fd_array(0) {}
    ~EventSelector() { if (fd_array) delete[] fd_array; }
    void Add(FdHandler *h);
    bool Remove(FdHandler *h);
    void Run();
};

#endif

10.11 Graphical user interfaces

Widget libraries supply common GUI machinery so applications can focus on their own behavior. Windows, controls, and event responses offer practical examples of both object-oriented organization and callback-driven execution.

Detailed notes - 10.11: Graphical user interfaces

1

many users expect a graphical interface

  • the author's broad criticism of GUIs is a personal assessment
  • graphical interaction still has conventions that users must learn

2

programmers need to provide a GUI when the application requires one

  • event-driven architecture, C++ and objects now supply the background

3

OOP and graphical interfaces have a close historical connection

  • Smalltalk helped develop object-oriented interactive environments
  • windows, buttons and other widgets fit an object/message model
  • the text's sweeping historical priority claims are simplified

4

building directly on a window system requires much detailed work

  • establish a connection and create windows
  • draw controls, labels and visual feedback
  • interpret mouse and keyboard events
  • maintain appearances when a control is pressed or released

5

widget libraries implement this common machinery

  • create controls, arrange them and specify application responses
  • library handles much drawing and routine input behavior
  • application callbacks implement the events with domain meaning
Book examples (10 files) - 10.11: Graphical user interfaces
Book exampleBook example: fltk/In catalog
fltk/cmdline.cppC++ / 80 lines
#include <stdio.h>
#include <stdlib.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>

enum {
    spacing = 5,
    button_w = 200,
    button_h = 40,
    font_size = 20
};

static void say_callback(Fl_Widget *w, void *user)
{
    printf("%s\n", (const char*)user);
}

static int buttons_count = 3;

static void set_buttons_count(const char *arg)
{
    char *errptr;
    buttons_count = strtol(arg, &errptr, 10);
    if(errptr == arg || *errptr) {
        fprintf(stderr, "Invalid count %s\n", arg);
        exit(1);
    }
}

static int cmdline_callback(int argc, char **argv, int &idx)
{
    if(0 == strcmp(argv[idx], "-count")) {
        if(argc < idx + 2) {
            fprintf(stderr, "Count (number) expected\n");
            exit(1);
        }
        set_buttons_count(argv[idx+1]);
        idx += 2;
        return 2;  /* we use the current and the next one */
    }
#if 0
    if(0 == strcmp(argv[idx], "-bg")) {
        // just ignore
        idx += 2;
        return 2;
    }
#endif
    return 0;  /* we don't know flags other than '-count' */
}


int main(int argc, char **argv)
{
    int arg_idx, res;
    res = Fl::args(argc, argv, arg_idx, cmdline_callback);
    if(!res) {
        fprintf(stderr, "Malformed command line\n");
        return 1;
    }

    int win_w = button_w + spacing * 2;
    int win_h = (button_h + spacing) * buttons_count + spacing;
    Fl_Window *win = new Fl_Window(win_w, win_h, "command line demo");

    int i;
    int y = spacing;
    for(i = 0; i < buttons_count; i++) {
        const char *msg =
            arg_idx + i < argc ? argv[arg_idx + i] : "Not set";
        Fl_Button *b =
            new Fl_Button(spacing, y, button_w, button_h, msg);
        b->labelsize(font_size);
        b->callback(say_callback, (void*)msg);
        y += button_h + spacing;
    }
    win->end();
    win->show(argc, argv);
    return Fl::run();
}
fltk/cmdline2.cppC++ / 74 lines
#include <stdio.h>
#include <stdlib.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>

enum {
    spacing = 5,
    button_w = 200,
    button_h = 40,
    font_size = 20
};

static void say_callback(Fl_Widget *w, void *user)
{
    printf("%s\n", (const char*)user);
}

int main(int argc, char **argv)
{
    int buttons_count = 3;
    int idx = 1;
    bool fltk_args = false;

    while(idx < argc) {
        if(0 == strcmp(argv[idx], "-count")) {
            if(argc < idx + 2) {
                fprintf(stderr, "Count (number) expected\n");
                exit(1);
            }

            char *errptr;
            buttons_count = strtol(argv[idx+1], &errptr, 10);
            if(errptr == argv[idx+1] || *errptr) {
                fprintf(stderr, "Invalid count %s\n", argv[idx+1]);
                exit(1);
            }
            idx += 2;
            continue;
        }
        if(argv[idx][0] == '-') {
            int res = Fl::arg(argc, argv, idx);
            fltk_args = true;
            if(res == 0) {
                fprintf(stderr, "Flag <<%s>> unknown\n", argv[idx]);
                exit(1);
            }
            continue;
        }
        break;
    }

    int win_w = button_w + spacing * 2;
    int win_h = (button_h + spacing) * buttons_count + spacing;
    Fl_Window *win = new Fl_Window(win_w, win_h, "command line demo");

    int i;
    int y = spacing;
    for(i = 0; i < buttons_count; i++) {
        const char *msg =
            idx + i < argc ? argv[idx + i] : "Not set";
        Fl_Button *b =
            new Fl_Button(spacing, y, button_w, button_h, msg);
        b->labelsize(font_size);
        b->callback(say_callback, (void*)msg);
        y += button_h + spacing;
    }
    win->end();
    if(fltk_args)
        win->show(argc, argv);
    else
        win->show();
    return Fl::run();
}
fltk/fonts.cppC++ / 56 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>


Fl_Box **make_box_grid(int w, int h, int spc, int nx, int ny)
{
    int i, j;
    Fl_Box **r = new Fl_Box*[nx*ny];
    for(i = 0; i < nx; i++)
        for(j = 0; j < ny; j++) {
             r[i * ny + j] = new Fl_Box((w+spc)*i+spc, (h+spc)*j+spc, w, h);
        }
    return r;
}

enum {
    spacing = 10,
    box_h = 45,
    box_w = 330,
    count_x = 3,
    count_y = 4,
    labelsize = 35
};

const char * const lab_main[count_x] = { "Helvetica", "Courier", "Times" };
const char * const lab_aux[count_y] =
                              { "", " BOLD", " ITALIC", " B+I" };
const int font_codes[count_x] = { FL_HELVETICA, FL_COURIER, FL_TIMES };
const int font_add[count_y] = { 0, FL_BOLD, FL_ITALIC, FL_BOLD+FL_ITALIC };


int main(int argc, char **argv)
{
    int win_w = (box_w+spacing)*count_x+spacing;
    int win_h = (box_h+spacing)*count_y+spacing;
    Fl_Window *win = new Fl_Window(win_w, win_h, "fonts demo (fonts.cpp)");

    Fl_Box **grid = make_box_grid(box_w, box_h, spacing, count_x, count_y);

    int n, k;
    char buf[80];
    for(n = 0; n < count_x; n++) {
        for(k = 0; k < count_y; k++) {
            sprintf(buf, "%s%s", lab_main[n], lab_aux[k]);
            int idx = n*count_y + k;
            grid[idx]->copy_label(buf);
            grid[idx]->labelfont(font_codes[n] + font_add[k]);
            grid[idx]->labelsize(labelsize);
            grid[idx]->align(FL_ALIGN_CENTER);
        }
    }
    win->end();
    win->show();
    return Fl::run();
}
fltk/hello.cppC++ / 13 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>

int main(int argc, char **argv)
{
    Fl_Window *win = new Fl_Window(300, 100, "hello");
    Fl_Box *b = new Fl_Box(0, 0, 300, 100, "Hello, World!");
    b->labelsize(36);
    win->end();
    win->show();
    return Fl::run();
}
fltk/labelpics.cppC++ / 62 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>


Fl_Box **make_box_grid(int w, int h, int spc, int nx, int ny)
{
    int i, j;
    Fl_Box **r = new Fl_Box*[nx*ny];
    for(i = 0; i < nx; i++)
        for(j = 0; j < ny; j++) {
             r[i * ny + j] = new Fl_Box((w+spc)*i+spc, (h+spc)*j+spc, w, h);
        }
    return r;
}

enum {
    spacing = 10,
    box_h = 45,
    box_w = 200,
    count_x = 4,
    count_y = 5,
    labelsize = 20
};

const char * const labels[] = {
    "@>>", "@2>>", "@7>>", "@+9>>", "@-200097>>",
    "@fileprint", "@%fileprint", "@3fileprint", "@+5fileprint", "@-28fileprint",
    //"@-->", "@$-->", "@00015-->", "@9-->", "@+99-->",
    "@DnArrow", "@$DnArrow", "@00015DnArrow", "@9DnArrow", "@+99DnArrow",
    "@->|", "@-100345->|", "@00015->|", "@9->|", "@+99->|",
    0
};

int main(int argc, char **argv)
{
    int win_w = (box_w+spacing)*count_x+spacing;
    int win_h = (box_h+spacing)*count_y+spacing;
    Fl_Window *win = new Fl_Window(win_w, win_h,
                                   "label icons demo (labelpics.cpp)");

    Fl_Box **grid = make_box_grid(box_w, box_h, spacing, count_x, count_y);

    int n;
    char buf[80];
    for(n = 0; n < count_x * count_y; n++) {
        if(!labels[n])
            break;
        if(!*labels[n])
            continue;
        sprintf(buf, "%s  @%s", labels[n], labels[n]);
        grid[n]->labelfont(FL_COURIER);
        grid[n]->labelsize(labelsize);
        grid[n]->copy_label(buf);
        grid[n]->align(FL_ALIGN_LEFT|FL_ALIGN_INSIDE);
//        grid[n]->box(FL_BORDER_FRAME);
//        grid[n]->color(FL_RED);
    }
    win->end();
    win->show();
    return Fl::run();
}
fltk/oo_speak.cppC++ / 59 lines
#include <stdio.h>
#include <stdlib.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>


class OOFLButton : public Fl_Button {
public:
    OOFLButton(int x, int y, int w, int h, const char *lb = 0)
        : Fl_Button(x, y, w, h, lb)
        { callback(CallbackFunction, 0); }
    virtual ~OOFLButton() {}
    virtual void OnPress() {}
private:
    static void CallbackFunction(Fl_Widget *w, void *user)
        { static_cast<OOFLButton*>(w)->OnPress(); }
};

enum {
    spacing = 5,
    button_w = 200,
    button_h = 40,
    font_size = 20
};

class ButtonCommon : public OOFLButton {
public:
    ButtonCommon(int y, const char *lb)
        : OOFLButton(spacing, y, button_w, button_h, lb)
        { labelsize(font_size); }
};

class SayButton : public ButtonCommon {
    const char *msg;
public:
    SayButton(int y, const char *lb, const char *amsg)
        : ButtonCommon(y, lb), msg(amsg) {}
    virtual void OnPress() { printf("%s\n", msg); }
};

class ExitButton : public ButtonCommon {
public:
    ExitButton(int y) : ButtonCommon(y, "Quit") {}
    virtual void OnPress() { exit(0); }
};

int main(int argc, char **argv)
{
    int win_w = button_w + spacing * 2;
    int win_h = button_h * 3 + spacing * 4;
    Fl_Window *win = new Fl_Window(win_w, win_h, "buttons demo");
    new SayButton(spacing, "Say hello", "Hello, world!");
    new SayButton(2 * spacing + button_h, "Say goodbye", "Goodbye, world!");
    new ExitButton(3 * spacing + 2 * button_h);
    win->end();
    win->show();
    return Fl::run();
}
fltk/options.cppC++ / 82 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Radio_Round_Button.H>
#include <FL/Fl_Check_Button.H>
#include <FL/Fl_Box.H>

enum {
    spacing = 2,
    button_w = 150,
    button_h = 40,
    option_w = 120,
    option_h = 20,
    letter_size = 90
};

struct controls {
    Fl_Radio_Round_Button *rb[3];
    Fl_Check_Button *cb;
    Fl_Box *box;
};

static const int colors[]        = { FL_RED, FL_GREEN, FL_BLUE };
static const char *const colnames[] = { "red", "green", "blue" };

static void set_callback(Fl_Widget *w, void *user)
{
    controls *c = (controls*)user;
    int i;
    for(i = 0; i < 3; i++) {
        if(c->rb[i]->value()) {
            c->box->color(colors[i]);
            break;
        }
    }
    c->box->label(c->cb->value() ? "A" : "");
}

static void exit_callback(Fl_Widget *, void *)
{
    exit(0);
}

int main()
{
    int win_w = button_w * 2 + spacing * 3;
    int win_h = option_h * 4 + button_h + spacing * 7;
    Fl_Window *win = new Fl_Window(win_w, win_h, "buttons demo");

    controls *ctrl = new controls;

    int i;
    for(i = 0; i < 3; i++) {
        int y = spacing * (i+1) + option_h * i;
        ctrl->rb[i] = new Fl_Radio_Round_Button(spacing, y,
                            option_w, option_h, colnames[i]);
    }
    ctrl->cb = new Fl_Check_Button(spacing, 5*spacing + 3*option_h,
                                   option_w, option_h, "show letter");

    int box_x = 2 * spacing + option_w;
    int box_w = 2 * button_w + spacing - option_w - spacing;
    int box_h = 4 * option_h + 4 * spacing;
    ctrl->box = new Fl_Box(box_x, spacing, box_w, box_h);
    ctrl->box->labelsize(letter_size);
    ctrl->box->labelcolor(FL_WHITE);
    ctrl->box->box(FL_FLAT_BOX);

    int buttons_y = 6*spacing + 4*option_h;
    Fl_Button *set_b =
        new Fl_Button(spacing, buttons_y, button_w, button_h, "Set!");
    set_b->callback(set_callback, (void*)ctrl);

    Fl_Button *close_b =
        new Fl_Button(2*spacing + button_w,
                      buttons_y, button_w, button_h, "Quit");
    close_b->callback(exit_callback, 0);

    win->end();
    win->show();
    return Fl::run();
}
fltk/resize.cppC++ / 53 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Group.H>
#include <FL/Fl_Box.H>

enum {
    spacing = 5,
    cell_w = 100,
    cell_h = 100,
    num_x = 4,
    num_y = 4,
    labelsz = 50
};

static int cell_x(int n) { return n * (cell_w + spacing) + spacing; }
static int cell_y(int m) { return m * (cell_h + spacing) + spacing; }

static Fl_Box *mkwidget(int n, int m, int cn, int cm, const char *lab)
{
    Fl_Box *b = new Fl_Box(cell_x(n), cell_y(m),
                           cn * cell_w + spacing * (cn-1),
                           cm * cell_h + spacing * (cm-1),
                           lab);
    b->box(FL_EMBOSSED_BOX);
    b->color(FL_WHITE);
    b->labelsize(labelsz);
    return b;
}

int main(int argc, char **argv)
{
    Fl_Window *win =
        new Fl_Window(cell_x(num_x), cell_y(num_y), "resize demo");

    mkwidget(0, 0, 2, 1, "A");
    mkwidget(2, 0, 1, 1, "B");
    mkwidget(3, 0, 1, 1, "C");

    mkwidget(0, 1, 1, 2, "D");
    mkwidget(3, 1, 1, 1, "E");

    mkwidget(3, 2, 1, 2, "F");

    mkwidget(0, 3, 1, 1, "G");
    mkwidget(1, 3, 2, 1, "H");

    Fl_Box *b = mkwidget(1, 1, 2, 2, "R");
    win->resizable(b);

    win->end();
    win->show();
    return Fl::run();
}
fltk/say_it.cppC++ / 69 lines
#include <stdio.h>
#include <stdlib.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Input.H>
#include <FL/Fl_Button.H>

enum {
    spacing = 20,
    input_h = 30,
    label_w = 50,
    button_w = 100,
    button_h = 40
};

static void say_callback(Fl_Widget *w, void *user)
{
    printf("%s\n", ((Fl_Input*)user)->value());
    ((Fl_Input*)user)->take_focus();
}

static void clear_callback(Fl_Widget *w, void *user)
{
    ((Fl_Input*)user)->value("");
    ((Fl_Input*)user)->take_focus();
}

static void exit_callback(Fl_Widget *w, void *)
{
    Fl_Widget *p;
    do {
        p = w->parent();
        if(p)
            w = p;
    } while(p);
    w->hide();
}

int main(int argc, char **argv)
{
    int win_w = button_w * 3 + spacing * 4;
    int win_h = input_h + button_h + spacing * 3;
    Fl_Window *win = new Fl_Window(win_w, win_h, "input demo");

    int inp_w = button_w * 3 + 2 * spacing - label_w;
    Fl_Input *inp = new Fl_Input(spacing + label_w,
                                 spacing, inp_w, input_h, "Type:");
    inp->callback(say_callback, (void*)inp);
    inp->when(FL_WHEN_ENTER_KEY|FL_WHEN_NOT_CHANGED);

    int buttons_y = 2 * spacing + input_h;
    Fl_Button *say_b =
        new Fl_Button(spacing, buttons_y, button_w, button_h, "Say it!");
    say_b->callback(say_callback, (void*)inp);

    Fl_Button *clear_b =
        new Fl_Button(2 * spacing + button_w,
                      buttons_y, button_w, button_h, "Clear");
    clear_b->callback(clear_callback, (void*)inp);

    Fl_Button *close_b =
        new Fl_Button(3 * spacing + 2 * button_w,
                      buttons_y, button_w, button_h, "Quit");
    close_b->callback(exit_callback, 0);

    win->end();
    win->show();
    return Fl::run();
}
fltk/speak.cppC++ / 50 lines
#include <stdio.h>
#include <stdlib.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>

enum {
    spacing = 5,
    button_w = 200,
    button_h = 40,
    font_size = 20
};

static const char *msg[] = {
    "Say hello", "Say goodbye", "Quit"
};

static void say_callback(Fl_Widget *w, void *user)
{
    printf("%s\n", (const char*)user);
}

static void exit_callback(Fl_Widget *, void *)
{
    exit(0);
}

int main(int argc, char **argv)
{
    int win_w = button_w + spacing * 2;
    int win_h = button_h * 3 + spacing * 4;
    Fl_Window *win = new Fl_Window(win_w, win_h, "buttons demo");

    Fl_Button *b[3];
    int i;
    int y = spacing;
    for(i = 0; i < 3; i++) {
        b[i] = new Fl_Button(spacing, y, button_w, button_h, msg[i]);
        b[i]->labelsize(font_size);
        y += button_h + spacing;
    }
    win->end();

    b[0]->callback(say_callback, (void*)"Hello, world!");
    b[1]->callback(say_callback, (void*)"Goodbye, world!");
    b[2]->callback(exit_callback, 0);

    win->show();
    return Fl::run();
}

10.11.1 Introducing FLTK

The book's FLTK 1.3 examples construct windows and child widgets, finish group construction, display the window, and enter the event loop. A small greeting program introduces that lifecycle and the corresponding headers and linkage.

#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>

int main()
{
    Fl_Window *win = new Fl_Window(300, 100, "hello");
    Fl_Box *b = new Fl_Box(0, 0, 300, 100, "Hello, World!");
    b->labelsize(36);
    win->end();
    win->show();
    return Fl::run();
}
g++ -Wall -g hello.cpp -lfltk -o hello
Detailed notes - 10.11.1: Introducing FLTK

1

FLTK: Fast Light Toolkit, a C++ widget library

  • selected because it fits the book's restricted C++ approach
  • concepts learned with one toolkit also help when learning another

2

the examples target the FLTK 1.3 series, especially 1.3.5

  • version and development-history statements describe the book's period

3

the source describes installing development headers and libraries

  • its Debian package example is libfltk1.3-dev
  • custom installation paths require appropriate -I and -L options
  • compiling examples assumes the toolchain can find FLTK

4

window: a rectangular graphical-system surface

  • top-level windows are independent application surfaces
  • the window manager normally supplies their decorations
  • child windows live inside other windows
  • an application may have several top-level windows, including dialogs

5

widget: a distinct interface element

  • button, checkbox, text field, label or containing group
  • widgets may contain other widgets

FLTK treats a window as one kind of widget

  • most ordinary controls are drawn within a window
  • they do not each need a separate native child window

6

hello example: a window titled hello, containing Hello, World!

  • Fl_Window represents the window
  • Fl_Box displays the text
  • Fl supplies common static library operations and event handling

7

include the headers for each class used

  • create a 300 by 100 window
  • create its Fl_Box while the window is the current group

Fl_Window derives from Fl_Group

  • widgets created while a group is current become its children
  • end() finishes that implicit addition interval

8

Fl_Box constructor takes x, y, width, height and optional label

  • ordinary coordinates are relative to the containing window
  • the example's box fills its window

9

labelsize(36) enlarges the displayed text

10

end() completes construction of the group's contents show() displays the window, establishing graphical-system access as needed

Fl::run() enters the event loop

  • return its result as the process status in this example

11

the source builds with g++ and links -lfltk

  • run the resulting executable to see the window
  • Escape uses FLTK's default window-closing behavior in this example
  • decorations can differ with the window manager

12

the initial window moves but has no configured resizing behavior

  • resizing policy is introduced later

13

the short example embeds dimensions and font size as literal constants

  • later examples give layout quantities names
Tests & experiments (3 files) - 10.11.1: Introducing FLTK
Section test01 (10-11)In catalog
MakefileMake / 13 lines
FLTK_DIR = $(HOME)/.app/fltk-1.3.11

CPPFLAGS = -I$(FLTK_DIR)
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDFLAGS = -L$(FLTK_DIR)/lib
LDLIBS = $(shell $(FLTK_DIR)/fltk-config --ldflags)

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
hello.cppC++ / 13 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>

int main(int argc, char **argv)
{
    Fl_Window *win = new Fl_Window(800, 800, "hello");
    Fl_Box *b = new Fl_Box(200, 200, 200, 200, "Hello, World!");
    b->labelsize(36);
    win->end();
    win->show();
    return Fl::run();
}
hello01.cppC++ / 21 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Group.H>
#include <FL/Fl_Box.H>

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

    Fl_Window *win = new Fl_Window(300, 200, "Example");

    Fl_Group *group = new Fl_Group(50, 40, 200, 120);

    Fl_Box *box = new Fl_Box(60, 50, 100, 40, "Text");
    box->labelsize(24);
    group->end();

    win->end();

    win->show();
    return Fl::run();
}

10.11.2 Buttons and callbacks

A button callback receives the widget and application context when the toolkit reports activation. The speaking-buttons example keeps handlers short and locates the intended window for quitting without taking over the event loop.

Two buttons share one callback; the user pointer carries each message:

#include <FL/Fl_Group.H>

static void say_callback(Fl_Widget *w, void *user)
{
    printf("%s\n", (const char *) user);
    fflush(stdout);
}

static void exit_callback(Fl_Widget *w, void *user)
{
    Fl_Widget *p = w;
    while (p->parent())
        p = p->parent();
    p->hide();              // Fl::run returns when no window is shown
}
Show the complete program
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
#include <stdio.h>

enum {
    spacing = 5,
    button_w = 200,
    button_h = 40,
    font_size = 20,
    win_w = button_w + 2 * spacing,
    win_h = 3 * button_h + 4 * spacing
};

static void say_callback(Fl_Widget *w, void *user)
{
    printf("%s\n", (const char *) user);
    fflush(stdout);
}

static void exit_callback(Fl_Widget *w, void *user)
{
    Fl_Widget *p = w;
    while (p->parent())
        p = p->parent();
    p->hide();
}

int main(int argc, char **argv)
{
    static const char *const labels[3] = { "Say hello", "Say goodbye", "Quit" };
    Fl_Window *win = new Fl_Window(win_w, win_h, "buttons demo");
    Fl_Button *b[3];
    int y = spacing;
    for (int i = 0; i < 3; i++) {
        b[i] = new Fl_Button(spacing, y, button_w, button_h, labels[i]);
        b[i]->labelsize(font_size);
        y += button_h + spacing;
    }
    b[0]->callback(say_callback, (void *) "Hello, world!");
    b[1]->callback(say_callback, (void *) "Goodbye, world!");
    b[2]->callback(exit_callback, 0);
    win->end();
    win->show(argc, argv);
    return Fl::run();
}
Detailed notes - 10.11.2: Buttons and callbacks

1

Fl_Box is normally an output widget

  • displays information rather than soliciting an action
  • its displayed information may still change during execution

2

input widgets respond to user actions

  • begin with an ordinary button activated by clicking it
  • an input widget can also be disabled temporarily

3

users may understand graphical controls differently from their developers

  • design the interface with the user's interpretation in mind

4

Fl_Button constructor follows the common widget pattern

  • x, y, width, height, label

5

FLTK supplies the button's pressed/released visual feedback

  • the application must supply the meaningful action

6

callback signature: void function(Fl_Widget *w, void *user)

  • w identifies the initiating widget
  • Fl_Widget is the common widget base type
  • user carries application-specific context

7

register a function and context with the widget's callback method

  • on activation FLTK supplies the widget and saved context

8

the example prints to stdout to keep event handling visible and short

  • a normal GUI application cannot assume the user sees its terminal

9

three buttons: Say hello, Say goodbye and Quit

  • two share a callback that prints the string carried by user
  • Quit can hide the enclosing top-level window

Fl::run finishes when no displayed application windows remain

  • hiding the one main window allows ordinary return from main
  • more orderly than calling exit from the button callback

finding the intended window:

  • parent()->hide() works only if the immediate parent is the window
  • walking parent links to the outermost widget tolerates nested groups

layout uses named width, height, spacing and font-size constants

  • window width = one button width + two margins
  • height = three button heights + four gaps/margins
  • loop builds equal buttons and advances y by height + spacing

retain button pointers to configure callbacks

  • message context differs for the first two buttons
  • Quit needs no message context

10

finish the group, show the window and run the event loop

  • the full example is speak.cpp in the source examples
A static bridge matches the toolkit signature, then invokes a virtual operation on the widget object.
A callback adapter restores object-specific behavior. Open full size - Editable SVG
Tests & experiments (3 files) - 10.11.2: Buttons and callbacks
Section test02 (10-11)In catalog
MakefileMake / 13 lines
FLTK_DIR = $(HOME)/.app/fltk-1.3.11

CPPFLAGS = -I$(FLTK_DIR)
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDFLAGS = -L$(FLTK_DIR)/lib
LDLIBS = $(shell $(FLTK_DIR)/fltk-config --ldflags)

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
button.cppC++ / 57 lines
#include <stdio.h>
#include <stdlib.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>

enum {
    spacing = 5,
    button_w = 200,
    button_h = 40,
    font_size = 20,
    num_buttons = 3
};

static const char *msg[] = {
    "Say hello", "Say goodbye", "Quit"
};


static void say_callback(Fl_Widget *, void *user)
{
    printf("%s\n", (const char*) user);
}

static void exit_callback(Fl_Widget *w, void *)
{
    Fl_Widget *p;
    do {
        p = w->parent();
        if (p)
            w = p;
    } while(p);
    w->hide();
}

int main(int argc, char **argv)
{
    msg[0] = "Bob";
    int win_w = button_w + 2 * spacing;
    int win_h = num_buttons * button_h + (num_buttons + 1) * spacing;
    Fl_Window *win = new Fl_Window(win_w, win_h, "buttons demo");

    Fl_Button *b[3];
    for (int i = 0, y = spacing; i < num_buttons;
         i++, y += button_h + spacing) {
        b[i] = new Fl_Button(spacing, y, button_w, button_h, msg[i]);
        b[i]->labelsize(font_size);
    }
    win->end();

    b[0]->callback(say_callback, (void*)"Hello, world!");
    b[1]->callback(say_callback, (void*)"Goodbye, world!");
    b[2]->callback(exit_callback, 0);

    win->show();
    return Fl::run();
}
hello.cppC++ / 49 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>

static const char hello_msg[] = "hello there";

class ClickableBox : public Fl_Box {
public:
    ClickableBox(int x, int y, int w, int h, const char *label)
        : Fl_Box(x, y, w, h, label) {}

    int handle(int event)
    {
        if (event == FL_PUSH) {
            do_callback();
            return 1;
        }

        return Fl_Box::handle(event);
    }
};

static void say_callback(Fl_Widget *, void *user)
{
    printf("%s\n", (const char*) user);
}

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

    Fl_Window *win = new Fl_Window(300, 200, hello_msg);

    Fl_Group *group = new Fl_Group(20, 20, 260, 160);

    ClickableBox *box =
        new ClickableBox(20, 20, 260, 160, hello_msg);
    box->labelsize(24);
    box->labelcolor(FL_WHITE);
    box->box(FL_FLAT_BOX);
    box->color(FL_GREEN);
    box->callback(say_callback, (void*)hello_msg);

    group->end();

    win->end();

    win->show();
    return Fl::run();
}

10.11.3 Other button types

Checkboxes represent independent choices, while radio buttons select one option within a common parent group. A shared controls structure gives the Set callback access to all widgets needed to update the displayed result.

The callback gets every widget it needs through one structure:

#include <FL/Fl_Box.H>
#include <FL/Fl_Check_Button.H>
#include <FL/Fl_Radio_Round_Button.H>

enum { color_count = 3 };

static const Fl_Color colors[color_count] = { FL_RED, FL_GREEN, FL_BLUE };

struct Controls {
    Fl_Radio_Round_Button *radio[color_count];
    Fl_Check_Button *show_letter;
    Fl_Box *box;
};

static void set_callback(Fl_Widget *w, void *user)
{
    Controls *c = (Controls *) user;
    for (int i = 0; i < color_count; i++) {
        if (c->radio[i]->value())
            c->box->color(colors[i]);
    }
    c->box->label(c->show_letter->value() ? "A" : "");
    c->box->redraw();
}
Show the complete program
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Check_Button.H>
#include <FL/Fl_Radio_Round_Button.H>

enum { color_count = 3 };

static const Fl_Color colors[color_count] = { FL_RED, FL_GREEN, FL_BLUE };
static const char *const color_names[color_count] = { "Red", "Green", "Blue" };

enum {
    spacing = 10,
    option_w = 120,
    option_h = 30,
    button_w = 100,
    button_h = 30,
    box_size = 150,
    win_w = 3 * spacing + option_w + box_size,
    win_h = 3 * spacing + box_size + button_h
};

struct Controls {
    Fl_Radio_Round_Button *radio[color_count];
    Fl_Check_Button *show_letter;
    Fl_Box *box;
};

static void set_callback(Fl_Widget *w, void *user)
{
    Controls *c = (Controls *) user;
    for (int i = 0; i < color_count; i++) {
        if (c->radio[i]->value())
            c->box->color(colors[i]);
    }
    c->box->label(c->show_letter->value() ? "A" : "");
    c->box->redraw();
}

static void exit_callback(Fl_Widget *w, void *user)
{
    w->window()->hide();
}

int main(int argc, char **argv)
{
    static Controls controls;       // must outlive the callbacks
    Fl_Window *win = new Fl_Window(win_w, win_h, "colors");

    for (int i = 0; i < color_count; i++) {
        controls.radio[i] = new Fl_Radio_Round_Button(spacing,
            spacing + i * option_h, option_w, option_h, color_names[i]);
    }
    controls.radio[0]->value(1);
    controls.show_letter = new Fl_Check_Button(spacing,
        spacing + color_count * option_h, option_w, option_h, "Letter A");

    controls.box = new Fl_Box(2 * spacing + option_w, spacing,
                              box_size, box_size);
    controls.box->box(FL_FLAT_BOX);         // filled, so color() shows
    controls.box->labelsize(72);
    controls.box->labelcolor(FL_WHITE);

    int y = 2 * spacing + box_size;
    Fl_Button *set = new Fl_Button(spacing, y, button_w, button_h, "Set");
    set->callback(set_callback, &controls);
    Fl_Button *quit = new Fl_Button(win_w - spacing - button_w, y,
                                    button_w, button_h, "Quit");
    quit->callback(exit_callback, 0);

    win->end();
    win->show(argc, argv);
    return Fl::run();
}
Detailed notes - 10.11.3: Other button types

1

several controls derive from Fl_Button

  • share its interface while offering different interaction behavior

2

Fl_Check_Button: a checkbox with a label

  • clicking toggles its checked state

3

radio buttons represent mutually exclusive choices

  • selecting one clears the others in its group

4

Fl_Radio_Round_Button supplies the familiar circular indicator

  • Fl_Radio_Button provides similar selection behavior with button styling

5

FLTK radio grouping follows the common parent widget

  • separate Fl_Group parents establish independent sets of choices

6

the demonstration combines radio buttons, a checkbox and ordinary buttons

  • chosen radio determines a box's background color
  • checkbox determines whether the box displays A
  • Set applies the choices; Quit closes the window

7

pass all relevant widget pointers in a controls structure

  • callback receives that structure through user
  • avoids global mutable widget pointers

parallel constant arrays associate radio positions with colors and labels

Set callback:

  • use value() to find the selected radio button
  • set the box color from its corresponding entry
  • label is A when checked, otherwise an empty string
  • callback context must outlive its use by the widgets

8

derive layout from six named dimensions/style values

  • radio controls and checkbox occupy the left column
  • color box fills the remaining upper region
  • Set and Quit occupy the bottom row

box setup:

  • large white label
  • FL_FLAT_BOX supplies a filled rectangular background
  • without a drawing box type, a label-only box remains transparent

register Set with the controls pointer, then end/show/run the window

  • changing state and requesting redraw are distinct operations; redraw explicitly when the changed property requires it

9

the same callback could be registered on the options for immediate updates

  • the author prefers an explicit Set action
  • that is a UI-design preference; choose the behavior for the task
Tests & experiments (4 files) - 10.11.3: Other button types
Section test03 (10-11)In catalog
MakefileMake / 13 lines
FLTK_DIR = $(HOME)/.app/fltk-1.3.11

CPPFLAGS = -I$(FLTK_DIR)
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDFLAGS = -L$(FLTK_DIR)/lib
LDLIBS = $(shell $(FLTK_DIR)/fltk-config --ldflags)

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
buttons.cppC++ / 91 lines
#include <stdio.h>
#include <stdlib.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Radio_Round_Button.H>
#include <FL/Fl_Check_Button.H>
#include <FL/Fl_Box.H>

enum {
    spacing = 2,
    button_w = 150,
    button_h = 40,
    option_w = 120,
    option_h = 20,
    letter_size = 90,
    num_radio_buttons = 3
};

static const int colors[] = { FL_RED, FL_GREEN, FL_BLUE };
static const char *const colnames[] = { "red", "green", "blue" };
static const char *const check_button_name = "show letter";
static const char *const buttons_name[] = { "Set!", "Quit" };

struct controls {
    Fl_Radio_Round_Button *rb[num_radio_buttons];
    Fl_Check_Button *cb;
    Fl_Box *box;
};

static void set_callback(Fl_Widget *w, void *user)
{
    controls *c = (controls*)user;
    for (int i = 0; i < num_radio_buttons; i++)
        if (c->rb[i]->value()) {
            c->box->color(colors[i]);
            break;
        }
    c->box->label(c->cb->value() ? "A" : "");
}

static void exit_callback(Fl_Widget *w, void *)
{
    Fl_Widget *p;
    do {
        p = w->parent();
        if (p)
            w = p;
    } while(p);
    w->hide();
}

int main(int argc, char **argv)
{
    int win_w = 2 * button_w + 3 * spacing;
    int win_h = 4 * option_h + button_h + 7 * spacing;
    Fl_Window *win = new Fl_Window(win_w, win_h, "buttons demo");

    controls *ctrl = new controls;

    for (int i = 0; i < num_radio_buttons; i++) {
        int y = spacing * (i + 1) + option_h * i;
        ctrl->rb[i] = new Fl_Radio_Round_Button(spacing, y,
                                                option_w, option_h,
                                                colnames[i]);
    }
    ctrl->cb = new Fl_Check_Button(spacing, 5 * spacing + 3 * option_h,
                                   option_w, option_h, check_button_name);

    int box_x = 2 * spacing + option_w;
    int box_w = 2 * button_w + spacing - option_w - spacing;
    int box_h = 4 * option_h + 4 * spacing;
    ctrl->box = new Fl_Box(box_x, spacing, box_w, box_h);
    ctrl->box->labelsize(letter_size);
    ctrl->box->labelcolor(FL_WHITE);
    ctrl->box->box(FL_FLAT_BOX);

    int button_y = 6 * spacing + 4 * option_h;
    Fl_Button *set_b = new Fl_Button(spacing, button_y,
                                     button_w, button_h, buttons_name[0]);
    set_b->callback(set_callback, (void*)ctrl);

    Fl_Button *close_b = new Fl_Button(2 * spacing + button_w, button_y,
                                       button_w, button_h, buttons_name[1]);
    close_b->callback(exit_callback, 0);

    win->end();

    win->show();
    return Fl::run();
}
buttons01.cppC++ / 99 lines
#include <stdio.h>
#include <stdlib.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Radio_Button.H>
#include <FL/Fl_Check_Button.H>
#include <FL/Fl_Box.H>

enum {
    spacing = 2,
    button_w = 150,
    button_h = 40,
    option_w = 120,
    option_h = 20,
    letter_size = 90,
    num_radio_buttons = 3
};

static const int colors[] = { FL_RED, FL_GREEN, FL_BLUE };
static const char *const colnames[] = { "red", "green", "blue" };
static const char *const check_button_name = "show letter";
static const char *const buttons_name[] = { "Set!", "Quit" };

struct controls {
    Fl_Radio_Button *rb[num_radio_buttons];
    Fl_Check_Button *cb;
    Fl_Box *box;
};

static void set_callback(Fl_Widget *w, void *user)
{
    controls *c = (controls*)user;
    for (int i = 0; i < num_radio_buttons; i++)
        if (c->rb[i]->value()) {
            c->box->color(colors[i]);
            break;
        }
    c->box->label(c->cb->value() ? "A" : "");
}

static void exit_callback(Fl_Widget *w, void *)
{
    Fl_Widget *p;
    do {
        p = w->parent();
        if (p)
            w = p;
    } while(p);
    w->hide();
}

int main(int argc, char **argv)
{
    int win_w = 2 * button_w + 3 * spacing;
    int win_h = 4 * option_h + button_h + 7 * spacing;
    Fl_Window *win = new Fl_Window(win_w, win_h, "buttons demo");

    controls *ctrl = new controls;

    Fl_Group *group = new Fl_Group(0, 0, 200, 120);
    int i = 0;
    int y = spacing * (i + 1) + option_h * i;
    ctrl->rb[i] = new Fl_Radio_Button(spacing, y,
                                      option_w, option_h,
                                      colnames[i]);
    group->end();
    for (i = 1; i < num_radio_buttons; i++) {

        int y = spacing * (i + 1) + option_h * i;
        ctrl->rb[i] = new Fl_Radio_Button(spacing, y,
                                                option_w, option_h,
                                                colnames[i]);
    }
    ctrl->cb = new Fl_Check_Button(spacing, 5 * spacing + 3 * option_h,
                                   option_w, option_h, check_button_name);

    int box_x = 2 * spacing + option_w;
    int box_w = 2 * button_w + spacing - option_w - spacing;
    int box_h = 4 * option_h + 4 * spacing;
    ctrl->box = new Fl_Box(box_x, spacing, box_w, box_h);
    ctrl->box->labelsize(letter_size);
    ctrl->box->labelcolor(FL_WHITE);
    ctrl->box->box(FL_FLAT_BOX);

    int button_y = 6 * spacing + 4 * option_h;
    Fl_Button *set_b = new Fl_Button(spacing, button_y,
                                     button_w, button_h, buttons_name[0]);
    set_b->callback(set_callback, (void*)ctrl);

    Fl_Button *close_b = new Fl_Button(2 * spacing + button_w, button_y,
                                       button_w, button_h, buttons_name[1]);
    close_b->callback(exit_callback, 0);

    win->end();

    win->show();
    return Fl::run();
}
buttons02.cppC++ / 99 lines
#include <stdio.h>
#include <stdlib.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Radio_Round_Button.H>
#include <FL/Fl_Check_Button.H>
#include <FL/Fl_Box.H>

enum {
    spacing = 2,
    button_w = 150,
    button_h = 40,
    option_w = 120,
    option_h = 20,
    letter_size = 90,
    num_radio_buttons = 3
};

static const int colors[] = { FL_RED, FL_GREEN, FL_BLUE };
static const char *const colnames[] = { "red", "green", "blue" };
static const char *const check_button_name = "show letter";
static const char *const buttons_name[] = { "Set!", "Quit" };

struct controls {
    Fl_Radio_Round_Button *rb[num_radio_buttons];
    Fl_Check_Button *cb;
    Fl_Box *box;
};

static void set_callback(Fl_Widget *w, void *user)
{
    controls *c = (controls*)user;
    for (int i = 0; i < num_radio_buttons; i++)
        if (c->rb[i]->value()) {
            c->box->color(colors[i]);
            break;
        }
    c->box->label(c->cb->value() ? "A" : "");
}

static void exit_callback(Fl_Widget *w, void *)
{
    Fl_Widget *p;
    do {
        p = w->parent();
        if (p)
            w = p;
    } while(p);
    w->hide();
}

int main(int argc, char **argv)
{
    int win_w = 2 * button_w + 3 * spacing;
    int win_h = 4 * option_h + button_h + 7 * spacing;
    Fl_Window *win = new Fl_Window(win_w, win_h, "buttons demo");

    controls *ctrl = new controls;

    Fl_Group *group = new Fl_Group(0, 0, 200, 120);
    int i = 0;
    int y = spacing * (i + 1) + option_h * i;
    ctrl->rb[i] = new Fl_Radio_Round_Button(spacing, y,
                                      option_w, option_h,
                                      colnames[i]);
    group->end();
    for (i = 1; i < num_radio_buttons; i++) {

        int y = spacing * (i + 1) + option_h * i;
        ctrl->rb[i] = new Fl_Radio_Round_Button(spacing, y,
                                                option_w, option_h,
                                                colnames[i]);
    }
    ctrl->cb = new Fl_Check_Button(spacing, 5 * spacing + 3 * option_h,
                                   option_w, option_h, check_button_name);

    int box_x = 2 * spacing + option_w;
    int box_w = 2 * button_w + spacing - option_w - spacing;
    int box_h = 4 * option_h + 4 * spacing;
    ctrl->box = new Fl_Box(box_x, spacing, box_w, box_h);
    ctrl->box->labelsize(letter_size);
    ctrl->box->labelcolor(FL_WHITE);
    ctrl->box->box(FL_FLAT_BOX);

    int button_y = 6 * spacing + 4 * option_h;
    Fl_Button *set_b = new Fl_Button(spacing, button_y,
                                     button_w, button_h, buttons_name[0]);
    set_b->callback(set_callback, (void*)ctrl);

    Fl_Button *close_b = new Fl_Button(2 * spacing + button_w, button_y,
                                       button_w, button_h, buttons_name[1]);
    close_b->callback(exit_callback, 0);

    win->end();

    win->show();
    return Fl::run();
}

10.11.4 Text input widgets

Input widgets expose text, cursor position, selection, and edits, while focus and Enter handling shape normal interaction. Larger editing tasks use a text editor with an attached buffer that may be shared with other views.

After a button click, the callback gives the keyboard focus back to the field; when makes Enter call the same callback:

#include <FL/Fl_Input.H>

static void print_callback(Fl_Widget *w, void *user)
{
    Fl_Input *in = (Fl_Input *) user;
    printf("[%s]\n", in->value());
    fflush(stdout);
    in->take_focus();
}

static void clear_callback(Fl_Widget *w, void *user)
{
    Fl_Input *in = (Fl_Input *) user;
    in->value("");
    in->take_focus();
}

void setup_input(Fl_Input *in)
{
    in->callback(print_callback, in);
    in->when(FL_WHEN_ENTER_KEY | FL_WHEN_NOT_CHANGED);
}

Editing operations work on character positions:

void edit_demo(Fl_Input *in)
{
    in->position(0, in->size());    // select the whole text
    in->replace(0, 5, "Hi");        // replace the first five characters
    in->insert("!");                // insert at the cursor
    in->undo();
}

Fl_Text_Editor keeps its text in a separate buffer:

#include <FL/Fl_Text_Buffer.H>
#include <FL/Fl_Text_Editor.H>

static void print_text_callback(Fl_Widget *w, void *user)
{
    Fl_Text_Editor *ed = (Fl_Text_Editor *) user;
    char *text = ed->buffer()->text();      // an allocated copy
    fputs(text, stdout);
    fflush(stdout);
    free(text);                             // required by the API
    ed->take_focus();
}

Fl_Text_Editor *make_editor(int x, int y, int w, int h)
{
    Fl_Text_Buffer *buf = new Fl_Text_Buffer;
    Fl_Text_Editor *ed = new Fl_Text_Editor(x, y, w, h, "Text:");
    ed->buffer(buf);
    return ed;
}
Show the complete program
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Input.H>
#include <FL/Fl_Button.H>
#include <stdio.h>

enum {
    spacing = 10,
    label_w = 50,
    input_w = 300,
    input_h = 30,
    button_w = 90,
    button_h = 30,
    win_w = label_w + input_w + 2 * spacing,
    win_h = input_h + button_h + 3 * spacing
};

static void print_callback(Fl_Widget *w, void *user)
{
    Fl_Input *in = (Fl_Input *) user;
    printf("[%s]\n", in->value());
    fflush(stdout);
    in->take_focus();
}

static void clear_callback(Fl_Widget *w, void *user)
{
    Fl_Input *in = (Fl_Input *) user;
    in->value("");
    in->take_focus();
}

static void exit_callback(Fl_Widget *w, void *user)
{
    w->window()->hide();
}

int main(int argc, char **argv)
{
    Fl_Window *win = new Fl_Window(win_w, win_h, "input demo");
    Fl_Input *in = new Fl_Input(spacing + label_w, spacing,
                                input_w, input_h, "Type:");
    in->callback(print_callback, in);
    in->when(FL_WHEN_ENTER_KEY | FL_WHEN_NOT_CHANGED);

    int y = 2 * spacing + input_h;
    Fl_Button *print = new Fl_Button(spacing, y, button_w, button_h, "Print");
    print->callback(print_callback, in);
    Fl_Button *clear = new Fl_Button(2 * spacing + button_w, y,
                                     button_w, button_h, "Clear");
    clear->callback(clear_callback, in);
    Fl_Button *quit = new Fl_Button(win_w - spacing - button_w, y,
                                    button_w, button_h, "Quit");
    quit->callback(exit_callback, 0);

    win->end();
    win->show(argc, argv);
    return Fl::run();
}
Detailed notes - 10.11.4: Text input widgets

1

three relevant input classes:

  • Fl_Input: one line
  • Fl_Multiline_Input: a simple multiline field
  • Fl_Text_Editor: a fuller text editor

2

Fl_Input takes coordinates, dimensions and an optional label

  • the default label appears to the left, outside the input rectangle
  • leave space for it or position a separate label widget

3

value() returns the current text as const char*

  • value(text) replaces it with the supplied text

4

demo: input field with print, clear and quit buttons

  • pass the input widget pointer to callbacks as user context

5

keyboard focus identifies the widget receiving typed input

  • buttons also use keyboard events, e.g. Space to activate
  • Tab and Shift-Tab move between focusable controls
  • a visual focus indicator shows the active recipient

6

clicking a button can move focus away from the input field

  • the print callback reads value(), then calls take_focus()
  • the clear callback sets value(""), then restores focus

layout reserves space for the input's Type: label

  • input and button dimensions derive from named constants
  • both callbacks receive the same input object

typing followed by Enter should perform the natural primary action

  • requiring a mouse click after typing interrupts that interaction

7

Fl_Input can invoke the same print callback directly

  • when(FL_WHEN_ENTER_KEY | FL_WHEN_NOT_CHANGED)
  • Enter triggers the callback even if the text did not change
  • the default focus-change trigger would serve a different purpose

8

position(): get or set the insertion cursor

  • two-argument form also sets the opposite selection boundary

mark(): get or set that other boundary

  • equal cursor and mark positions mean no selection

9

size() without arguments reports text length

  • do not confuse it with widget size(width, height)

10

replace(begin, end, text) edits a half-open range

  • equal positions insert without deleting
  • empty replacement deletes the selected range
  • cut and insert provide convenient editing forms
  • undo reverses an edit according to the widget's supported undo behavior

11

additional operations are documented by the toolkit

12

Fl_Int_Input and Fl_Float_Input constrain numeric input syntax

  • still validate that the resulting text is a complete acceptable value

Fl_Secret_Input masks displayed characters for password entry

  • these retain the general Fl_Input interface

13

Fl_Multiline_Input displays embedded newlines as separate lines

  • still exposes text as a C-style string
  • limited visible area can hide content without scrollbar controls

14

wrap controls display of long lines

  • enabled: wrap at whitespace
  • disabled: show the visible portion of the original line
  • a very long unbroken word still needs consideration

15

for multiline input, place a label appropriately above the editing region

  • keep Enter available for inserting newlines
  • do not blindly reuse the single-line submit-on-Enter behavior

16

Fl_Text_Editor suits more substantial editing and supplies scrolling

  • text is held in a separate Fl_Text_Buffer
  • buffer->text() returns an allocated copy
  • caller releases that copy with free, as this API requires
  • do not infer the buffer's internal representation from this interface

17

create a buffer and attach it to the editor with buffer(buf)

print callback:

  • obtain the allocated text copy
  • write/flush the output, free the copy, restore focus

clear callback:

  • replace buffer contents with an empty string, restore focus

one buffer may be shared by several editor/display widgets

  • an editor can also be switched among several buffers
  • manage the buffer's lifetime separately from each displayed view

18

the chapter leaves the editor's larger feature set to toolkit documentation

Tests & experiments (17 files) - 10.11.4: Text input widgets
Section test04 (10-11)In catalog
MakefileMake / 13 lines
FLTK_DIR = $(HOME)/.app/fltk-1.3.11

CPPFLAGS = -I$(FLTK_DIR)
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDFLAGS = -L$(FLTK_DIR)/lib
LDLIBS = $(shell $(FLTK_DIR)/fltk-config --ldflags)

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
input.cppC++ / 73 lines
#include <stdio.h>
#include <stdlib.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Input.H>
#include <FL/Fl_Button.H>

enum {
    spacing = 20,
    input_h = 30,
    label_w = 50,
    button_w = 100,
    button_h = 40
};

static void say_callback(Fl_Widget *w, void *user)
{
    Fl_Input *input = (Fl_Input*) user;
    printf("%s\n", input->value());
    input->take_focus();
}

static void clear_callback(Fl_Widget *w, void *user)
{
    Fl_Input *input = (Fl_Input*) user;
    input->value("");
    input->take_focus();
}

static void exit_callback(Fl_Widget *w, void *)
{
    Fl_Widget *p;
    do {
        p = w->parent();
        if (p)
            w = p;
    } while(p);
    w->hide();
}

int main(int argc, char **argv)
{
    int win_w = 3 * button_w + 4 * spacing;
    int win_h = input_h + button_h + 3 * spacing;
    Fl_Window *win = new Fl_Window(win_w, win_h, "input demo");

    int input_w = 3 * button_w + 2 * spacing - label_w;
    Fl_Input *inp =
        new Fl_Input(spacing + label_w, spacing,
                     input_w, input_h, "Type: ");
    inp->callback(say_callback, (void*)inp);
    inp->when(FL_WHEN_ENTER_KEY|FL_WHEN_NOT_CHANGED);

    int buttons_y = 2 * spacing + input_h;
    Fl_Button *say_b =
        new Fl_Button(spacing, buttons_y,
                      button_w, button_h, "Say it!");
    say_b->callback(say_callback, (void*)inp);

    Fl_Button *clear_b =
        new Fl_Button(2 * spacing + button_w, buttons_y,
                      button_w, button_h, "Clear");
    clear_b->callback(clear_callback, (void*)inp);

    Fl_Button *close_b =
        new Fl_Button(3 * spacing + 2 * button_w, buttons_y,
                      button_w, button_h, "Quit");
    close_b->callback(exit_callback, 0);

    win->end();
    win->show();
    return Fl::run();
}
input01.cppC++ / 76 lines
#include <stdio.h>
#include <stdlib.h>
#include <FL/Fl.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Input.H>
#include <FL/Fl_Button.H>

enum {
    spacing = 20,
    input_h = 30,
    label_w = 50,
    button_w = 100,
    button_h = 40
};

static void say_callback(Fl_Widget *w, void *user)
{
    Fl_Input *input = (Fl_Input*) user;
    printf("%s\n", input->value());
    input->take_focus();
}

static void clear_callback(Fl_Widget *w, void *user)
{
    Fl_Input *input = (Fl_Input*) user;
    input->value("");
    input->take_focus();
}

static void exit_callback(Fl_Widget *w, void *)
{
    Fl_Widget *p;
    do {
        p = w->parent();
        if (p)
            w = p;
    } while(p);
    w->hide();
}

int main(int argc, char **argv)
{
    int win_w = 3 * button_w + 4 * spacing;
    int win_h = input_h + button_h + 3 * spacing;
    Fl_Window *win = new Fl_Window(win_w, win_h, "input demo");

    new Fl_Box(spacing, spacing, label_w, input_h, "Type: ");

    int input_w = 3 * button_w + 2 * spacing - label_w;
    Fl_Input *inp =
        new Fl_Input(spacing + label_w, spacing,
                     input_w, input_h);
    inp->callback(say_callback, (void*)inp);
    inp->when(FL_WHEN_ENTER_KEY|FL_WHEN_NOT_CHANGED);

    int buttons_y = 2 * spacing + input_h;
    Fl_Button *say_b =
        new Fl_Button(spacing, buttons_y,
                      button_w, button_h, "Say it!");
    say_b->callback(say_callback, (void*)inp);

    Fl_Button *clear_b =
        new Fl_Button(2 * spacing + button_w, buttons_y,
                      button_w, button_h, "Clear");
    clear_b->callback(clear_callback, (void*)inp);

    Fl_Button *close_b =
        new Fl_Button(3 * spacing + 2 * button_w, buttons_y,
                      button_w, button_h, "Quit");
    close_b->callback(exit_callback, 0);

    win->end();
    win->show();
    return Fl::run();
}
input02.cppC++ / 73 lines
#include <stdio.h>
#include <stdlib.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Input.H>
#include <FL/Fl_Button.H>

enum {
    spacing = 20,
    input_h = 30,
    label_w = 50,
    button_w = 100,
    button_h = 40
};

static void say_callback(Fl_Widget *w, void *user)
{
    Fl_Input *input = (Fl_Input*) user;
    printf("%s\n", input->value());
    input->take_focus();
}

static void clear_callback(Fl_Widget *w, void *user)
{
    Fl_Input *input = (Fl_Input*) user;
    input->value("");
    input->take_focus();
}

static void exit_callback(Fl_Widget *w, void *)
{
    Fl_Widget *p;
    do {
        p = w->parent();
        if (p)
            w = p;
    } while(p);
    w->hide();
}

int main(int argc, char **argv)
{
    int win_w = 3 * button_w + 4 * spacing;
    int win_h = input_h + button_h + 3 * spacing;
    Fl_Window *win = new Fl_Window(win_w, win_h, "input demo");

    int input_w = 3 * button_w + 2 * spacing - label_w;
    Fl_Input *inp =
        new Fl_Input(spacing + label_w, spacing,
                     input_w, input_h, "Type: ");
    inp->callback(say_callback, (void*)inp);
    inp->when(FL_WHEN_ENTER_KEY|FL_WHEN_NOT_CHANGED);

    int buttons_y = 2 * spacing + input_h;
    Fl_Button *say_b =
        new Fl_Button(spacing, buttons_y,
                      button_w, button_h, "Say it!");
    say_b->callback(say_callback, (void*)inp);

    Fl_Button *clear_b =
        new Fl_Button(2 * spacing + button_w, buttons_y,
                      button_w, button_h, "Clear");
    clear_b->callback(clear_callback, (void*)inp);

    Fl_Button *close_b =
        new Fl_Button(3 * spacing + 2 * button_w, buttons_y,
                      button_w, button_h, "Quit");
    close_b->callback(exit_callback, 0);

    win->end();
    win->show();
    return Fl::run();
}
input03.cppC++ / 69 lines
#include <stdio.h>
#include <stdlib.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Input.H>
#include <FL/Fl_Button.H>

enum {
    spacing = 20,
    input_h = 30,
    label_w = 50,
    button_w = 100,
    button_h = 40
};

static void say_callback(Fl_Widget *w, void *user)
{
    Fl_Input *input = static_cast<Fl_Input*>(user);
    printf("%s\n", input->value());
    input->take_focus();
}

static void clear_callback(Fl_Widget *w, void *user)
{
    Fl_Input *input = static_cast<Fl_Input*>(user);
    input->value("");
    input->take_focus();
}

static void exit_callback(Fl_Widget *w, void *)
{
    Fl_Widget *p;
    do {
        p = w->parent();
        if (p)
            w = p;
    } while(p);
    w->hide();
}

int main(int argc, char **argv)
{
    int win_w = 3 * button_w + 4 * spacing;
    int win_h = input_h + button_h + 3 * spacing;
    Fl_Window *win = new Fl_Window(win_w, win_h, "input demo");

    int input_w = 3 * button_w + 2 * spacing - label_w;
    Fl_Input *inp = new Fl_Input(spacing + label_w, spacing,
                                 input_w, input_h, "Type: ");
    inp->callback(say_callback, (void*)inp);
    inp->when(FL_WHEN_ENTER_KEY|FL_WHEN_NOT_CHANGED);

    int buttons_y = 2 * spacing + input_h;
    Fl_Button *say_b = new Fl_Button(spacing, buttons_y,
                                     button_w, button_h, "Say it!");
    say_b->callback(say_callback, (void*)inp);

    Fl_Button *clear_b = new Fl_Button(2 * spacing + button_w, buttons_y,
                                       button_w, button_h, "Clear");
    clear_b->callback(clear_callback, (void*)inp);

    Fl_Button *close_b = new Fl_Button(3 * spacing + 2 * button_w, buttons_y,
                                       button_w, button_h, "Quit");
    close_b->callback(exit_callback, 0);

    win->end();
    win->show();
    return Fl::run();
}
input_methods00.cppC++ / 42 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Input.H>

enum {
    spacing = 10,
    input_w = 500,
    input_h = 50,
    label_w = 50,
    font_size = 20
};

static void say_callback(Fl_Widget *w, void *user)
{
    Fl_Input *input = static_cast<Fl_Input*>(user);
    printf("%s\n", input->value());
    input->take_focus();
}


int main(int argc, char **argv)
{
    int win_w = label_w + input_w + 3 * spacing;
    int win_h = input_h + 2 * spacing;
    Fl_Window *win = new Fl_Window(win_w, win_h, "input demo");

    Fl_Input *inp = new Fl_Input(spacing + label_w, spacing,
                                 input_w, input_h, "Type: ");
    inp->callback(say_callback, (void*)inp);
    inp->when(FL_WHEN_ENTER_KEY|FL_WHEN_NOT_CHANGED);
    inp->textsize(font_size);
    inp->labelsize(font_size);

    inp->textcolor(FL_GRAY);
    inp->color(FL_BLACK);
    inp->cursor_color(FL_GRAY);

    win->end();
    win->show();
    return Fl::run();
}
input_methods01.cppC++ / 49 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Input.H>

enum {
    spacing = 10,
    input_w = 500,
    input_h = 50,
    label_w = 50,
    font_size = 20
};

static void say_callback(Fl_Widget *w, void *user)
{
    Fl_Input *input = static_cast<Fl_Input*>(user);
    printf("%s\n", input->value());
    input->take_focus();
}


int main(int argc, char **argv)
{
    int win_w = label_w + input_w + 3 * spacing;
    int win_h = input_h + 2 * spacing;
    Fl_Window *win = new Fl_Window(win_w, win_h, "input demo");

    Fl_Input *inp = new Fl_Input(spacing + label_w, spacing,
                                 input_w, input_h, "Type: ");
    inp->callback(say_callback, (void*)inp);
    inp->when(FL_WHEN_ENTER_KEY|FL_WHEN_NOT_CHANGED);
    inp->value("hello there");
    inp->textsize(font_size);
    inp->labelsize(font_size);

    inp->textcolor(FL_GRAY);
    inp->color(FL_BLACK);
    inp->cursor_color(FL_GRAY);

    inp->position(1);
    inp->mark(9);
    int size = inp->size();
    inp->size(200, 50);
    printf("%d\n", size);

    win->end();
    win->show();
    return Fl::run();
}
input_methods02.cppC++ / 45 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Input.H>

enum {
    spacing = 10,
    input_w = 500,
    input_h = 50,
    label_w = 50,
    font_size = 20
};

static void say_callback(Fl_Widget *w, void *user)
{
    Fl_Input *input = static_cast<Fl_Input*>(user);
    printf("%s\n", input->value());
    input->take_focus();
}

int main(int argc, char **argv)
{
    int win_w = label_w + input_w + 3 * spacing;
    int win_h = input_h + 2 * spacing;
    Fl_Window *win = new Fl_Window(win_w, win_h, "input demo");

    Fl_Input *inp = new Fl_Input(spacing + label_w, spacing,
                                 input_w, input_h, "Type: ");
    inp->callback(say_callback, (void*)inp);
    inp->when(FL_WHEN_ENTER_KEY|FL_WHEN_NOT_CHANGED);
    inp->value("hello there");
    inp->textsize(font_size);
    inp->labelsize(font_size);

    inp->textcolor(FL_GRAY);
    inp->color(FL_BLACK);
    inp->cursor_color(FL_GRAY);

    inp->position(1);
    inp->insert("boom");

    win->end();
    win->show();
    return Fl::run();
}
input_methods03.cppC++ / 40 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Int_Input.H>

enum {
    spacing = 10,
    input_w = 500,
    input_h = 50,
    label_w = 50,
    font_size = 20
};

static void undo_callback(Fl_Widget *w, void *user)
{
    Fl_Int_Input *input = static_cast<Fl_Int_Input*>(user);
    input->undo();
}

int main(int argc, char **argv)
{
    int win_w = label_w + input_w + 3 * spacing;
    int win_h = input_h + 2 * spacing;
    Fl_Window *win = new Fl_Window(win_w, win_h, "input demo");

    Fl_Int_Input *inp = new Fl_Int_Input(spacing + label_w, spacing,
                                 input_w, input_h, "Type: ");
    inp->callback(undo_callback, (void*)inp);
    inp->when(FL_WHEN_ENTER_KEY|FL_WHEN_NOT_CHANGED);
    inp->textsize(font_size);
    inp->labelsize(font_size);

    inp->textcolor(FL_GRAY);
    inp->color(FL_BLACK);
    inp->cursor_color(FL_GRAY);

    win->end();
    win->show();
    return Fl::run();
}
input_methods04.cppC++ / 41 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Float_Input.H>

enum {
    spacing = 10,
    input_w = 500,
    input_h = 50,
    label_w = 50,
    font_size = 20
};

static void say_callback(Fl_Widget *w, void *user)
{
    Fl_Input *input = static_cast<Fl_Input*>(user);
    printf("%s\n", input->value());
    input->take_focus();
}

int main(int argc, char **argv)
{
    int win_w = label_w + input_w + 3 * spacing;
    int win_h = input_h + 2 * spacing;
    Fl_Window *win = new Fl_Window(win_w, win_h, "input demo");

    Fl_Float_Input *inp = new Fl_Float_Input(spacing + label_w, spacing,
                                 input_w, input_h, "Type: ");
    inp->callback(say_callback, (void*)inp);
    inp->when(FL_WHEN_ENTER_KEY|FL_WHEN_NOT_CHANGED);
    inp->textsize(font_size);
    inp->labelsize(font_size);

    inp->textcolor(FL_GRAY);
    inp->color(FL_BLACK);
    inp->cursor_color(FL_GRAY);

    win->end();
    win->show();
    return Fl::run();
}
input_methods05.cppC++ / 41 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Secret_Input.H>

enum {
    spacing = 10,
    input_w = 500,
    input_h = 50,
    label_w = 50,
    font_size = 20
};

static void say_callback(Fl_Widget *w, void *user)
{
    Fl_Secret_Input *input = static_cast<Fl_Secret_Input*>(user);
    printf("%s\n", input->value());
    input->take_focus();
}

int main(int argc, char **argv)
{
    int win_w = label_w + input_w + 3 * spacing;
    int win_h = input_h + 2 * spacing;
    Fl_Window *win = new Fl_Window(win_w, win_h, "input demo");

    Fl_Secret_Input *inp = new Fl_Secret_Input(spacing + label_w, spacing,
                                 input_w, input_h, "Type: ");
    inp->callback(say_callback, (void*)inp);
    inp->when(FL_WHEN_ENTER_KEY|FL_WHEN_NOT_CHANGED);
    inp->textsize(font_size);
    inp->labelsize(font_size);

    inp->textcolor(FL_GRAY);
    inp->color(FL_BLACK);
    inp->cursor_color(FL_GRAY);

    win->end();
    win->show();
    return Fl::run();
}
multiline_input.cppC++ / 27 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Multiline_Input.H>

enum {
    input_w = 500,
    input_h = 200,
    font_size = 30
};

int main(int argc, char **argv)
{
    Fl_Window *win = new Fl_Window(input_w, input_h, "input demo");

    Fl_Multiline_Input *inp = new Fl_Multiline_Input(0, 0, input_w, input_h);
    inp->textsize(font_size);
    inp->labelsize(font_size);
    inp->textcolor(FL_GRAY);
    inp->color(FL_BLACK);
    inp->cursor_color(FL_GRAY);
    inp->wrap(1);

    win->end();
    win->show();
    return Fl::run();
}
multiline_input01.cppC++ / 32 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Multiline_Input.H>

enum {
    input_w = 500,
    input_h = 200,
    font_size = 30,
    box_h = 30
};

int main(int argc, char **argv)
{
    Fl_Window *win = new Fl_Window(input_w, input_h, "input demo");

    Fl_Box *box = new Fl_Box(0, 0, input_w, box_h, "multiline input");
    box->labelsize(font_size);

    Fl_Multiline_Input *inp = new Fl_Multiline_Input(0, box_h, input_w, input_h);
    inp->textsize(font_size);
    inp->labelsize(font_size);
    inp->textcolor(FL_GRAY);
    inp->color(FL_BLACK);
    inp->cursor_color(FL_GRAY);
    inp->wrap(1);

    win->end();
    win->show();
    return Fl::run();
}
text_editor.cppC++ / 40 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Text_Editor.H>

enum {
    input_w = 1000,
    input_h = 1000,
    font_size = 40
};

static void print_callback(Fl_Widget *w, void *user)
{
    Fl_Text_Editor *editor = static_cast<Fl_Text_Editor*>(user);
    char* str = editor->buffer()->text();
    fputs(str, stdout);
    fflush(stdout);
    free(str);
    editor->take_focus();
}

int main(int argc, char **argv)
{
    Fl_Window *win = new Fl_Window(input_w, input_h, "input demo");

    Fl_Text_Buffer *buf = new Fl_Text_Buffer;
    Fl_Text_Editor *ed = new Fl_Text_Editor(0, 0, input_w, input_h);
    ed->buffer(buf);
    ed->textsize(font_size);
    ed->labelsize(font_size);
    ed->textcolor(FL_GRAY);
    ed->color(FL_BLACK);
    ed->cursor_color(FL_GRAY);

    ed->callback(print_callback, (void*)ed);

    win->end();
    win->show();
    return Fl::run();
}
text_editor01.cppC++ / 56 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Text_Editor.H>

enum {
    input_w = 1000,
    input_h = 1000,
    button_h = 100,
    font_size = 40
};

static void print_callback(Fl_Widget *w, void *user)
{
    Fl_Text_Editor *editor = static_cast<Fl_Text_Editor*>(user);
    char* str = editor->buffer()->text();
    fputs(str, stdout);
    fflush(stdout);
    free(str);
    editor->take_focus();
}

static void clear_callback(Fl_Widget *w, void *user)
{
    Fl_Text_Editor *editor = static_cast<Fl_Text_Editor*>(user);
    editor->buffer()->text("");
    editor->take_focus();
}

int main(int argc, char **argv)
{
    Fl_Window *win = new Fl_Window(input_w, input_h + button_h, "input demo");

    Fl_Text_Buffer *buf = new Fl_Text_Buffer;
    Fl_Text_Editor *ed = new Fl_Text_Editor(0, 0, input_w, input_h);
    ed->buffer(buf);
    ed->textsize(font_size);
    ed->textcolor(FL_GRAY);
    ed->color(FL_BLACK);
    ed->cursor_color(FL_GRAY);

    Fl_Button *print_b = new Fl_Button(0, input_h,
                                     input_w / 2, button_h, "Print");
    print_b->callback(print_callback, (void*)ed);
    print_b->labelsize(font_size);

    Fl_Button *clear_b = new Fl_Button(input_w / 2, input_h,
                                     input_w / 2, button_h, "Clear");
    clear_b->callback(clear_callback, (void*)ed);
    clear_b->labelsize(font_size);

    win->end();
    win->show();
    return Fl::run();
}
text_editor02.cppC++ / 64 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Text_Editor.H>

enum {
    input_w = 2000,
    input_h = 1000,
    button_h = 100,
    font_size = 40
};

static void print_callback(Fl_Widget *w, void *user)
{
    Fl_Text_Editor *editor = static_cast<Fl_Text_Editor*>(user);
    char* str = editor->buffer()->text();
    fputs(str, stdout);
    fflush(stdout);
    free(str);
    editor->take_focus();
}

static void clear_callback(Fl_Widget *w, void *user)
{
    Fl_Text_Editor *editor = static_cast<Fl_Text_Editor*>(user);
    editor->buffer()->text("");
    editor->take_focus();
}

int main(int argc, char **argv)
{
    Fl_Window *win = new Fl_Window(input_w, input_h + button_h, "input demo");

    Fl_Text_Buffer *buf = new Fl_Text_Buffer;

    Fl_Text_Editor *ed1 = new Fl_Text_Editor(0, 0, input_w / 2, input_h);
    ed1->textsize(font_size);
    ed1->buffer(buf);
    ed1->textcolor(FL_GRAY);
    ed1->color(FL_BLACK);
    ed1->cursor_color(FL_GRAY);

    Fl_Text_Editor *ed2 = new Fl_Text_Editor(input_w / 2, 0, input_w / 2, input_h);
    ed2->textsize(font_size);
    ed2->buffer(buf);
    ed2->textcolor(FL_GRAY);
    ed2->color(FL_BLACK);
    ed2->cursor_color(FL_GRAY);

    Fl_Button *print_b = new Fl_Button(0, input_h,
                                     input_w / 2, button_h, "Print");
    print_b->callback(print_callback, (void*)ed1);
    print_b->labelsize(font_size);

    Fl_Button *clear_b = new Fl_Button(input_w / 2, input_h,
                                     input_w / 2, button_h, "Clear");
    clear_b->callback(clear_callback, (void*)ed2);
    clear_b->labelsize(font_size);

    win->end();
    win->show();
    return Fl::run();
}
text_editor03.cppC++ / 70 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Text_Editor.H>

struct controls {
    Fl_Text_Editor *ed;
    Fl_Text_Buffer *buf1;
    Fl_Text_Buffer *buf2;
};

enum {
    input_w = 1000,
    input_h = 1000,
    button_h = 100,
    font_size = 40
};

static void print_callback(Fl_Widget *w, void *user)
{
    controls *ctrl = static_cast<controls*>(user);
    char* str = ctrl->ed->buffer()->text();
    fputs(str, stdout);
    fflush(stdout);
    free(str);
    ctrl->ed->take_focus();
}

static void buffer_callback(Fl_Widget *w, void *user)
{
    controls *ctrl = static_cast<controls*>(user);
    Fl_Text_Buffer *buf =
        ctrl->ed->buffer() == ctrl->buf1 ? ctrl->buf2 : ctrl->buf1;
    ctrl->ed->buffer(buf);
    ctrl->ed->take_focus();
}

int main(int argc, char **argv)
{
    controls *ctrl = new controls;

    Fl_Window *win = new Fl_Window(input_w, input_h + button_h, "input demo");

    ctrl->buf1 = new Fl_Text_Buffer;
    ctrl->buf2 = new Fl_Text_Buffer;

    Fl_Text_Editor *ed = new Fl_Text_Editor(0, 0, input_w, input_h);
    ed->textsize(font_size);
    ed->buffer(ctrl->buf1);
    ed->textcolor(FL_GRAY);
    ed->color(FL_BLACK);
    ed->cursor_color(FL_GRAY);
    ed->resize(ed->x(), ed->y(), ed->w(), ed->h());
    ctrl->ed = ed;

    Fl_Button *print_b = new Fl_Button(0, input_h,
                                       input_w / 2, button_h, "Print");
    print_b->callback(print_callback, (void*)ctrl);
    print_b->labelsize(font_size);

    Fl_Button *clear_b = new Fl_Button(input_w / 2, input_h,
                                     input_w / 2, button_h, "Buffer");
    clear_b->callback(buffer_callback, (void*)ctrl);
    clear_b->labelsize(font_size);

    win->end();
    win->show();
    return Fl::run();
}

10.11.5 Boxes and labels

Widget presentation separates box style, background, label color, alignment, and font. Label storage also has lifetime consequences: label retains a text pointer, while copy_label creates library-managed storage.

#include <FL/Fl_Box.H>

void style_box(Fl_Box *box)
{
    box->box(FL_UP_BOX);
    box->color(fl_rgb_color(255, 240, 200));
    box->labelcolor(FL_DARK_BLUE);
    box->labelfont(FL_COURIER_BOLD);
    box->labelsize(24);
    box->align(FL_ALIGN_INSIDE | FL_ALIGN_BOTTOM);
}

void show_count(Fl_Box *box, int count)
{
    char buf[64];
    sprintf(buf, "%d items", count);
    box->copy_label(buf);   // label(buf) would keep a pointer to buf
}

Label text starting or ending with @ shows a built-in symbol:

Label Result
@>> double arrow pointing right
@8>> pointing up (keypad direction 8)
@00270>> pointing down (rotated by 270 degrees)
@+93>> larger, pointing down-right
@$--> arrow reflected horizontally
@%fileprint printer symbol flipped vertically
@-> Next symbol, then text
name@@host a literal at-sign
Detailed notes - 10.11.5: Boxes and labels

1

Fl_Widget supplies common presentation properties

  • colors, box style and labels
  • particular widget types interpret or ignore properties as appropriate
  • Fl_Box is specifically useful for a drawn box/frame and optional label

2

box() chooses the frame/background style

  • box styles fill the interior with the widget background color
  • frame-only styles draw a border without filling the interior
  • FL_NO_BOX draws neither, so background color has no filling effect

3

color() selects a background color value

  • named colors include the ordinary primaries and dark variants
  • semantic values include foreground, background, inactive and selection
  • fl_rgb_color(r, g, b) constructs a color from component values

4

labelcolor() separately selects the label text color

5

label(text) retains the supplied text pointer

  • its storage must remain valid and suitable while used

copy_label(text) copies the text into library-managed storage

  • appropriate for generated results or short-lived application buffers
  • a permanent string literal normally needs no extra copy

6

constructor-supplied labels also retain their text pointer

  • the same lifetime requirement applies

7

@ introduces a built-in graphical symbol within a label

  • write @@ when a literal at-sign is required by this label syntax

8

built-in symbols can be resized, reflected and rotated

  • further symbols can be added through the toolkit's drawing support

9

symbol modifiers follow @ before the symbol name

  • signed size adjustment, e.g. -9 through +9
  • $ reflects horizontally; % reflects vertically
  • keypad direction digit or zero-prefixed angle selects rotation

keypad examples: 6 faces right, 8 up, 4 left, 2 down

  • the longer numeric form supplies an angle in degrees

10

@8>> and @00090>> point the double-arrow symbol upward

  • @2>> and @00270>> point it downward
  • @+93>> enlarges it and points it down-right
  • @$--> reflects an arrow; @%fileprint flips the printer symbol

11

the labelpics example demonstrates combinations of these modifiers

12

symbol parsing expects symbols at label boundaries

  • a leading symbol ends at the separating space
  • a trailing symbol uses the remaining symbol text
  • text can sit between leading and trailing symbols
  • account for the parser's spacing conventions in the book's version

13

align() combines FL_ALIGN_ flags to position the label

  • boxes/buttons normally center labels
  • input fields normally place labels to the left

14

FL_ALIGN_INSIDE moves alignment to the widget's interior

  • combine with directions using bitwise OR
  • INSIDE | BOTTOM puts the label just inside the lower edge
  • BOTTOM alone places it below the widget
  • distinguish corner/side variants when selecting combined flags

15

FL_ALIGN_WRAP wraps labels within the allocated width

  • explicit newlines also create multiline labels

16

labelcolor and labelsize set label color and font size

17

labelfont selects a font family/style

  • Helvetica, Courier, Times and Screen are the examples
  • supported bold/italic variants have predefined identifiers
  • the book also combines family/style numeric constants

18

Helvetica is sans serif; Times has serifs; Courier is monospaced

  • monospaced text is useful for source code and alignment-sensitive text
  • the author's screen/print preferences are typography recommendations

19

the author found Screen selection unpredictable in his environments

  • uses Courier when an explicitly monospaced display is wanted

20

the fonts example displays available variants

  • exact appearance depends on the graphical platform's fonts

21

labeltype selects label rendering effects and more complex label forms

  • shadow, engraved and image-related presentations are examples

22

some controls rely on their drawing style for correct repainting

  • arbitrary decorative box changes can disrupt input-field rendering
  • preserve the functional appearance of interactive controls
Tests & experiments (14 files) - 10.11.5: Boxes and labels
Section test05 (10-11)In catalog
MakefileMake / 13 lines
FLTK_DIR = $(HOME)/.app/fltk-1.3.11

CPPFLAGS = -I$(FLTK_DIR)
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDFLAGS = -L$(FLTK_DIR)/lib
LDLIBS = $(shell $(FLTK_DIR)/fltk-config --ldflags)

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
box.cppC++ / 15 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>

int main()
{
    Fl_Window *win = new Fl_Window(1000, 1000, "window");

    win->box(FL_OVAL_FRAME);
    win->color(FL_DARK_BLUE);

    win->end();
    win->show();

    return Fl::run();
}
box01.cppC++ / 27 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>

enum {
    width = 1000,
    height = 1000,
    font_size = 40
};

int main()
{
    Fl_Window *win = new Fl_Window(width, height, "window");
    win->color(FL_BLACK);

    Fl_Box *box = new Fl_Box(0, 0, width, height);
    box->label("@+98-->");
    box->box(FL_DIAMOND_UP_BOX);
    box->color(fl_rgb_color(2, 20, 5));
    box->labelsize(font_size);
    box->labelcolor(FL_GRAY);

    win->end();
    win->show();

    return Fl::run();
}
box02.cppC++ / 25 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>

int main()
{
    Fl_Window *win = new Fl_Window(400, 300, "Pictograms");

    Fl_Box *normal = new Fl_Box(20, 20, 160, 100, "@>>");
    normal->labelsize(40);

    Fl_Box *rotated = new Fl_Box(220, 20, 160, 100, "@8>>");
    rotated->labelsize(40);

    Fl_Box *large = new Fl_Box(20, 150, 160, 100, "@+9>>");
    large->labelsize(40);

    Fl_Box *flipped = new Fl_Box(220, 150, 160, 100, "@$-->");
    flipped->labelsize(40);

    win->end();
    win->show();

    return Fl::run();
}
box03.cppC++ / 27 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>

enum {
    width = 1000,
    height = 1000,
    font_size = 40
};

int main()
{
    Fl_Window *win = new Fl_Window(width, height, "window");
    win->color(FL_BLACK);

    Fl_Box *box = new Fl_Box(0, 0, width, height);
    box->label("@-28fileprint");
    box->box(FL_DIAMOND_UP_BOX);
    box->color(fl_rgb_color(2, 20, 5));
    box->labelsize(font_size);
    box->labelcolor(FL_GRAY);

    win->end();
    win->show();

    return Fl::run();
}
box04.cppC++ / 27 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>

enum {
    width = 1000,
    height = 1000,
    font_size = 40
};

int main()
{
    Fl_Window *win = new Fl_Window(width, height, "window");
    win->color(FL_BLACK);

    Fl_Box *box = new Fl_Box(0, 0, width, height);
    box->label("@-28fileprint");
    box->box(FL_ROUNDED_FRAME);
    box->color(FL_YELLOW);
    box->labelsize(font_size);
    box->labelcolor(FL_GRAY);

    win->end();
    win->show();

    return Fl::run();
}
box05.cppC++ / 22 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>

enum {
    dx = 200,
    dy = 200,
    font_size = 50
};
int main()
{
    Fl_Window *win = new Fl_Window(0, 0, dx, dy);

    Fl_Box *box = new Fl_Box(0, 0, dx, dy, "hello\nthere");
    box->labelsize(font_size);
    box->labelfont(FL_TIMES);

    win->end();
    win->show();

    return Fl::run();
}
buttons.cppC++ / 91 lines
#include <stdio.h>
#include <stdlib.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Radio_Round_Button.H>
#include <FL/Fl_Check_Button.H>
#include <FL/Fl_Box.H>

enum {
    spacing = 2,
    button_w = 150,
    button_h = 40,
    option_w = 120,
    option_h = 20,
    letter_size = 90,
    num_radio_buttons = 3
};

static const int colors[] = { FL_RED, FL_GREEN, FL_BLUE };
static const char *const colnames[] = { "red", "green", "blue" };
static const char *const check_button_name = "show letter";
static const char *const buttons_name[] = { "Set!", "Quit" };

struct controls {
    Fl_Radio_Round_Button *rb[num_radio_buttons];
    Fl_Check_Button *cb;
    Fl_Box *box;
};

static void set_callback(Fl_Widget *w, void *user)
{
    controls *c = (controls*)user;
    for (int i = 0; i < num_radio_buttons; i++)
        if (c->rb[i]->value()) {
            c->box->color(colors[i]);
            break;
        }
    c->box->label(c->cb->value() ? "A" : "");
}

static void exit_callback(Fl_Widget *w, void *)
{
    Fl_Widget *p;
    do {
        p = w->parent();
        if (p)
            w = p;
    } while(p);
    w->hide();
}

int main(int argc, char **argv)
{
    int win_w = 2 * button_w + 3 * spacing;
    int win_h = 4 * option_h + button_h + 7 * spacing;
    Fl_Window *win = new Fl_Window(win_w, win_h, "buttons demo");

    controls *ctrl = new controls;

    for (int i = 0; i < num_radio_buttons; i++) {
        int y = spacing * (i + 1) + option_h * i;
        ctrl->rb[i] = new Fl_Radio_Round_Button(spacing, y,
                                                option_w, option_h,
                                                colnames[i]);
    }
    ctrl->cb = new Fl_Check_Button(spacing, 5 * spacing + 3 * option_h,
                                   option_w, option_h, check_button_name);

    int box_x = 2 * spacing + option_w;
    int box_w = 2 * button_w + spacing - option_w - spacing;
    int box_h = 4 * option_h + 4 * spacing;
    ctrl->box = new Fl_Box(box_x, spacing, box_w, box_h);
    ctrl->box->labelsize(letter_size);
    ctrl->box->labelcolor(FL_WHITE);
    ctrl->box->box(FL_DOWN_FRAME);

    int button_y = 6 * spacing + 4 * option_h;
    Fl_Button *set_b = new Fl_Button(spacing, button_y,
                                     button_w, button_h, buttons_name[0]);
    set_b->callback(set_callback, (void*)ctrl);

    Fl_Button *close_b = new Fl_Button(2 * spacing + button_w, button_y,
                                       button_w, button_h, buttons_name[1]);
    close_b->callback(exit_callback, 0);

    win->end();

    win->show();
    return Fl::run();
}
fonts.cppC++ / 53 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>

Fl_Box **make_box_grid(int w, int h, int spc, int nx, int ny)
{
    int i, j;
    Fl_Box **r = new Fl_Box*[nx * ny];
    for(i = 0; i < nx; i++)
        for(j = 0; j < ny; j++)
             r[i * ny + j] = new Fl_Box((w + spc) * i + spc,
                                        (h + spc) * j + spc, w, h);
    return r;
}

enum {
    spacing = 10,
    box_h = 45,
    box_w = 330,
    count_x = 3,
    count_y = 4,
    labelsize = 35
};

const char * const lab_main[count_x] = { "Helvetica", "Courier", "Times" };
const char * const lab_aux[count_y] = { "", " BOLD", " ITALIC", " B+I" };
const int font_codes[count_x] = { FL_HELVETICA, FL_COURIER, FL_TIMES };
const int font_add[count_y] = { 0, FL_BOLD, FL_ITALIC, FL_BOLD+FL_ITALIC };


int main(int argc, char **argv)
{
    int win_w = (box_w + spacing) * count_x + spacing;
    int win_h = (box_h + spacing) * count_y + spacing;
    Fl_Window *win = new Fl_Window(win_w, win_h, "fonts demo");

    Fl_Box **grid = make_box_grid(box_w, box_h, spacing, count_x, count_y);

    char buf[80];
    for(int n = 0; n < count_x; n++)
        for(int k = 0; k < count_y; k++) {
            sprintf(buf, "%s%s", lab_main[n], lab_aux[k]);
            int idx = n * count_y + k;
            grid[idx]->copy_label(buf);
            grid[idx]->labelfont(font_codes[n] + font_add[k]);
            grid[idx]->labelsize(labelsize);
            grid[idx]->align(FL_ALIGN_CENTER);
        }

    win->end();
    win->show();
    return Fl::run();
}
input.cppC++ / 30 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Input.H>

enum {
    input_w = 500,
    input_h = 100,
    font_size = 30,
    label_w = 100
};

int main(int argc, char **argv)
{
    Fl_Window *win = new Fl_Window(input_w + 2 * label_w, 3 * input_h,
                                   "input demo");

    Fl_Input *inp = new Fl_Input(label_w, input_h, input_w, input_h, "input");
    inp->textsize(font_size);
    inp->labelsize(font_size);
    inp->textcolor(FL_GRAY);
    inp->color(FL_YELLOW);
    inp->cursor_color(FL_GRAY);
    inp->box(FL_ROUNDED_FRAME);
    inp->align(FL_ALIGN_TOP);

    win->end();
    win->show();
    return Fl::run();
}
input01.cppC++ / 47 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Input.H>
#include <FL/Fl_Box.H>

enum {
    spacing = 20,
    label_w = 100,
    input_w = 440,
    input_h = 55,
    hint_h = 35,

    hint_font_size = 16,
    input_font_size = 25,

    input_x = spacing + label_w,
    hint_y = spacing,
    normal_y = hint_y + hint_h + spacing,
    oval_y = normal_y + input_h + spacing,

    win_w = input_x + input_w + spacing,
    win_h = oval_y + input_h + spacing
};

int main()
{
    Fl_Window win(win_w, win_h, "Fl_Input box styles");

    Fl_Box hint(spacing, hint_y, win_w - 2 * spacing, hint_h,
                "Try typing, selecting and deleting text");
    hint.labelsize(hint_font_size);

    Fl_Input normal(input_x, normal_y, input_w, input_h, "Normal:");
    normal.textsize(input_font_size);
    normal.value("Hello world!");

    Fl_Input oval(input_x, oval_y, input_w, input_h, "Oval:");
    oval.box(FL_OFLAT_BOX);
    oval.color(FL_YELLOW);
    oval.textsize(input_font_size);
    oval.value("Hello world!");

    win.end();
    win.show();

    return Fl::run();
}
label_type.cppC++ / 64 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Pixmap.H>

// A tiny red diamond, stored as XPM image data
static const char *const icon_xpm[] = {
    "12 12 2 1",
    "  c None",
    "* c #E33E36",
    "     **     ",
    "    ****    ",
    "   ******   ",
    "  ********  ",
    " ********** ",
    "************",
    "************",
    " ********** ",
    "  ********  ",
    "   ******   ",
    "    ****    ",
    "     **     "
};

enum {
    label_w = 420,
    label_h = 60,
    num_labels = 5,
    space = 20,
    font_size = 30
};

const Fl_Labeltype label_types[] = {
    FL_NORMAL_LABEL, FL_SHADOW_LABEL, FL_ENGRAVED_LABEL, FL_EMBOSSED_LABEL
};

const char * const label_text[] = {
    "Normal", "Shadow", "Engraved", "Embossed", "Image + Text"
};


int main()
{
    int win_w = label_w + 2 * space;
    int win_h = num_labels * label_h + (num_labels + 1) * space;
    Fl_Window win(win_w, win_h, "FLTK label types");

    Fl_Pixmap icon(icon_xpm);
    for (int i = 0; i < num_labels; i++) {
        int y = i * label_h + (i + 1) * space;
        Fl_Box *box = new Fl_Box(space, y, label_w, label_h, label_text[i]);
        box->labelsize(font_size);
        if (i == num_labels - 1) {
            box->image(icon);
            box->align(FL_ALIGN_IMAGE_NEXT_TO_TEXT);
        } else
            box->labeltype(label_types[i]);
    }

    win.end();
    win.show();

    return Fl::run();
}
labels.cppC++ / 52 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>

Fl_Box **make_box_grid(int w, int h, int spc, int nx, int ny)
{
    int i, j;
    Fl_Box **r = new Fl_Box*[nx * ny];
    for(i = 0; i < nx; i++)
        for(j = 0; j < ny; j++)
             r[i * ny + j] = new Fl_Box((w + spc) * i + spc,
                                        (h + spc) * j + spc, w, h);
    return r;
}

enum {
    spacing = 10,
    box_h = 45,
    box_w = 200,
    count_x = 4,
    count_y = 5,
    labelsize = 20
};

const char * const labels[] = {
    "@>>", "@2>>", "@7>>", "@+9>>", "@-200097>>",
    "@fileprint", "@%fileprint", "@3fileprint", "@+5fileprint", "@-28fileprint",
    //"@-->", "@$-->", "@00015-->", "@9-->", "@+99-->",
    "@DnArrow", "@$DnArrow", "@00015DnArrow", "@9DnArrow", "@+99DnArrow",
    "@->|", "@-100345->|", "@00015->|", "@9->|", "@+99->|"
};

int main(int argc, char **argv)
{
    int win_w = (box_w + spacing) * count_x + spacing;
    int win_h = (box_h + spacing) * count_y + spacing;
    Fl_Window *win = new Fl_Window(win_w, win_h, "label icons");

    Fl_Box **grid = make_box_grid(box_w, box_h, spacing, count_x, count_y);

    char buf[80];
    for(int n = 0; n < count_x * count_y; n++) {
        sprintf(buf, "%s  @%s", labels[n], labels[n]);
        grid[n]->labelfont(FL_COURIER);
        grid[n]->labelsize(labelsize);
        grid[n]->copy_label(buf);
        grid[n]->align(FL_ALIGN_BOTTOM_LEFT|FL_ALIGN_INSIDE);
    }
    win->end();
    win->show();
    return Fl::run();
}
text_editor03.cppC++ / 71 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Text_Editor.H>

struct controls {
    Fl_Text_Editor *ed;
    Fl_Text_Buffer *buf1;
    Fl_Text_Buffer *buf2;
};

enum {
    input_w = 1000,
    input_h = 1000,
    button_h = 100,
    font_size = 40
};

static void print_callback(Fl_Widget *w, void *user)
{
    controls *ctrl = static_cast<controls*>(user);
    char* str = ctrl->ed->buffer()->text();
    fputs(str, stdout);
    fflush(stdout);
    free(str);
    ctrl->ed->take_focus();
}

static void buffer_callback(Fl_Widget *w, void *user)
{
    controls *ctrl = static_cast<controls*>(user);
    Fl_Text_Buffer *buf =
        ctrl->ed->buffer() == ctrl->buf1 ? ctrl->buf2 : ctrl->buf1;
    ctrl->ed->buffer(buf);
    ctrl->ed->take_focus();
}

int main(int argc, char **argv)
{
    controls *ctrl = new controls;

    Fl_Window *win = new Fl_Window(input_w, input_h + button_h, "input demo");
    win->box(FL_OVAL_BOX);

    ctrl->buf1 = new Fl_Text_Buffer;
    ctrl->buf2 = new Fl_Text_Buffer;

    Fl_Text_Editor *ed = new Fl_Text_Editor(0, 0, input_w, input_h);
    ed->textsize(font_size);
    ed->buffer(ctrl->buf1);
    ed->textcolor(FL_GRAY);
    ed->color(FL_BLACK);
    ed->cursor_color(FL_GRAY);
    ed->resize(ed->x(), ed->y(), ed->w(), ed->h());
    ctrl->ed = ed;

    Fl_Button *print_b = new Fl_Button(0, input_h,
                                       input_w / 2, button_h, "Print");
    print_b->callback(print_callback, (void*)ctrl);
    print_b->labelsize(font_size);

    Fl_Button *clear_b = new Fl_Button(input_w / 2, input_h,
                                     input_w / 2, button_h, "Buffer");
    clear_b->callback(buffer_callback, (void*)ctrl);
    clear_b->labelsize(font_size);

    win->end();
    win->show();
    return Fl::run();
}

10.11.6 Output widgets

Read-only output widgets make result text selectable without permitting edits. Put the result in the widget's value rather than its label, and use a text display with a buffer for larger scrollable output.

Selectable output goes into a value, not a label:

#include <FL/Fl_Output.H>
#include <FL/Fl_Text_Buffer.H>
#include <FL/Fl_Text_Display.H>

void show_result(Fl_Output *out, double value)
{
    char buf[64];
    sprintf(buf, "%g", value);
    out->value(buf);                    // copied: buf can be reused
}

void make_read_only_look(Fl_Output *out)
{
    out->box(FL_FLAT_BOX);              // still a filled box
    out->color(FL_BACKGROUND_COLOR);
}

Fl_Text_Buffer *make_log(int x, int y, int w, int h)
{
    Fl_Text_Buffer *log = new Fl_Text_Buffer;
    Fl_Text_Display *view = new Fl_Text_Display(x, y, w, h);
    view->buffer(log);
    log->append("started\n");          // every view of log shows this
    return log;
}
Detailed notes - 10.11.6: Output widgets

1

labels can show results but their text is not normally selectable

  • generated label text needs appropriate lifetime/copy handling
  • users often need to select and copy an actual output value

2

Fl_Output provides a non-editable single-line text field

  • Fl_Multiline_Output provides its multiline counterpart
  • these retain selection/navigation behavior while disabling editing
  • the simple multiline output lacks full scrollbar facilities

3

selectable output belongs in value(text), not the widget's label

  • value copies the supplied text
  • the application can then reuse or release its source buffer

4

output text follows input-like left alignment

  • wrapping is available
  • these controls do not offer the label's full positioning freedom

5

make read-only results look read-only

  • FL_FLAT_BOX avoids the usual editable-field appearance
  • matching the surrounding background makes the border unobtrusive

retain a filled box style

  • text controls erase old content by repainting their box
  • FL_NO_BOX or frame-only drawing can leave old text artifacts

6

Fl_Text_Display suits larger scrollable text views

  • uses Fl_Text_Buffer, possibly shared with other views
  • append adds successive messages to the buffer
  • connected views reflect buffer changes
Tests & experiments (7 files) - 10.11.6: Output widgets
Section test06 (10-11)In catalog
MakefileMake / 13 lines
FLTK_DIR = $(HOME)/.app/fltk-1.3.11

CPPFLAGS = -I$(FLTK_DIR)
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDFLAGS = -L$(FLTK_DIR)/lib
LDLIBS = $(shell $(FLTK_DIR)/fltk-config --ldflags)

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
output.cppC++ / 23 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Output.H>

enum {
    win_w = 800,
    out_h = 100,
    win_h = out_h,
    font_size = 40
};

int main()
{
    Fl_Window win(win_w, win_h, "output");

    Fl_Output out(0, 0, win_w, win_h);
    out.textsize(font_size);
    out.value("hello there");

    win.end();
    win.show();
    return Fl::run();
}
output1.cppC++ / 24 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Multiline_Output.H>

enum {
    win_w = 200,
    out_h = 200,
    win_h = out_h,
    font_size = 40
};

int main()
{
    Fl_Window win(win_w, win_h, "output");

    Fl_Multiline_Output out(0, 0, win_w, win_h);
    out.textsize(font_size);
    out.wrap(1);
    out.value("hello there\nhow are you?\nAlright");

    win.end();
    win.show();
    return Fl::run();
}
output2.cppC++ / 27 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Multiline_Output.H>

enum {
    out_w = 300,
    out_h = 200,
    space = 10,
    win_h = out_h + 2 * space,
    win_w = out_w + 2 * space,
    font_size = 40
};

int main()
{
    Fl_Window win(win_w, win_h, "output");

    Fl_Multiline_Output out(space, space, out_w, out_h);
    out.textsize(font_size);
    out.box(FL_FLAT_BOX);
    out.color(FL_BACKGROUND_COLOR);
    out.value("hello there\nhow are you?\nAlright");

    win.end();
    win.show();
    return Fl::run();
}
output3.cppC++ / 32 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Text_Display.H>
#include <FL/Fl_Text_Buffer.H>

enum {
    out_w = 300,
    out_h = 200,
    space = 10,
    win_h = out_h + 2 * space,
    win_w = out_w + 2 * space,
    font_size = 40
};

int main()
{
    Fl_Window win(win_w, win_h, "output");

    Fl_Text_Display out(space, space, out_w, out_h);
    out.textsize(font_size);
    out.box(FL_FLAT_BOX);
    out.color(FL_BACKGROUND_COLOR);

    Fl_Text_Buffer buf;
    out.buffer(buf);
    buf.text("hello there\nhow are you?\nAlright\n");
    buf.append("i am doing fine, it's all good\n");

    win.end();
    win.show();
    return Fl::run();
}
output4.cppC++ / 24 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Output.H>

enum {
    win_w = 200,
    out_h = 200,
    win_h = out_h,
    font_size = 40
};

int main()
{
    Fl_Window win(win_w, win_h, "output");

    Fl_Output out(0, 0, win_w, win_h);
    out.textsize(font_size);
    out.wrap(1);
    out.value("hello there, how are you?");

    win.end();
    win.show();
    return Fl::run();
}
output5.cppC++ / 41 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Text_Display.H>
#include <FL/Fl_Text_Buffer.H>

enum {
    out_w = 500,
    out_h = 300,
    space = 10,
    win_h = out_h + 2 * space,
    win_w = out_w + 2 * space,
    font_size = 40
};

static void append_callback(void *user)
{
    Fl_Text_Buffer *buf = static_cast<Fl_Text_Buffer*>(user);
    buf->append("i am doing fine, it's all good\n");
}

int main()
{
    Fl_Window win(win_w, win_h, "output");

    Fl_Text_Buffer buf;

    Fl_Text_Display out(space, space, out_w, out_h);
    out.textsize(font_size);
    out.box(FL_FLAT_BOX);
    out.color(FL_BACKGROUND_COLOR);
    out.buffer(buf);

    buf.text("hello there\nhow are you?\nAlright\n");

    win.end();
    win.show();

    Fl::add_timeout(2.0, append_callback, &buf);

    return Fl::run();
}

10.11.7 Resizable windows

FLTK resizing uses a reference rectangle to determine which children stretch or move along each axis. Nested groups and invisible reference widgets express more complex policies, while explicit size limits constrain the window.

#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Group.H>

int main(int argc, char **argv)
{
    Fl_Window *win = new Fl_Window(400, 300, "resizable");

    Fl_Box *area = new Fl_Box(10, 10, 380, 240, "stretches both ways");
    area->box(FL_DOWN_BOX);

    Fl_Group *row = new Fl_Group(10, 260, 380, 30);
    Fl_Box *spring = new Fl_Box(10, 260, 170, 0);   // zero height: invisible
    new Fl_Button(190, 260, 90, 30, "Apply");
    new Fl_Button(300, 260, 90, 30, "Close");
    row->end();
    row->resizable(spring);     // the row grows only horizontally

    win->end();
    win->resizable(area);
    win->size_range(250, 150);  // minimum size; no maximum
    win->show(argc, argv);
    return Fl::run();
}
Detailed notes - 10.11.7: Resizable windows

1

resizable windows require an explicit policy for their contained widgets

  • decide what stretches, moves and stays fixed

2

the source presents FLTK's geometry-based scheme

  • its ease of use depends on the layout being expressed

3

Fl_Group manages child resizing

  • Fl_Window inherits that capability

4

resizable(widget) identifies a reference rectangle for the group's changes

  • can name one child or the group itself

5

resizable(0) disables automatic resizing of the group's children

  • on the simple window setup this corresponds to a fixed-size window
  • choosing the group itself makes its children scale with its geometry

6

choosing a contained resizable widget distributes changes by overlap

  • horizontal overlap determines horizontal stretching
  • vertical overlap determines vertical stretching
  • controls outside those ranges keep their sizes but may move

7

diagram's central R changes in both dimensions

  • A, B and H change width only
  • D, E and F change height only
  • C and G keep their sizes

8

nested groups and invisible widgets can express more complex policies

  • deriving the right group structure may require thought

9

useful patterns:

  • isolate a fixed-size control in a non-resizing group
  • use a zero-height invisible reference box for horizontal-only growth
  • use the symmetric zero-width arrangement for vertical-only growth

10

such patterns require deliberate construction of the group hierarchy

11

a window is also a group

  • parent() identifies a widget's containing group
  • ordinary controls need a path into a displayed window

12

current group determines the parent of newly created widgets

  • constructing a group makes it current
  • begin() selects that group again
  • end() selects its parent, or no group if there is no parent
  • Fl_Group::current provides explicit access to this setting

13

add can attach an existing widget directly

  • more commonly construct children immediately after their group
  • call end(), then continue constructing the parent's remaining children

14

window shrinking can stop at an automatically selected minimum

  • the resize demonstration stops while its central region remains visible

15

Fl_Window::size_range configures limits explicitly

  • minw/minh: minimum dimensions
  • maxw/maxh: optional upper limits
  • dw/dh: increments, useful for integral character-cell sizes
  • aspect: preserve the specified aspect-ratio policy

16

without size_range, the example version derives minimums from resizable

  • the source describes a 100-unit minimum cap for that region
  • a smaller starting region keeps its smaller minimum
  • a zero extent can prevent resizing along that axis
Tests & experiments (10 files) - 10.11.7: Resizable windows
Section test07 (10-11)In catalog
MakefileMake / 13 lines
FLTK_DIR = $(HOME)/.app/fltk-1.3.11

CPPFLAGS = -I$(FLTK_DIR)
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDFLAGS = -L$(FLTK_DIR)/lib
LDLIBS = $(shell $(FLTK_DIR)/fltk-config --ldflags)

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
group.cppC++ / 65 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Group.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Button.H>

enum {
    spacing = 10,
    cell_w = 80,
    cell_h = 70,
    button_w = 120,
    button_h = 40,
    font_size = 25,
    num_boxes = 4,

    group_w = num_boxes * cell_w + (num_boxes + 1) * spacing,
    group_h = cell_h + 2 * spacing,

    win_w = group_w + 2 * spacing,
    win_h = group_h + button_h + 3 * spacing
};

static void add_callback(Fl_Widget *w, void *user)
{
    Fl_Group *group = static_cast<Fl_Group*>(user);

    static int count = 0;
    static const char *const labels[] = {"A", "B", "C", "D"};

    if (count >= num_boxes)
        return;

    int x = group->x() + spacing + count * (cell_w + spacing);
    int y = group->y() + spacing;

    Fl_Box *box = new Fl_Box(x, y, cell_w, cell_h, labels[count]);
    box->box(FL_UP_BOX);
    box->color(FL_YELLOW);
    box->labelsize(font_size);

    group->add(box);
    group->redraw();

    count++;

    if (count == num_boxes)
        w->deactivate();
}

int main()
{
    Fl_Window win(win_w, win_h, "Dynamic group");

    Fl_Group group(spacing, spacing, group_w, group_h);
    group.box(FL_ENGRAVED_BOX);
    group.end();

    Fl_Button button(spacing, group_h + 2 * spacing, button_w, button_h,
                     "Add box");
    button.callback(add_callback, &group);

    win.end();
    win.show();
    return Fl::run();
}
resize.cppC++ / 52 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Group.H>
#include <FL/Fl_Box.H>

enum {
    spacing = 5,
    cell_w = 100,
    cell_h = 100,
    num_x = 4,
    num_y = 4,
    labelsz = 50
};

static int cell_x(int n) { return n * (cell_w + spacing) + spacing; }
static int cell_y(int m) { return m * (cell_h + spacing) + spacing; }

static Fl_Box *mkwidget(int n, int m, int cn, int cm, const char *lab)
{
    Fl_Box *b = new Fl_Box(cell_x(n), cell_y(m),
                           cn * cell_w + spacing * (cn-1),
                           cm * cell_h + spacing * (cm-1),
                           lab);
    b->box(FL_EMBOSSED_BOX);
    b->color(FL_WHITE);
    b->labelsize(labelsz);
    return b;
}

int main(int argc, char **argv)
{
    Fl_Window *win = new Fl_Window(cell_x(num_x), cell_y(num_y), "resize");

    mkwidget(0, 0, 2, 1, "A");
    mkwidget(2, 0, 1, 1, "B");
    mkwidget(3, 0, 1, 1, "C");

    mkwidget(0, 1, 1, 2, "D");
    mkwidget(3, 1, 1, 1, "E");

    mkwidget(3, 2, 1, 2, "F");

    mkwidget(0, 3, 1, 1, "G");
    mkwidget(1, 3, 2, 1, "H");

    Fl_Box *b = mkwidget(1, 1, 2, 2, "R");
    win->resizable(b);

    win->end();
    win->show();
    return Fl::run();
}
resize1.cppC++ / 24 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>

enum {
    dx = 100,
    dy = 100,
    font_size = 40
};

int main(int argc, char **argv)
{
    Fl_Window win(dx, dy, "resize");

    Fl_Box box(0, 0, dx, dy, "R");
    box.box(FL_EMBOSSED_BOX);
    box.color(FL_WHITE);
    box.labelsize(font_size);
    win.resizable(box);

    win.end();
    win.show();
    return Fl::run();
}
resize2.cppC++ / 28 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Group.H>
#include <FL/Fl_Box.H>

enum {
    dx = 100,
    dy = 100,
    font_size = 40
};

int main(int argc, char **argv)
{
    Fl_Window win(dx, dy, "resize");

    Fl_Box box(0, 0, dx, dy, "R");
    box.box(FL_EMBOSSED_BOX);
    box.color(FL_WHITE);
    box.labelsize(font_size);

    Fl_Box hid(0, 0, dx, 0);
    hid.box(FL_NO_BOX);
    win.resizable(hid);

    win.end();
    win.show();
    return Fl::run();
}
resize3.cppC++ / 28 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Group.H>
#include <FL/Fl_Box.H>

enum {
    dx = 100,
    dy = 100,
    font_size = 40
};

int main(int argc, char **argv)
{
    Fl_Window win(dx, dy, "resize");

    Fl_Box box(0, 0, dx, dy, "R");
    box.box(FL_EMBOSSED_BOX);
    box.color(FL_WHITE);
    box.labelsize(font_size);

    Fl_Box hid(0, 0, 0, dy);
    hid.box(FL_NO_BOX);
    win.resizable(hid);

    win.end();
    win.show();
    return Fl::run();
}
resize4.cppC++ / 52 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Group.H>
#include <FL/Fl_Box.H>

enum {
    spacing = 5,
    cell_w = 50,
    cell_h = 50,
    num_x = 4,
    num_y = 4,
    labelsz = 50
};

static int cell_x(int n) { return n * (cell_w + spacing) + spacing; }
static int cell_y(int m) { return m * (cell_h + spacing) + spacing; }

static Fl_Box *mkwidget(int n, int m, int cn, int cm, const char *lab)
{
    Fl_Box *b = new Fl_Box(cell_x(n), cell_y(m),
                           cn * cell_w + spacing * (cn-1),
                           cm * cell_h + spacing * (cm-1),
                           lab);
    b->box(FL_EMBOSSED_BOX);
    b->color(FL_WHITE);
    b->labelsize(labelsz);
    return b;
}

int main(int argc, char **argv)
{
    Fl_Window *win = new Fl_Window(cell_x(num_x), cell_y(num_y), "resize");

    mkwidget(0, 0, 2, 1, "A");
    mkwidget(2, 0, 1, 1, "B");
    mkwidget(3, 0, 1, 1, "C");

    mkwidget(0, 1, 1, 2, "D");
    mkwidget(3, 1, 1, 1, "E");

    mkwidget(3, 2, 1, 2, "F");

    mkwidget(0, 3, 1, 1, "G");
    mkwidget(1, 3, 2, 1, "H");

    Fl_Box *b = mkwidget(1, 1, 2, 2, "R");
    win->resizable(b);

    win->end();
    win->show();
    return Fl::run();
}
resize5.cppC++ / 56 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Group.H>
#include <FL/Fl_Box.H>

enum {
    spacing = 5,
    cell_w = 50,
    cell_h = 50,
    num_x = 4,
    num_y = 4,
    labelsz = 50
};

static int cell_x(int n) { return n * (cell_w + spacing) + spacing; }
static int cell_y(int m) { return m * (cell_h + spacing) + spacing; }

static Fl_Box *mkwidget(int n, int m, int cn, int cm, const char *lab)
{
    Fl_Box *b = new Fl_Box(cell_x(n), cell_y(m),
                           cn * cell_w + spacing * (cn-1),
                           cm * cell_h + spacing * (cm-1),
                           lab);
    b->color(FL_WHITE);
    b->box(FL_EMBOSSED_BOX);
    b->labelsize(labelsz);
    return b;
}

int main(int argc, char **argv)
{
    Fl_Window *win = new Fl_Window(cell_x(num_x), cell_y(num_y), "resize");

    Fl_Group g1(0, 0, 4, 1);
    mkwidget(0, 0, 2, 1, "A");
    mkwidget(2, 0, 1, 1, "B");
    mkwidget(3, 0, 1, 1, "C");
    g1.end();

    Fl_Group g2(0, 1, 4, 2);
    mkwidget(0, 1, 1, 2, "D");
    mkwidget(3, 1, 1, 1, "E");
    Fl_Box *b = mkwidget(1, 1, 2, 2, "R");
    win->resizable(b);
    g2.end();

    Fl_Group g3(0, 3, 4, 1);
    mkwidget(3, 2, 1, 2, "F");
    mkwidget(0, 3, 1, 1, "G");
    mkwidget(1, 3, 2, 1, "H");
    g3.end();

    win->end();
    win->show();
    return Fl::run();
}
resize6.cppC++ / 98 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Group.H>
#include <FL/Fl_Box.H>

enum {
    spacing = 12,
    gap = 8,

    sidebar_w = 130,
    side_box_h = 44,

    edge_w = 80,
    center_w = 190,
    row_h = 58,
    center_h = 165,

    header_h = 40,
    footer_h = 30,
    font_size = 22,

    main_w = 2 * edge_w + center_w + 4 * gap,
    main_h = 2 * row_h + center_h + 4 * gap,

    main_x = 2 * spacing + sidebar_w,
    main_y = 2 * spacing + header_h,

    win_w = main_x + main_w + spacing,
    footer_y = main_y + main_h + spacing,
    win_h = footer_y + footer_h + spacing
};

static Fl_Box *mkbox(int x, int y, int w, int h, const char *label, Fl_Color color)
{
    Fl_Box *box = new Fl_Box(x, y, w, h, label);
    box->box(FL_UP_BOX);
    box->color(color);
    box->labelsize(font_size);
    return box;
}

int main()
{
    Fl_Window *win = new Fl_Window(win_w, win_h, "Nested Groups and Resizing");

    mkbox(spacing, spacing, win_w - 2 * spacing, header_h,
          "Resize the window!", fl_rgb_color(190, 190, 190));

    Fl_Group *sidebar = new Fl_Group(spacing, main_y, sidebar_w, main_h);
    sidebar->box(FL_ENGRAVED_BOX);

    for (int i = 0; i < 3; i++) {
        static const char *names[] = {"1", "2", "3"};
        mkbox(spacing + gap, main_y + gap + i * (side_box_h + gap),
              sidebar_w - 2 * gap, side_box_h, names[i],
              fl_rgb_color(160, 195, 230));
    }

    sidebar->resizable(0);
    sidebar->end();

    Fl_Group *main_group = new Fl_Group(main_x, main_y, main_w, main_h);
    main_group->box(FL_ENGRAVED_BOX);

    int left_x = main_x + gap;
    int center_x = left_x + edge_w + gap;
    int right_x = center_x + center_w + gap;

    int top_y = main_y + gap;
    int center_y = top_y + row_h + gap;
    int bottom_y = center_y + center_h + gap;

    Fl_Color fixed_color = fl_rgb_color(165, 220, 215);
    Fl_Color grow_color = fl_rgb_color(245, 210, 140);

    mkbox(left_x, top_y, main_w - 2 * gap, row_h, "TOP", fixed_color);
    mkbox(left_x, center_y, edge_w, center_h, "L", fixed_color);

    Fl_Box *center = mkbox(center_x, center_y, center_w, center_h, "R",
                           grow_color);
    mkbox(right_x, center_y, edge_w, center_h, "R2", fixed_color);
    mkbox(left_x, bottom_y, main_w - 2 * gap, row_h, "BOTTOM", fixed_color);

    main_group->resizable(center);
    main_group->end();

    Fl_Box *footer = mkbox(spacing, footer_y, win_w - 2 * spacing, footer_h,
                           "The bottom bar moves with the window",
                           fl_rgb_color(190, 190, 190));
    footer->labelsize(16);

    win->resizable(main_group);
    win->size_range(win_w, win_h, 2 * win_w, 2 * win_h, 50, 50, 1);

    win->end();
    win->show();
    return Fl::run();
}
resize7.cppC++ / 42 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>

enum {
    spacing = 15,
    box_w = 240,
    box_h = 140,
    font_size = 22,

    win_w = box_w + 2 * spacing,
    win_h = box_h + 2 * spacing,

    win_x = 50,
    win_y = 80,
    win_gap = 30
};

static void make_window(int res_w, int res_h, const char *title)
{
    Fl_Window *win = new Fl_Window(win_w, win_h, title);

    Fl_Box *box = new Fl_Box(spacing, spacing, box_w, box_h, title);
    box->box(FL_EMBOSSED_BOX);
    box->color(FL_YELLOW);
    box->labelsize(font_size);

    Fl_Box *res = new Fl_Box(spacing, spacing, res_w, res_h);
    win->resizable(res);

    win->end();
    win->show();
}

int main()
{
    make_window(0, box_h, "Height only");
    make_window(box_w, 0, "Width only");
    make_window(box_w, box_h, "Both");

    return Fl::run();
}

10.11.8 Command-line arguments

Graphical applications can combine their own command-line options with FLTK's parser. The application handler gets first opportunity, positional arguments end the illustrated pass, and window display must be coordinated with library option handling.

The application handler sees each option first; FLTK handles the ones it declines:

static int buttons_count = 3;

static int count_handler(int argc, char **argv, int &idx)
{
    if (strcmp(argv[idx], "-count") != 0 || idx + 1 >= argc)
        return 0;               // not ours: let FLTK try
    char *end;
    long n = strtol(argv[idx + 1], &end, 10);
    if (end == argv[idx + 1] || *end != 0 || n < 1 || n > 20)
        return 0;
    buttons_count = n;
    idx += 2;
    return 2;                   // two arguments consumed
}
Show the complete program
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

enum {
    spacing = 5,
    button_w = 200,
    button_h = 30
};

static int buttons_count = 3;

static int count_handler(int argc, char **argv, int &idx)
{
    if (strcmp(argv[idx], "-count") != 0 || idx + 1 >= argc)
        return 0;
    char *end;
    long n = strtol(argv[idx + 1], &end, 10);
    if (end == argv[idx + 1] || *end != 0 || n < 1 || n > 20)
        return 0;
    buttons_count = n;
    idx += 2;
    return 2;
}

static void print_callback(Fl_Widget *w, void *user)
{
    printf("%s\n", w->label());
    fflush(stdout);
}

int main(int argc, char **argv)
{
    int idx;
    int res = Fl::args(argc, argv, idx, count_handler);
    if (!res) {
        fprintf(stderr, "usage: %s [-count N] [FLTK options] [labels]\n",
                argv[0]);
        return 1;
    }
    int win_h = buttons_count * (button_h + spacing) + spacing;
    Fl_Window *win = new Fl_Window(button_w + 2 * spacing, win_h, "labels");
    for (int i = 0; i < buttons_count; i++) {
        const char *label = idx + i < argc ? argv[idx + i] : "Not set";
        Fl_Button *b = new Fl_Button(spacing,
            spacing + i * (button_h + spacing), button_w, button_h, label);
        b->callback(print_callback, 0);
    }
    win->end();
    win->show(argc, argv);      // applies the parsed FLTK options
    return Fl::run();
}
$ ./cmdline -count 4 -geometry +100+100 One Two Three
Detailed notes - 10.11.8: Command-line arguments

1

graphical programs can still accept command-line options

  • -display selects an X server instead of the default DISPLAY setting
  • -geometry specifies size and possibly position
  • -bg changes the background color
  • FLTK supplies parsing for its recognized options

2

win->show(argc, argv) offers the simple library-only route

  • suitable when the application has no additional argument syntax

3

applications with their own options can combine the two parsers

  • let Fl::args drive parsing and call an application handler
  • or drive parsing themselves and delegate individual options to Fl::arg

4

Fl::args takes argc, argv, an index reference and optional handler

  • handler signature: int function(int, char**, int&)
  • the returned index identifies where option processing stopped

5

the application handler gets first chance at the current option

  • return zero if it is not recognized
  • when handled, advance the index by the number of consumed arguments
  • return that same consumed count
  • taking a library option name therefore overrides its usual processing

6

parsing stops at end of arguments or a positional argument

  • an unrecognized option or missing required option value is an error
  • zero return reports parsing failure

7

options after the first positional argument are not processed by this pass

  • place the expected options before the trailing positional arguments

8

this argument-handler interface has no user-data pointer

  • the example therefore stores the selected count in a file-local variable

9

in the book's Fl::args path, still call show(argc, argv)

  • parsed display/window settings must be applied when showing the window

10

demo: a variable number of buttons with trailing arguments as labels

  • default button count is three
  • -count N changes it
  • ordinary FLTK display and geometry options remain available

11

name layout constants and begin with buttons_count = 3

count parser:

  • strtol reads a decimal value
  • reject absent digits and trailing junk
  • also check overflow, destination range and an acceptable positive count before computing geometry; the short listing omits these checks

application option handler:

  • recognize -count and require its following value
  • consume both arguments; otherwise return zero

main:

  • reject failure from Fl::args
  • derive window height from the accepted count
  • use remaining arguments as labels, with Not set for missing labels
  • each button prints its own label through the shared callback
  • end the group, show(argc, argv), then run

12

Fl::arg processes one current option under the application's own loop

  • accepts the current index by reference
  • returns zero when unhandled
  • otherwise advances the index and returns the consumed count

coordinate this manual route with show's parsing behavior

  • the source tracks whether FLTK's argument parser was invoked
  • avoids asking show to reject application options a second time

13

cmdline2.cpp demonstrates that manually driven variant

Tests & experiments (4 files) - 10.11.8: Command-line arguments
Section test08 (10-11)In catalog
MakefileMake / 13 lines
FLTK_DIR = $(HOME)/.app/fltk-1.3.11

CPPFLAGS = -I$(FLTK_DIR)
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDFLAGS = -L$(FLTK_DIR)/lib
LDLIBS = $(shell $(FLTK_DIR)/fltk-config --ldflags)

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
args0.cppC++ / 17 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>

enum {
    win_w = 400,
    win_h = 400
};

int main(int argc, char **argv)
{
    Fl_Window *win = new Fl_Window(win_w, win_h);
    win->end();
    //win->show(argc, argv);
    win->show();
    return Fl::run();
}

args1.cppC++ / 67 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>

enum {
    spacing = 5,
    button_w = 200,
    button_h = 40,
    fontsz = 20
};

static int buttons_count = 3;

static void say_callback(Fl_Widget *, void *user)
{
    printf("%s\n", (const char*) user);
}

static void set_buttons_count(const char *arg)
{
    char *errptr;
    buttons_count = strtol(arg, &errptr, 10);
    if (errptr == arg || *errptr) {
        fprintf(stderr, "Invalid count %s\n", arg);
        exit(1);
    }
}

static int cmdline_callback(int argc, char **argv, int &idx)
{
    if (0 == strcmp(argv[idx], "-count")) {
        if (idx >= argc - 1) {
            fprintf(stderr, "Count (number) expected\n");
            exit(1);
        }
        set_buttons_count(argv[idx+1]);
        idx += 2;
        return 2;
    }
    return 0;
}

int main(int argc, char **argv)
{
   int arg_idx;
    int res = Fl::args(argc, argv, arg_idx, cmdline_callback);
    if (!res) {
        fprintf(stderr, "Malformed command line\n");
        return 1;
    }

    int win_w = button_w + spacing * 2;
    int win_h = (button_h + spacing) * buttons_count + spacing;
    Fl_Window *win = new Fl_Window(win_w, win_h, "command line demo");

    for (int i = 0, y = spacing; i < buttons_count; i++) {
        const char *msg = arg_idx + i < argc ? argv[arg_idx + i] : "Not set";
        Fl_Button *b = new Fl_Button(spacing, y, button_w, button_h, msg);
        b->labelsize(fontsz);
        b->callback(say_callback, (void*)msg);
        y += button_h + spacing;
    }
    win->end();
    win->show(argc, argv);
    return Fl::run();
}

args2.cppC++ / 78 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>

enum {
    spacing = 5,
    button_w = 200,
    button_h = 40,
    fontsz = 20
};

static void say_callback(Fl_Widget *, void *user)
{
    printf("%s\n", (const char*) user);
}

static int str2num(const char *arg)
{
    char *errptr;
    int count = strtol(arg, &errptr, 10);
    if (errptr == arg || *errptr) {
        fprintf(stderr, "Invalid count %s\n", arg);
        exit(1);
    }
    return count;
}

void process_args(int argc, char **argv, int &idx,
                  int &buttons_count, bool &fltk_args)
{
    while (idx < argc) {
        if (0 == strcmp(argv[idx], "-count")) {
            if (idx >= argc - 1) {
                fprintf(stderr, "Count (number) expected\n");
                exit(1);
            }
            buttons_count = str2num(argv[idx+1]);
            idx += 2;
        } else if (argv[idx][0] == '-') {
            int res = Fl::arg(argc, argv, idx);
            fltk_args = true;
            if (res == 0) {
                fprintf(stderr, "Flag <<%s>> unkown\n", argv[idx]);
                exit(1);
            }
        } else
            break;
    }
}

int main(int argc, char **argv)
{
    int arg_idx = 1, buttons_count = 0;
    bool fltk_args = false;

    process_args(argc, argv, arg_idx, buttons_count, fltk_args);
    if (buttons_count < 3)
        buttons_count = 3;

    int win_w = button_w + spacing * 2;
    int win_h = (button_h + spacing) * buttons_count + spacing;
    Fl_Window *win = new Fl_Window(win_w, win_h, "command line demo");

    for (int i = 0, y = spacing; i < buttons_count; i++) {
        const char *msg = arg_idx + i < argc ? argv[arg_idx + i] : "Not set";
        Fl_Button *b = new Fl_Button(spacing, y, button_w, button_h, msg);
        b->labelsize(fontsz);
        b->callback(say_callback, (void*)msg);
        y += button_h + spacing;
    }
    win->end();
    if (fltk_args)
        win->show(argc, argv);
    else
        win->show();
    return Fl::run();
}

10.11.9 Further FLTK facilities

FLTK also provides menus, scrolling regions, progress indicators, numeric controls, tables, tabs, dialogs, and image support. These facilities extend the basic widget model, with specialized interfaces left to the toolkit's documentation.

#include <FL/fl_ask.H>

void save_dialogs(const char *name, int records)
{
    int answer = fl_choice("Save changes to %s?",
                           "Cancel", "Save", "Discard", name);
    if (answer == 1)
        fl_message("Saved %d records", records);
    const char *who = fl_input("Your name:", "anonymous");
    if (!who)
        fl_alert("No name given");
}
Detailed notes - 10.11.9: Further FLTK facilities

1

the following is an orientation to facilities omitted from full examples

2

event handling can intercept keyboard, mouse and other activity

  • Fl_Event names event categories
  • handle is a virtual widget method
  • system/application handlers and event dispatch supply broader hooks

3

menu and selection widgets:

  • Fl_Menu_Bar: horizontal menu bar
  • Fl_Menu_Button: a button opening a menu
  • Fl_Choice: current selection plus a menu of alternatives
  • Fl_Tree: expandable/collapsible hierarchical items

4

Fl_Scroll provides a scrollable area containing widgets

  • Fl_Scrollbar supplies scrollbar controls
  • Fl_Pack arranges child widgets in a horizontal or vertical sequence

5

Fl_Progress displays progress through a longer operation

6

Fl_Valuator's subclasses offer numeric-value controls

  • sliders, dials and other specialized presentations

7

Fl_Table supports tabular arrangements

  • subclassing its virtual drawing/interaction hooks customizes cells

8

Fl_Tile arranges touching child regions with draggable boundaries

  • changing a boundary redistributes their sizes

9

Fl_Tabs provides user-selectable pages

Fl_Wizard provides pages selected by the application

  • useful for controlled multistage dialogs

10

Fl_Tooltip controls tooltip behavior

  • widget tooltip/copy_tooltip methods supply the displayed text

11

predefined modal dialogs provide simple messages and choices

  • fl_message/fl_alert: information or warning
  • fl_ask/fl_choice in the book's API: select among supplied answers
  • format strings and arguments construct their messages
  • modal interaction temporarily prevents ordinary use of other windows

12

other dialogs request text, passwords, files, directories or colors

  • corresponding functions supply those specialized interactions
  • predefined button-label variables allow changing common dialog labels

13

Fl_Image and its subclasses represent image data

  • examples include bitmap and PNG support
  • image/deimage associate normal and inactive imagery with widgets

14

the toolkit contains much more than this introduction

  • use its documentation when a specific facility becomes necessary
Tests & experiments (11 files) - 10.11.9: Further FLTK facilities
Section test09 (10-11)In catalog
MakefileMake / 15 lines
FLTK_DIR = $(HOME)/.app/fltk-1.3.11

CPPFLAGS = -I$(FLTK_DIR)
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDFLAGS = -L$(FLTK_DIR)/lib
LDLIBS = $(shell $(FLTK_DIR)/fltk-config --ldflags)

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

dialogs: LDLIBS = $(shell $(FLTK_DIR)/fltk-config --use-images --ldflags)

clean:
    rm -f *.o $(PROGS)
batch_estimator.cppC++ / 440 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Group.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Progress.H>
#include <FL/Fl_Value_Slider.H>
#include <FL/Fl_Dial.H>
#include <FL/Fl_Value_Output.H>
#include <FL/Fl_Counter.H>
#include <FL/Fl_Table.H>
#include <FL/Fl_Tile.H>
#include <FL/Fl_Tabs.H>
#include <FL/Fl_Wizard.H>
#include <FL/Fl_Tooltip.H>
#include <FL/fl_draw.H>

enum {
    pad = 16,
    win_w = 900,
    win_h = 620,
    min_win_w = win_w - 140,
    min_win_h = win_h - 60,
    tabs_x = pad,
    tabs_y = pad,
    tabs_w = win_w - 2 * pad,
    tabs_h = win_h - 2 * pad,
    page_x = tabs_x + 8,
    page_y = tabs_y + 36,
    page_w = tabs_w - 16,
    page_h = tabs_h - 44,
    wizard_x = page_x + pad,
    wizard_y = page_y + pad,
    wizard_w = page_w - 2 * pad,
    wizard_h = page_h - 110,
    nav_y = wizard_y + wizard_h + pad,
    tile_x = page_x + pad,
    tile_y = page_y + pad,
    tile_w = page_w - 2 * pad,
    tile_h = page_h - 2 * pad,
    left_w = tile_w * 2 / 3,
    right_w = tile_w - left_w
};

class ResultsTable : public Fl_Table {
    int completed_;
    double multiplier_;
    double offset_;

protected:
    void draw_cell(TableContext context, int r, int c,
                   int x, int y, int w, int h)
    {
        if (context != CONTEXT_COL_HEADER && context != CONTEXT_CELL)
            return;

        fl_push_clip(x, y, w, h);
        fl_color(context == CONTEXT_COL_HEADER ? FL_BACKGROUND_COLOR :
                 (r % 2 ? FL_WHITE : fl_rgb_color(245, 247, 249)));
        fl_rectf(x, y, w, h);
        fl_color(FL_DARK3);
        fl_rect(x, y, w, h);
        fl_color(FL_BLACK);
        fl_font(context == CONTEXT_COL_HEADER ? FL_HELVETICA_BOLD :
                FL_HELVETICA, 14);

        char text[80];
        if (context == CONTEXT_COL_HEADER) {
            const char *headings[] = { "Case", "Base value", "Estimate" };
            snprintf(text, sizeof(text), "%s", headings[c]);
        } else if (c == 0) {
            snprintf(text, sizeof(text), "%d", r + 1);
        } else if (c == 1) {
            snprintf(text, sizeof(text), "%.2f", 10.0 * (r + 1));
        } else if (r < completed_) {
            snprintf(text, sizeof(text), "%.2f",
                     10.0 * (r + 1) * multiplier_ + offset_);
        } else {
            snprintf(text, sizeof(text), "Pending");
        }
        fl_draw(text, x + 8, y, w - 16, h, FL_ALIGN_LEFT);
        fl_pop_clip();
    }

public:
    ResultsTable(int x, int y, int w, int h)
        : Fl_Table(x, y, w, h), completed_(0),
          multiplier_(1.0), offset_(0.0)
    {
        cols(3);
        rows(0);
        col_header(1);
        col_header_height(30);
        col_width(0, 80);
        col_width(1, 140);
        col_width(2, w - 80 - 140 - Fl::scrollbar_size() - 4);
        col_resize(1);
        box(FL_DOWN_BOX);
        end();
    }

    void resize(int X, int Y, int W, int H)
    {
        Fl_Table::resize(X, Y, W, H);

        int remaining = W - col_width(0) - col_width(1)
                          - Fl::scrollbar_size() - 4;

        col_width(2, remaining > 120 ? remaining : 120);
    }

    void reset(int count, double multiplier, double offset)
    {
        completed_ = 0;
        multiplier_ = multiplier;
        offset_ = offset;
        rows(count);
        row_height_all(30);
        redraw();
    }

    void complete_one()
    {
        ++completed_;
        redraw();
    }
};

class SetupPage : public Fl_Group {
    Fl_Wizard *wizard_;
    Fl_Button *back_;
    Fl_Button *next_;
    Fl_Button *start_;

public:
    SetupPage(int x, int y, int w, int h, const char *label)
        : Fl_Group(x, y, w, h, label),
        wizard_(0), back_(0), next_(0), start_(0) {}

    void controls(Fl_Wizard *wizard, Fl_Button *back,
                  Fl_Button *next, Fl_Button *start)
    {
        wizard_ = wizard;
        back_ = back;
        next_ = next;
        start_ = start;
    }

    void resize(int X, int Y, int W, int H)
    {
        Fl_Widget::resize(X, Y, W, H);

        if (!wizard_)
            return;

        const int wx = X + pad;
        const int wy = Y + pad;
        const int ww = W - 2 * pad;
        const int wh = H - 110;
        const int ny = wy + wh + pad;

        wizard_->resize(wx, wy, ww, wh);
        back_->resize(wx + 10, ny, 110, 36);
        next_->resize(wx + 130, ny, 110, 36);
        start_->resize(wx + ww - 130, ny, 120, 36);
        redraw();
    }
};

class Progress : public Fl_Progress {
public:
    Progress(int x, int y, int w, int h)
        : Fl_Progress(x, y, w, h) {}

    int handle(int event)
    {
        switch (event) {
        case FL_ENTER:
        case FL_LEAVE:
            return 1;
        }

        return Fl_Progress::handle(event);
    }
};

struct App {
    Fl_Tabs *tabs;
    Fl_Group *results_page;
    Fl_Wizard *wizard;
    Fl_Value_Slider *multiplier;
    Fl_Dial *offset;
    Fl_Value_Output *offset_display;
    Fl_Counter *count;
    Fl_Box *review;
    Fl_Button *back;
    Fl_Button *next;
    Fl_Button *start;
    Fl_Button *cancel;
    Progress *progress;
    Fl_Box *status;
    Fl_Box *total;
    ResultsTable *table;
    int planned;
    int completed;
    double run_multiplier;
    double run_offset;
    bool running;
};

static void tick(void *data);

static void dial_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);
    a->offset_display->value(a->offset->value());
}

static void next_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);
    char text[256];
    snprintf(text, sizeof(text),
             "Step 2: Review your settings\n\n"
             "Multiplier: %.2f\nFixed addition: %.2f\nCases: %d\n\n"
             "Press Run to calculate the estimates.",
             a->multiplier->value(), a->offset->value(),
             static_cast<int>(a->count->value()));
    a->review->copy_label(text);
    a->wizard->next();
    a->back->activate();
    a->next->deactivate();
    if (!a->running)
        a->start->activate();
}

static void back_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);
    a->wizard->prev();
    a->back->deactivate();
    a->next->activate();
    a->start->deactivate();
}

static void start_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);
    if (a->running)
        return;

    a->planned = static_cast<int>(a->count->value());
    a->completed = 0;
    a->run_multiplier = a->multiplier->value();
    a->run_offset = a->offset->value();
    a->running = true;

    a->table->reset(a->planned, a->run_multiplier, a->run_offset);
    a->progress->minimum(0);
    a->progress->maximum(a->planned);
    a->progress->value(0);
    a->status->copy_label("Calculating...");
    a->total->copy_label("Results will appear as each case finishes.");
    a->start->deactivate();
    a->cancel->activate();
    a->tabs->value(a->results_page);
    Fl::add_timeout(0.15, tick, a);
}

static void tick(void *data)
{
    App *a = static_cast<App*>(data);
    if (!a->running)
        return;

    ++a->completed;
    a->table->complete_one();
    a->progress->value(a->completed);

    char text[128];
    snprintf(text, sizeof(text), "Processed %d of %d cases",
             a->completed, a->planned);
    a->status->copy_label(text);

    if (a->completed == a->planned) {
        a->running = false;
        a->cancel->deactivate();
        a->start->activate();
        double sum = a->run_multiplier * 10.0 * a->planned *
                     (a->planned + 1) / 2.0 + a->run_offset * a->planned;
        snprintf(text, sizeof(text),
                 "Finished.\nTotal estimated value: %.2f", sum);
        a->total->copy_label(text);
    } else {
        Fl::repeat_timeout(0.15, tick, a);
    }
}

static void cancel_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);
    if (!a->running)
        return;

    a->running = false;
    Fl::remove_timeout(tick, a);
    a->status->copy_label("Cancelled");
    a->total->copy_label("Completed rows remain visible.");
    a->cancel->deactivate();
    a->start->activate();
}

int main()
{
    App a = {};
    Fl_Tooltip::delay(0.5);
    Fl_Window win(win_w, win_h, "Batch Estimator");

    a.tabs = new Fl_Tabs(tabs_x, tabs_y, tabs_w, tabs_h);

    SetupPage *setup = new SetupPage(page_x, page_y, page_w, page_h, "Configure");
    a.wizard = new Fl_Wizard(wizard_x, wizard_y, wizard_w, wizard_h);

    Fl_Group *step1 = new Fl_Group(wizard_x, wizard_y, wizard_w, wizard_h);
    Fl_Box *heading = new Fl_Box(wizard_x + 24, wizard_y + 12, wizard_w - 48, 30,
                                 "Step 1: Calculation parameters");
    heading->labelfont(FL_HELVETICA_BOLD);
    heading->labelsize(19);
    heading->align(FL_ALIGN_LEFT | FL_ALIGN_INSIDE);

    a.multiplier = new Fl_Value_Slider(wizard_x + 205, wizard_y + 85,
                                       390, 35, "Multiplier:");
    a.multiplier->type(FL_HOR_NICE_SLIDER);
    a.multiplier->bounds(0.5, 3.0);
    a.multiplier->step(0.05);
    a.multiplier->value(1.25);
    a.multiplier->tooltip("Scale each case's base value.");

    a.offset = new Fl_Dial(wizard_x + 205, wizard_y + 155,
                           90, 90, "Fixed addition:");
    a.offset->type(FL_LINE_DIAL);
    a.offset->bounds(-20, 20);
    a.offset->step(1);
    a.offset->value(5);
    a.offset->copy_tooltip("Added to every case after multiplication.");
    a.offset->callback(dial_cb, &a);
    a.offset->when(FL_WHEN_CHANGED);

    a.offset_display = new Fl_Value_Output(wizard_x + 390, wizard_y + 180, 90, 30,
                                           "Value:");
    a.offset_display->value(a.offset->value());

    a.count = new Fl_Counter(wizard_x + 205, wizard_y + 290,
                             190, 35, "Number of cases:");
    a.count->bounds(5, 30);
    a.count->step(1);
    a.count->value(15);
    a.count->tooltip("Each case starts with a base value of 10, 20, 30, ...");
    step1->end();

    Fl_Group *step2 = new Fl_Group(wizard_x, wizard_y, wizard_w, wizard_h);
    a.review = new Fl_Box(wizard_x + 24, wizard_y + 24,
                          wizard_w - 48, wizard_h - 48,
                          "Review your settings");
    a.review->align(FL_ALIGN_LEFT | FL_ALIGN_TOP | FL_ALIGN_INSIDE);
    a.review->labelsize(18);
    step2->end();

    a.wizard->end();
    a.wizard->value(step1);

    a.back = new Fl_Button(wizard_x + 10, nav_y, 110, 36, "Back");
    a.next = new Fl_Button(wizard_x + 130, nav_y, 110, 36, "Next");
    a.start = new Fl_Button(wizard_x + wizard_w - 130,
                            nav_y, 120, 36, "Run");
    a.back->callback(back_cb, &a);
    a.next->callback(next_cb, &a);
    a.start->callback(start_cb, &a);
    a.back->deactivate();
    a.start->deactivate();
    setup->controls(a.wizard, a.back, a.next, a.start);
    setup->end();

    a.results_page = new Fl_Group(page_x, page_y, page_w, page_h, "Results");
    Fl_Tile *tile = new Fl_Tile(tile_x, tile_y, tile_w, tile_h);

    Fl_Box *limits = new Fl_Box(tile_x + 200, tile_y, tile_w - 400, tile_h);
    tile->resizable(limits);

    a.table = new ResultsTable(tile_x, tile_y, left_w, tile_h);

    Fl_Group *panel = new Fl_Group(tile_x + left_w, tile_y,
                                   right_w, tile_h);
    panel->box(FL_DOWN_BOX);

    Fl_Box *panel_heading = new Fl_Box(panel->x() + 15, panel->y() + 20,
                                       panel->w() - 30, 35, "Run status");
    panel_heading->labelfont(FL_HELVETICA_BOLD);
    panel_heading->labelsize(18);

    a.status = new Fl_Box(panel->x() + 15, panel->y() + 90,
                          panel->w() - 30, 36, "Not started");
    a.progress = new Progress(panel->x() + 15, panel->y() + 140,
                              panel->w() - 30, 27);
    a.progress->minimum(0);
    a.progress->maximum(1);
    a.progress->value(0);
    a.progress->selection_color(FL_GREEN);
    a.progress->tooltip("Share of completed cases.");

    a.total = new Fl_Box(panel->x() + 15, panel->y() + 195,
                         panel->w() - 30, 100, "No results yet.");
    a.total->align(FL_ALIGN_TOP | FL_ALIGN_LEFT | FL_ALIGN_INSIDE);
    a.total->box(FL_FLAT_BOX);

    a.cancel = new Fl_Button(panel->x() + 15, panel->y() + 330,
                             panel->w() - 30, 37, "Cancel run");
    a.cancel->callback(cancel_cb, &a);
    a.cancel->deactivate();
    a.cancel->tooltip("Stop the timer; completed rows remain visible.");

    panel->resizable(a.total);
    panel->end();
    tile->end();
    a.results_page->resizable(tile);
    a.results_page->end();

    a.tabs->resizable(setup);
    a.tabs->end();
    a.tabs->value(setup);
    win.resizable(a.tabs);
    win.end();
    win.size_range(min_win_w, min_win_h);
    win.show();

    int result = Fl::run();
    Fl::remove_timeout(tick, &a);
    return result;
}
dialogs.cppC++ / 333 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Check_Button.H>
#include <FL/Fl_Tooltip.H>
#include <FL/Fl_File_Chooser.H>
#include <FL/Fl_Color_Chooser.H>
#include <FL/Fl_Image.H>
#include <FL/Fl_Bitmap.H>
#include <FL/Fl_PNG_Image.H>
#include <FL/fl_ask.H>

enum {
    spacing = 20,
    gap = 10,
    button_w = 190,
    button_h = 38,
    option_h = 28,
    preview_h = 150,
    status_h = 70,
    win_w = 3 * button_w + 2 * gap + 2 * spacing,

    options_y = 60,
    buttons_y = options_y + option_h + gap,
    caption_y = buttons_y + 3 * button_h + 2 * gap + spacing,
    preview_y = caption_y + option_h,
    active_y = preview_y + preview_h + gap,
    status_y = active_y + option_h + spacing,
    win_h = status_y + status_h + spacing
};

static const unsigned char check_bits[] = {
    0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x30,
    0x00, 0x18, 0x00, 0x0c, 0x06, 0x06, 0x0c, 0x03,
    0x98, 0x01, 0xf0, 0x00, 0x60, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};

static const unsigned char cross_bits[] = {
    0x00, 0x00, 0x00, 0x00, 0x0c, 0x30, 0x18, 0x18,
    0x30, 0x0c, 0x60, 0x06, 0xc0, 0x03, 0x80, 0x01,
    0x80, 0x01, 0xc0, 0x03, 0x60, 0x06, 0x30, 0x0c,
    0x18, 0x18, 0x0c, 0x30, 0x00, 0x00, 0x00, 0x00
};

struct App {
    Fl_Box *status;
    Fl_Box *preview;
};

static void set_status(App *a, const char *text)
{
    a->status->copy_label(text);
    puts(text);
    fflush(stdout);
}

static void tooltip_cb(Fl_Widget *w, void *data)
{
    Fl_Check_Button *button = static_cast<Fl_Check_Button*>(w);
    App *a = static_cast<App*>(data);

    Fl_Tooltip::enable(button->value());
    set_status(a, button->value() ? "Tooltips enabled" : "Tooltips disabled");
}

static void labels_cb(Fl_Widget *w, void *data)
{
    Fl_Check_Button *button = static_cast<Fl_Check_Button*>(w);
    App *a = static_cast<App*>(data);
    int custom = button->value();

    fl_yes = custom ? "Yes, please" : "Yes";
    fl_no = custom ? "No, thanks" : "No";
    fl_ok = custom ? "Accept" : "OK";
    fl_cancel = custom ? "Dismiss" : "Cancel";
    fl_close = custom ? "Done" : "Close";
    fl_file_chooser_ok_label(fl_ok);

    set_status(a, custom ? "Custom dialog buttons" : "Default dialog buttons");
}

static void hotspot_cb(Fl_Widget *w, void *)
{
    Fl_Check_Button *button = static_cast<Fl_Check_Button*>(w);
    fl_message_hotspot(button->value());
}

static void message_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);

    fl_message_title("Information");
    fl_message_icon()->label("i");
    // The call returns only after the modal dialog has been closed.
    fl_message("This example has %d dialog buttons.", 9);
    fl_message_icon()->label(0);
    set_status(a, "Message closed");
}

static void alert_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);

    fl_message_title("Warning");
    fl_alert("Example warning: value %d is too large.", 100);
    set_status(a, "Alert closed");
}

static void ask_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);

    // fl_ask is deprecated, but is included to illustrate the textbook API.
    int answer = fl_ask("Do you like %s?", "FLTK");
    char text[80];
    snprintf(text, sizeof(text), "fl_ask returned %d (%s)",
             answer, answer ? "Yes" : "No");
    set_status(a, text);
}

static void choice_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);
    const char *choices[] = { "Cancel", "Read", "Write" };

    int answer = fl_choice("Choose an action for %d files.",
                           choices[0], choices[1], choices[2], 3);
    char text[80];
    snprintf(text, sizeof(text), "fl_choice returned %d (%s)",
             answer, choices[answer]);
    set_status(a, text);
}

static void input_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);
    const char *value = fl_input("Enter a name for %s:", "Student", "the demo");

    if (!value) {
        set_status(a, "Text input cancelled");
        return;
    }

    char text[256];
    snprintf(text, sizeof(text), "Name: %s", value);
    set_status(a, text);
}

static void password_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);
    const char *value = fl_password("Enter a demo password:", "");

    set_status(a, value ? "Password accepted" : "Password input cancelled");
}

static void file_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);
    const char *path = fl_file_chooser("Choose a PNG image", "*.png", ".");

    if (!path) {
        set_status(a, "File selection cancelled");
        return;
    }

    Fl_PNG_Image png(path);
    if (png.fail()) {
        fl_alert("Cannot load PNG image:\n%s", path);
        set_status(a, "PNG loading failed");
        return;
    }

    int max_w = a->preview->w() - 2 * spacing;
    int max_h = a->preview->h() - 2 * spacing;
    double scale = static_cast<double>(max_w) / png.w();
    double height_scale = static_cast<double>(max_h) / png.h();
    if (height_scale < scale)
        scale = height_scale;
    if (scale > 1.0)
        scale = 1.0;

    int width = static_cast<int>(png.w() * scale);
    int height = static_cast<int>(png.h() * scale);
    Fl_Image *picture = png.copy(width > 0 ? width : 1,
                                 height > 0 ? height : 1);
    delete a->preview->image();
    a->preview->image(picture);
    a->preview->redraw();

    // Chooser strings belong to FLTK; copy them before another chooser call.
    set_status(a, path);
}

static void directory_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);
    const char *path = fl_dir_chooser("Choose a directory", ".", 0);
    set_status(a, path ? path : "Directory selection cancelled");
}

static void color_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);
    unsigned char r, g, b;
    Fl::get_color(a->preview->color(), r, g, b);

    if (!fl_color_chooser("Choose the preview background", r, g, b)) {
        set_status(a, "Color selection cancelled");
        return;
    }

    a->preview->color(fl_rgb_color(r, g, b));
    a->preview->redraw();

    char text[80];
    snprintf(text, sizeof(text), "Color: RGB(%d, %d, %d)", r, g, b);
    set_status(a, text);
}

static void active_cb(Fl_Widget *w, void *data)
{
    Fl_Check_Button *button = static_cast<Fl_Check_Button*>(w);
    App *a = static_cast<App*>(data);

    if (button->value())
        a->preview->activate();
    else
        a->preview->deactivate();

    a->preview->redraw();
    set_status(a, button->value() ? "Active preview: image()" :
                                   "Inactive preview: deimage()");
}

int main()
{
    App a = {};
    Fl_Bitmap check(check_bits, 16, 16);
    Fl_Bitmap cross(cross_bits, 16, 16);
    a.picture = check.copy(80, 80);
    Fl_Image *inactive_picture = cross.copy(80, 80);

    Fl_Tooltip::enable();
    Fl_Tooltip::delay(0.5);
    Fl_Tooltip::hoverdelay(0.1);
    Fl_Tooltip::size(14);
    Fl_Tooltip::color(fl_rgb_color(255, 255, 210));
    Fl_Tooltip::textcolor(FL_BLACK);
    fl_message_title_default("FLTK dialog example");
    fl_message_hotspot(0);

    Fl_Window win(win_w, win_h, "Tooltips, dialogs and images");

    Fl_Box title(spacing, spacing, win_w - 2 * spacing, option_h,
                 "Hover over a button, then click it");
    title.labelsize(18);

    Fl_Check_Button tooltips(spacing, options_y, button_w, option_h, "Tooltips");
    tooltips.value(1);
    tooltips.tooltip("Enable or disable tooltips on all widgets.");
    tooltips.callback(tooltip_cb, &a);

    Fl_Check_Button labels(spacing + button_w + gap, options_y,
                           button_w, option_h, "Custom button labels");
    labels.tooltip("Change fl_yes, fl_no, fl_ok, fl_cancel and fl_close.");
    labels.callback(labels_cb, &a);

    Fl_Check_Button hotspot(spacing + 2 * (button_w + gap), options_y,
                            button_w, option_h, "Dialog at pointer");
    hotspot.tooltip("Place common dialogs at the mouse pointer.");
    hotspot.callback(hotspot_cb);

    const char *names[] = {
        "fl_message", "fl_alert", "fl_ask",
        "fl_choice", "fl_input", "fl_password",
        "fl_file_chooser", "fl_dir_chooser", "fl_color_chooser"
    };
    Fl_Callback *callbacks[] = {
        message_cb, alert_cb, ask_cb,
        choice_cb, input_cb, password_cb,
        file_cb, directory_cb, color_cb
    };

    for (int i = 0; i < 9; ++i) {
        Fl_Button *button = new Fl_Button(spacing + (i % 3) * (button_w + gap),
                                          buttons_y + (i / 3) * (button_h + gap),
                                          button_w, button_h, names[i]);
        button->callback(callbacks[i], &a);

        char tip[160];
        snprintf(tip, sizeof(tip), "Button %d: open a modal %s dialog.",
                 i + 1, names[i]);
        // Unlike tooltip(), copy_tooltip() copies this temporary text.
        button->copy_tooltip(tip);
    }

    Fl_Box caption(spacing, caption_y, win_w - 2 * spacing, option_h,
                   "Fl_Bitmap preview; choose a PNG to replace it");

    Fl_Box preview(spacing, preview_y, win_w - 2 * spacing, preview_h);
    a.preview = &preview;
    preview.box(FL_DOWN_BOX);
    preview.color(FL_WHITE);
    preview.labelcolor(FL_DARK_GREEN);
    preview.image(check.copy(80, 80));
    preview.deimage(inactive_picture);
    preview.tooltip("image() is shown when active; deimage() when inactive.");

    Fl_Check_Button active(spacing, active_y, 260, option_h, "Preview active");
    active.value(1);
    active.tooltip("Uncheck to display the cross assigned with deimage().");
    active.callback(active_cb, &a);

    Fl_Box status(spacing, status_y, win_w - 2 * spacing, status_h, "Ready");
    a.status = &status;
    status.box(FL_DOWN_BOX);
    status.align(FL_ALIGN_LEFT | FL_ALIGN_INSIDE | FL_ALIGN_WRAP);

    win.end();
    win.show();

    int result = Fl::run();
    // Widgets borrow image pointers; the application owns the images.
    preview.image(0);
    preview.deimage(0);
    delete a.preview.image();
    delete inactive_picture;
    return result;
}
events1.cppC++ / 68 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>

enum {
    spacing = 20,
    box_w = 400,
    box_h = 220,
    font_size = 20,
    win_w = box_w + 2 * spacing,
    win_h = box_h + 2 * spacing
};

class EventBox : public Fl_Box {
public:
    EventBox(int x, int y, int w, int h, const char *title)
        : Fl_Box(x, y, w, h, title)
    {
        box(FL_DOWN_BOX);
        color(FL_DARK_GREEN);
        labelsize(font_size);
    }

    int handle(int event)
    {
        char text[100];

        switch (event) {
        case FL_ENTER:
        case FL_MOVE:
            sprintf(text, "Mouse: %d, %d",
                     Fl::event_x() - x(), Fl::event_y() - y());
            copy_label(text);
            return 1;

        case FL_DRAG:
            copy_label("Dragging!");
            return 1;

        case FL_PUSH:
            sprintf(text, "Mouse button %d pressed\n",
                    Fl::event_button());
            copy_label(text);
            return 1;

        case FL_KEYDOWN:
            sprintf(text, "Key: %d, text: %s",
                     Fl::event_key(), Fl::event_text());
            copy_label(text);
            return 1;
        }

        return Fl_Box::handle(event);
    }
};

int main()
{
    Fl_Window win(win_w, win_h, "Event handling");
    win.color(FL_BLACK);

    EventBox box(spacing, spacing, box_w, box_h, "Move mouse here");

    win.end();
    win.show();
    return Fl::run();
}
events2.cppC++ / 42 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>

enum {
    spacing = 20,
    box_w = 320,
    box_h = 100,
    font_size = 25,
    win_w = box_w + 2 * spacing,
    win_h = box_h + 2 * spacing
};

static int global_handler(int event)
{
    if (event == FL_SHORTCUT
            && Fl::event_key() == 'g'
            && Fl::event_state(FL_CTRL)) {
        puts("Global shortcut Ctrl+G");
        fflush(stdout);
        return 1;
    }

    return 0;
}

int main()
{
    Fl_Window win(win_w, win_h, "Global shortcut");

    Fl_Box box(spacing, spacing, box_w, box_h, "Press Ctrl+G");
    box.box(FL_DOWN_BOX);
    box.labelsize(font_size);

    Fl::add_handler(global_handler);

    win.end();
    win.show();

    return Fl::run();
}
events3.cppC++ / 57 lines
#include <stdio.h>
#include <X11/Xlib.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>

enum {
    spacing = 20,
    box_w = 320,
    box_h = 120,
    font_size = 22,
    win_w = box_w + 2 * spacing,
    win_h = box_h + 2 * spacing
};

static int system_handler(void *event, void *data)
{
    XEvent *xevent = static_cast<XEvent*>(event);

    if (xevent->type == ButtonPress)
        puts("X11: ButtonPress");

    if (xevent->type == KeyPress)
        puts("X11: KeyPress");

    return 0;
}

static int dispatch(int event, Fl_Window *win)
{
    if (event == FL_PUSH)
        puts("FLTK: FL_PUSH");

    if (event == FL_KEYDOWN)
        puts("FLTK: FL_KEYDOWN");

    fflush(stdout);

    return Fl::handle_(event, win);
}

int main()
{
    Fl_Window win(win_w, win_h, "Event interception");

    Fl_Box box(spacing, spacing, box_w, box_h, "Click or press a key");
    box.box(FL_DOWN_BOX);
    box.labelsize(font_size);

    Fl::add_system_handler(system_handler, 0);
    Fl::event_dispatch(dispatch);

    win.end();
    win.show();

    return Fl::run();
}
fourier_series.hC / 108 lines
#ifndef FOURIER_SERIES_H
#define FOURIER_SERIES_H

#include <cmath>
#include <vector>

namespace fourier {
const double pi = 3.14159265358979323846;
enum Waveform { SQUARE, SAWTOOTH, TRIANGLE };

inline const char *name(Waveform waveform)
{
    const char *names[] = { "Square", "Sawtooth", "Triangle" };
    return names[waveform];
}

// Period 2*pi; at a discontinuity, use the midpoint of the two limits.
inline double signal(Waveform waveform, double x)
{
    double s = std::sin(x);
    if (waveform == TRIANGLE)
        return 2.0 / pi * std::asin(s);
    if (waveform == SQUARE)
        return std::fabs(s) < 1e-12 ? 0.0 : (s > 0.0 ? 1.0 : -1.0);
    double wrapped = std::atan2(s, std::cos(x));
    return std::fabs(std::fabs(wrapped) - pi) < 1e-12 ? 0.0 : wrapped / pi;
}

struct Harmonic {
    double cosine, sine, rmse;
};

class Series {
    Waveform waveform_;
    double amplitude_, phase_, dc_, rmse_;
    std::vector<double> x_, target_, approximation_;
    std::vector<Harmonic> harmonics_;

    double error() const
    {
        double sum = 0.0;
        for (unsigned i = 0; i < target_.size(); ++i) {
            double difference = target_[i] - approximation_[i];
            sum += difference * difference;
        }
        return std::sqrt(sum / target_.size());
    }

public:
    Series() : waveform_(SQUARE), amplitude_(1), phase_(0), dc_(0), rmse_(0) {}

    void reset(Waveform waveform, double amplitude, double phase, int samples)
    {
        waveform_ = waveform;
        amplitude_ = amplitude;
        phase_ = phase;
        harmonics_.clear();
        x_.resize(samples);
        target_.resize(samples);
        approximation_.resize(samples);
        dc_ = 0.0;
        // Sample one period, excluding the duplicated right endpoint.
        for (int i = 0; i < samples; ++i) {
            x_[i] = -pi + 2.0 * pi * i / samples;
            target_[i] = amplitude * signal(waveform, x_[i] + phase);
            dc_ += target_[i];
        }
        dc_ /= samples;
        for (int i = 0; i < samples; ++i)
            approximation_[i] = dc_;
        rmse_ = error();
    }

    bool add_harmonic()
    {
        int n = terms() + 1;
        // Stay strictly below Nyquist, where this normalization is valid.
        if (x_.empty() || 2 * n >= samples())
            return false;
        Harmonic term = { 0.0, 0.0, 0.0 };
        for (int i = 0; i < samples(); ++i) {
            term.cosine += target_[i] * std::cos(n * x_[i]);
            term.sine += target_[i] * std::sin(n * x_[i]);
        }
        term.cosine *= 2.0 / samples();
        term.sine *= 2.0 / samples();
        for (int i = 0; i < samples(); ++i)
            approximation_[i] += term.cosine * std::cos(n * x_[i])
                                 + term.sine * std::sin(n * x_[i]);
        term.rmse = rmse_ = error();
        harmonics_.push_back(term);
        return true;
    }

    Waveform waveform() const { return waveform_; }
    double amplitude() const { return amplitude_; }
    double phase() const { return phase_; }
    double dc() const { return dc_; }
    double rmse() const { return rmse_; }
    int samples() const { return static_cast<int>(x_.size()); }
    int terms() const { return static_cast<int>(harmonics_.size()); }
    const Harmonic &harmonic(int i) const { return harmonics_[i]; }
    double x(int i) const { return x_[i]; }
    double target(int i) const { return target_[i]; }
    double approximation(int i) const { return approximation_[i]; }
};
} // namespace fourier
#endif
fourier_studio.cppC++ / 1379 lines
#include <stdio.h>
#include <algorithm>
#include <FL/Fl.H>
#include <FL/Fl_Double_Window.H>
#include <FL/Fl_Group.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Choice.H>
#include <FL/Fl_Valuator.H>
#include <FL/Fl_Table.H>
#include <FL/Fl_Tooltip.H>
#include <FL/Fl_Native_File_Chooser.H>
#include <FL/filename.H>
#include <FL/fl_ask.H>
#include <FL/fl_draw.H>
#include "fourier_series.h"
#include "studio_drawing.h"

namespace ui {
const Fl_Color canvas = fl_rgb_color(246, 246, 249);
const Fl_Color paper = fl_rgb_color(255, 255, 255);
const Fl_Color ink = fl_rgb_color(37, 40, 57);
const Fl_Color muted = fl_rgb_color(127, 132, 149);
const Fl_Color line = fl_rgb_color(232, 234, 241);
const Fl_Color accent = fl_rgb_color(116, 93, 224);
const Fl_Color accent_dark = fl_rgb_color(94, 72, 195);
const Fl_Color tint = fl_rgb_color(242, 239, 255);
const Fl_Color target = fl_rgb_color(131, 145, 151);
const Fl_Color green = fl_rgb_color(51, 154, 119);

enum {
    window_w = 1220,
    window_h = 860,
    min_w = 1040,
    min_h = 760,
    margin = 24,
    sidebar_w = 260,
    content_x = 308
};

static void round_fill(int x, int y, int w, int h, int r, Fl_Color color)
{
    drawing::round_rect(x, y, w, h, r, color);
}

static void card(int x, int y, int w, int h)
{
    round_fill(x, y, w, h, 14, line);
    round_fill(x + 1, y + 1, w - 2, h - 2, 13, paper);
}

static void text(const char *s, int x, int y, int size = 13,
                 Fl_Color color = ink, Fl_Font font = FL_HELVETICA)
{
    drawing::font(font, size);
    drawing::color(color);
    drawing::draw(s, x, y);
}

static void triangle_icon(int x, int y, int w, int h)
{
    drawing::line(x, y + h / 2, x + w / 4, y);
    drawing::line(x + w / 4, y, x + 3 * w / 4, y + h);
    drawing::line(x + 3 * w / 4, y + h, x + w, y + h / 2);
}

static void wave_icon(int x, int y, int w, int h, int wave, Fl_Color color)
{
    drawing::color(color);
    drawing::line_style(FL_SOLID, 2);
    if (wave == fourier::SQUARE) {
        drawing::line(x, y + h, x, y);
        drawing::line(x, y, x + w / 2, y);
        drawing::line(x + w / 2, y, x + w / 2, y + h);
        drawing::line(x + w / 2, y + h, x + w, y + h);
        drawing::line(x + w, y + h, x + w, y);
    } else if (wave == fourier::SAWTOOTH) {
        drawing::line(x, y + h, x + w / 2, y);
        drawing::line(x + w / 2, y, x + w / 2, y + h);
        drawing::line(x + w / 2, y + h, x + w, y);
    } else
        triangle_icon(x, y, w, h);
    drawing::line_style(0);
}
} // namespace ui

class Header : public Fl_Widget {
protected:
    void draw_logo()
    {
        ui::round_fill(24, 28, 40, 40, 12, ui::accent);
        drawing::color(ui::paper);
        drawing::line_style(FL_SOLID, 2);
        for (int i = 1; i <= 28; ++i) {
            double y0 = 48 - 9 * std::sin((i - 1) * 2 * fourier::pi / 28);
            double y1 = 48 - 9 * std::sin(i * 2 * fourier::pi / 28);
            drawing::line(30 + i - 1, y0, 30 + i, y1);
        }
        drawing::line_style(0);
    }

    void draw()
    {
        drawing::Scope paint(this);
        drawing::push_clip(x(), y(), w(), h());
        drawing::color(ui::canvas);
        drawing::rectf(x(), y(), w(), h());
        draw_logo();
        ui::text("Fourier Studio", 80, 46, 25, ui::ink, FL_HELVETICA_BOLD);
        ui::text("A signal playground. Build something from a little sine.", 81,
                 69, 13, ui::muted);
        ui::round_fill(w() - 306, 37, 130, 26, 13, fl_rgb_color(233, 247, 241));
        drawing::color(ui::green);
        drawing::pie(w() - 292, 47, 6, 6, 0, 360);
        ui::text("INTERACTIVE", w() - 278, 54, 10, ui::green,
                 FL_HELVETICA_BOLD);
        drawing::pop_clip();
    }

public:
    Header() : Fl_Widget(0, 0, ui::window_w, 90) {}
};

class Sidebar : public Fl_Group {
    const fourier::Series *series_;

protected:
    void draw_hints()
    {
        const char *hints[] = { "Sharp edges. Odd harmonics.",
                                "A ramp. Every harmonic.",
                                "Soft corners. Fast convergence." };
        ui::text(hints[series_->waveform()], x() + 22, y() + 587, 12, ui::ink);
        ui::text("Try adding a few more harmonics.", x() + 22, y() + 607, 11,
                 ui::muted);
        if (h() > 680)
            ui::text("Space: animate   Ctrl+E: export", x() + 22,
                     y() + h() - 24, 11, ui::muted);
    }

    void draw_panel()
    {
        ui::card(x(), y(), w(), h());
        ui::text("YOUR SIGNAL", x() + 22, y() + 29, 11, ui::muted,
                 FL_HELVETICA_BOLD);
        drawing::color(ui::line);
        drawing::line(x() + 22, y() + 142, x() + w() - 22, y() + 142);
        ui::text("SAMPLE RESOLUTION", x() + 22, y() + 409, 11, ui::muted,
                 FL_HELVETICA_BOLD);
        drawing::color(ui::line);
        drawing::line(x() + 22, y() + 563, x() + w() - 22, y() + 563);
        draw_hints();
    }

    void draw()
    {
        drawing::Scope paint(this);
        drawing::push_clip(x(), y(), w(), h());
        if (damage() & ~FL_DAMAGE_CHILD)
            draw_panel();
        drawing::flush();
        draw_children();
        drawing::pop_clip();
    }

public:
    Sidebar(const fourier::Series *series)
        : Fl_Group(24, 104, ui::sidebar_w, ui::window_h - 128), series_(series)
    {
        resizable(0);
    }
};

class WaveSelector : public Fl_Widget {
    int value_;

protected:
    void draw()
    {
        drawing::Scope paint(this);
        drawing::push_clip(x(), y(), w(), h());
        drawing::color(ui::paper);
        drawing::rectf(x(), y(), w(), h());
        const char *names[] = { "Square", "Sawtooth", "Triangle" };
        for (int i = 0; i < 3; ++i) {
            int X = x() + i * (w() + 6) / 3;
            int W = (w() - 12) / 3;
            bool selected = i == value_;
            ui::round_fill(X, y(), W, h(), 10,
                           selected ? ui::accent : ui::line);
            ui::round_fill(X + 1, y() + 1, W - 2, h() - 2, 9,
                           selected ? ui::tint : ui::paper);
            ui::wave_icon(X + W / 2 - 17, y() + 17, 34, 20, i,
                          selected ? ui::accent : ui::target);
            drawing::font(selected ? FL_HELVETICA_BOLD : FL_HELVETICA, 11);
            drawing::color(selected ? ui::accent : ui::muted);
            drawing::draw(names[i], X, y() + 48, W, 19, FL_ALIGN_CENTER);
        }
        drawing::pop_clip();
    }

public:
    WaveSelector() : Fl_Widget(46, 160, 216, 76), value_(0) {}
    int value() const { return value_; }
    void value(int n)
    {
        value_ = n;
        redraw();
    }

private:
    void select_from_mouse()
    {
        int n = std::min(2, std::max(0, (Fl::event_x() - x()) * 3 / w()));
        if (n != value_) {
            value(n);
            do_callback();
        }
    }

public:
    int handle(int event)
    {
        if (event == FL_PUSH) {
            take_focus();
            select_from_mouse();
            return 1;
        }
        if (event == FL_KEYDOWN
            && (Fl::event_key() == FL_Left || Fl::event_key() == FL_Right)) {
            value((value_ + (Fl::event_key() == FL_Right ? 1 : 2)) % 3);
            do_callback();
            return 1;
        }
        if (event == FL_FOCUS || event == FL_UNFOCUS) {
            redraw();
            return 1;
        }
        return 0;
    }
};

class StudioSlider : public Fl_Valuator {
    int format_;
    bool dragging_;
    void from_mouse()
    {
        double fraction =
            static_cast<double>(Fl::event_x() - x() - 7) / (w() - 14);
        fraction = std::max(0.0, std::min(1.0, fraction));
        handle_drag(
            clamp(round(minimum() + fraction * (maximum() - minimum()))));
    }

protected:
    void draw_value()
    {
        char text[40];
        if (format_ == 0)
            snprintf(text, sizeof(text), "%.2f", value());
        else if (format_ == 1)
            snprintf(text, sizeof(text), "%.0f°", value());
        else
            snprintf(text, sizeof(text), "%.0f", value());
        ui::round_fill(x() + w() - 58, y(), 58, 25, 7, ui::tint);
        drawing::font(FL_HELVETICA_BOLD, 12);
        drawing::color(ui::accent);
        drawing::draw(text, x() + w() - 58, y(), 58, 25, FL_ALIGN_CENTER);
    }

    void draw_track()
    {
        int left = x() + 7, width = w() - 14;
        int position = left
                       + static_cast<int>(width * (value() - minimum())
                                          / (maximum() - minimum()));
        ui::round_fill(left, y() + 43, width, 5, 2, ui::line);
        if (position > left)
            ui::round_fill(left, y() + 43, position - left, 5, 2, ui::accent);
        drawing::color(ui::accent);
        drawing::pie(position - 8, y() + 37, 16, 16, 0, 360);
        drawing::color(ui::paper);
        drawing::pie(position - 5, y() + 40, 10, 10, 0, 360);
    }

    void draw()
    {
        drawing::Scope paint(this);
        drawing::push_clip(x(), y(), w(), h());
        drawing::color(ui::paper);
        drawing::rectf(x(), y(), w(), h());
        ui::text(label(), x(), y() + 17, 13, ui::ink, FL_HELVETICA_BOLD);
        draw_value();
        draw_track();
        if (Fl::focus() == this) {
            drawing::color(ui::accent);
            drawing::line(x(), y() + h() - 1, x() + w(), y() + h() - 1);
        }
        drawing::pop_clip();
    }

public:
    StudioSlider(int Y, const char *label, int format)
        : Fl_Valuator(46, Y, 216, 62, label), format_(format), dragging_(false)
    {
        align(FL_ALIGN_INSIDE);
        when(FL_WHEN_CHANGED);
    }

private:
    void begin_drag()
    {
        take_focus();
        dragging_ = true;
        handle_push();
        from_mouse();
    }

    int handle_mouse(int event)
    {
        if (event == FL_PUSH)
            begin_drag();
        else if (event == FL_DRAG) {
            if (dragging_)
                from_mouse();
        } else {
            dragging_ = false;
            handle_release();
        }
        return 1;
    }

    void step_by_key(int direction)
    {
        handle_push();
        handle_drag(clamp(increment(value(), direction)));
        handle_release();
    }

    void jump_by_key(int key)
    {
        handle_push();
        handle_drag(key == FL_Home ? minimum() : maximum());
        handle_release();
    }

    int handle_key()
    {
        int key = Fl::event_key();
        if (key == FL_Left || key == FL_Right || key == FL_Up
            || key == FL_Down) {
            int direction = key == FL_Right || key == FL_Up ? 1 : -1;
            step_by_key(direction);
            return 1;
        }
        if (key == FL_Home || key == FL_End) {
            jump_by_key(key);
            return 1;
        }
        return 0;
    }

public:
    int handle(int event)
    {
        if (event == FL_PUSH || event == FL_DRAG || event == FL_RELEASE)
            return handle_mouse(event);
        if (event == FL_KEYDOWN)
            return handle_key();
        if (event == FL_FOCUS || event == FL_UNFOCUS) {
            redraw();
            return 1;
        }
        return 0;
    }
};

class SampleChoice : public Fl_Choice {
protected:
    void draw()
    {
        drawing::Scope paint(this);
        drawing::push_clip(x(), y(), w(), h());
        ui::round_fill(x(), y(), w(), h(), 9,
                       Fl::focus() == this ? ui::accent : ui::line);
        ui::round_fill(x() + 1, y() + 1, w() - 2, h() - 2, 8, ui::paper);
        ui::text(text(), x() + 14, y() + 26, 13);
        drawing::color(ui::muted);
        drawing::line(x() + w() - 25, y() + 17, x() + w() - 20, y() + 22,
                      x() + w() - 15, y() + 17);
        drawing::pop_clip();
    }

public:
    SampleChoice() : Fl_Choice(46, 538, 216, 42)
    {
        add("256 samples|512 samples|1,024 samples|2,048 samples");
        value(2);
        textsize(13);
        color(ui::paper);
        textcolor(ui::ink);
        selection_color(ui::accent);
    }
};

class ActionButton : public Fl_Button {
    bool primary_, hover_;
    int icon_;

protected:
    void draw_background()
    {
        Fl_Color fill = primary_
                            ? (value() || hover_ ? ui::accent_dark : ui::accent)
                            : ui::paper;
        if (!active_r())
            fill = ui::line;
        ui::round_fill(x(), y(), w(), h(), 10, primary_ ? fill : ui::line);
        if (!primary_)
            ui::round_fill(x() + 1, y() + 1, w() - 2, h() - 2, 9,
                           hover_ ? ui::canvas : fill);
    }

    void draw_play_icon()
    {
        if (label()[0] == 'P') {
            drawing::rectf(x() + 18, y() + h() / 2 - 5, 3, 10);
            drawing::rectf(x() + 24, y() + h() / 2 - 5, 3, 10);
        } else {
            drawing::polygon(x() + 18, y() + h() / 2 - 5, x() + 18,
                             y() + h() / 2 + 5, x() + 26, y() + h() / 2);
        }
    }

    void draw_download_icon()
    {
        int X = x() + 20, Y = y() + h() / 2;
        drawing::line(X, Y - 7, X, Y + 3);
        drawing::line(X - 4, Y - 1, X, Y + 3, X + 4, Y - 1);
        drawing::line(X - 6, Y + 7, X + 6, Y + 7);
    }

    void draw()
    {
        drawing::Scope paint(this);
        drawing::push_clip(x(), y(), w(), h());
        draw_background();
        drawing::font(FL_HELVETICA_BOLD, 13);
        drawing::color(primary_ && active_r()
                           ? ui::paper
                           : (active_r() ? ui::ink : ui::muted));
        if (icon_ == 1)
            draw_play_icon();
        else if (icon_ == 2)
            draw_download_icon();
        drawing::draw(label(), x() + (icon_ ? 15 : 0), y(),
                      w() - (icon_ ? 15 : 0), h(), FL_ALIGN_CENTER);
        if (Fl::focus() == this) {
            drawing::color(primary_ ? ui::paper : ui::accent);
            drawing::line(x() + 14, y() + h() - 7, x() + w() - 14,
                          y() + h() - 7);
        }
        drawing::pop_clip();
    }

public:
    ActionButton(int X, int Y, int W, int H, const char *label, bool primary,
                 bool export_icon = false)
        : Fl_Button(X, Y, W, H, label), primary_(primary), hover_(false),
          icon_(primary ? 1 : (export_icon ? 2 : 0))
    {}
    int handle(int event)
    {
        if (event == FL_ENTER || event == FL_LEAVE) {
            hover_ = event == FL_ENTER;
            redraw();
        }
        return Fl_Button::handle(event);
    }
};

class Metric : public Fl_Widget {
    char value_[48], hint_[96];

protected:
    void draw()
    {
        drawing::Scope paint(this);
        drawing::push_clip(x(), y(), w(), h());
        ui::card(x(), y(), w(), h());
        ui::text(label(), x() + 20, y() + 24, 10, ui::muted, FL_HELVETICA_BOLD);
        ui::text(value_, x() + 20, y() + 59, 28, ui::ink, FL_HELVETICA_BOLD);
        ui::text(hint_, x() + 20, y() + 79, 11, ui::muted);
        drawing::pop_clip();
    }

public:
    Metric(const char *label) : Fl_Widget(0, 104, 200, 96, label)
    {
        value_[0] = hint_[0] = '\0';
    }
    void display(const char *value, const char *hint)
    {
        snprintf(value_, sizeof(value_), "%s", value);
        snprintf(hint_, sizeof(hint_), "%s", hint);
        redraw();
    }
};

class WaveformPlot : public Fl_Widget {
    const fourier::Series *series_;
    int hover_, requested_;
    bool playing_;
    int graph_x() const { return x() + 60; }
    int graph_y() const { return y() + 82; }
    int graph_w() const { return w() - 86; }
    int graph_h() const { return h() - 123; }
    double point_y(double value) const
    {
        return graph_y()
               + graph_h() * (0.5 - value / (2.9 * series_->amplitude()));
    }

protected:
    void draw_header()
    {
        ui::text("Waveform reconstruction", x() + 22, y() + 31, 17, ui::ink,
                 FL_HELVETICA_BOLD);
        char subtitle[120];
        const char *state = playing_ ? "building the series…" : "one period";
        snprintf(subtitle, sizeof(subtitle),
                 "%s wave  ·  %d / %d harmonics  ·  %s",
                 fourier::name(series_->waveform()), series_->terms(),
                 requested_, state);
        ui::text(subtitle, x() + 22, y() + 52, 11, ui::muted);
    }

    void draw_legend()
    {
        drawing::color(ui::target);
        drawing::line_style(FL_DASH, 1);
        drawing::line(x() + w() - 246, y() + 28, x() + w() - 226, y() + 28);
        drawing::line_style(0);
        ui::text("Target", x() + w() - 218, y() + 32, 11, ui::muted);
        drawing::color(ui::accent);
        drawing::line_style(FL_SOLID, 2);
        drawing::line(x() + w() - 158, y() + 28, x() + w() - 138, y() + 28);
        drawing::line_style(0);
        ui::text("Fourier series", x() + w() - 130, y() + 32, 11, ui::accent);
    }

    double point_x(int sample) const
    {
        return graph_x()
               + static_cast<double>(graph_w()) * sample / series_->samples();
    }

    bool has_hover() const
    {
        return hover_ >= 0 && hover_ < series_->samples();
    }

    void draw_fill()
    {
        drawing::color(fl_rgb_color(248, 246, 255));
        drawing::begin_complex_polygon();
        drawing::vertex(graph_x(), point_y(0));
        for (int i = 0; i <= series_->samples(); ++i)
            drawing::vertex(point_x(i), point_y(series_->approximation(
                                            i % series_->samples())));
        drawing::vertex(graph_x() + graph_w(), point_y(0));
        drawing::end_complex_polygon();
    }

    void draw_grid()
    {
        int X = graph_x(), Y = graph_y(), W = graph_w(), H = graph_h();
        for (int i = -2; i <= 2; ++i) {
            drawing::color(i ? ui::line : fl_rgb_color(214, 216, 229));
            int yy = static_cast<int>(point_y(series_->amplitude() * i / 2.0));
            drawing::line(X, yy, X + W, yy);
        }
        for (int i = 0; i < 5; ++i) {
            drawing::color(ui::line);
            drawing::line(X + W * i / 4, Y, X + W * i / 4, Y + H);
        }
    }

    void draw_curve(int curve)
    {
        drawing::color(curve ? ui::accent : ui::target);
        drawing::line_style(curve ? FL_SOLID : FL_DASH, curve ? 2 : 1);
        drawing::begin_line();
        for (int i = 0; i <= series_->samples(); ++i) {
            int sample = i % series_->samples();
            drawing::vertex(point_x(i),
                            point_y(curve ? series_->approximation(sample)
                                          : series_->target(sample)));
        }
        drawing::end_line();
    }

    void draw_hover_point()
    {
        int hx = graph_x() + graph_w() * hover_ / series_->samples();
        int hy = static_cast<int>(point_y(series_->approximation(hover_)));
        drawing::color(ui::accent);
        drawing::line_style(FL_DOT, 1);
        drawing::line(hx, graph_y(), hx, graph_y() + graph_h());
        drawing::line_style(0);
        drawing::color(ui::paper);
        drawing::pie(hx - 5, hy - 5, 10, 10, 0, 360);
        drawing::color(ui::accent);
        drawing::pie(hx - 3, hy - 3, 6, 6, 0, 360);
    }

    void draw_vertical_ticks()
    {
        for (int i = -2; i <= 2; ++i) {
            char text[32];
            double value = series_->amplitude() * i / 2.0;
            snprintf(text, sizeof(text), "%.2g", value);
            drawing::font(FL_HELVETICA, 11);
            drawing::color(ui::muted);
            drawing::draw(text, x() + 10, static_cast<int>(point_y(value)) - 8,
                          39, 16, FL_ALIGN_RIGHT);
        }
    }

    void draw_horizontal_ticks()
    {
        const char *ticks[] = { "-π", "-π/2", "0", "π/2", "π" };
        for (int i = 0; i < 5; ++i) {
            drawing::font(FL_HELVETICA, 11);
            drawing::color(ui::muted);
            drawing::draw(ticks[i], graph_x() + graph_w() * i / 4 - 22,
                          graph_y() + graph_h() + 14, 44, 18, FL_ALIGN_CENTER);
        }
    }

    void draw_readout()
    {
        int bx =
            std::min(graph_x() + graph_w() - 180,
                     graph_x() + graph_w() * hover_ / series_->samples() + 14);
        int by = graph_y() + 10;
        ui::round_fill(bx, by, 180, 76, 10, ui::ink);
        char text[64];
        snprintf(text, sizeof(text), "x = %.3f", series_->x(hover_));
        ui::text(text, bx + 12, by + 21, 11, ui::paper, FL_HELVETICA_BOLD);
        snprintf(text, sizeof(text), "Target      % .4f",
                 series_->target(hover_));
        ui::text(text, bx + 12, by + 43, 11, fl_rgb_color(204, 211, 220));
        snprintf(text, sizeof(text), "Series       % .4f",
                 series_->approximation(hover_));
        ui::text(text, bx + 12, by + 62, 11, fl_rgb_color(194, 180, 255));
    }

    void draw_graph()
    {
        drawing::push_clip(graph_x(), graph_y(), graph_w() + 1, graph_h() + 1);
        draw_fill();
        draw_grid();
        draw_curve(0);
        draw_curve(1);
        drawing::line_style(0);
        if (has_hover())
            draw_hover_point();
        drawing::pop_clip();
        draw_vertical_ticks();
        draw_horizontal_ticks();
        if (has_hover())
            draw_readout();
    }

    void draw()
    {
        drawing::Scope paint(this);
        drawing::push_clip(x(), y(), w(), h());
        ui::card(x(), y(), w(), h());
        draw_header();
        draw_legend();
        if (series_->samples())
            draw_graph();
        drawing::pop_clip();
    }

public:
    WaveformPlot(const fourier::Series *series)
        : Fl_Widget(0, 0, 700, 390), series_(series), hover_(-1),
          requested_(15), playing_(false)
    {}
    void state(bool playing, int requested)
    {
        playing_ = playing;
        requested_ = requested;
        hover_ = -1;
        redraw();
    }

private:
    void update_hover()
    {
        if (Fl::event_x() >= graph_x() && Fl::event_x() <= graph_x() + graph_w()
            && Fl::event_y() >= graph_y()
            && Fl::event_y() <= graph_y() + graph_h()) {
            hover_ = std::min(series_->samples() - 1,
                              (Fl::event_x() - graph_x()) * series_->samples()
                                  / graph_w());
        } else
            hover_ = -1;
        redraw();
    }

public:
    int handle(int event)
    {
        if (event == FL_MOVE || event == FL_ENTER) {
            update_hover();
            return 1;
        }
        if (event == FL_LEAVE) {
            hover_ = -1;
            redraw();
            return 1;
        }
        return 0;
    }
};

class Spectrum : public Fl_Widget {
    const fourier::Series *series_;
    int requested_;

protected:
    double harmonic_amplitude(int i) const
    {
        const fourier::Harmonic &term = series_->harmonic(i);
        return std::sqrt(term.cosine * term.cosine + term.sine * term.sine);
    }

    double maximum_amplitude() const
    {
        double maximum = 0.0;
        for (int i = 0; i < series_->terms(); ++i)
            maximum = std::max(maximum, harmonic_amplitude(i));
        return maximum;
    }

    void draw_grid()
    {
        int left = x() + 22, top = y() + 18;
        int width = w() - 36, height = h() - 45;
        for (int i = 0; i < 3; ++i) {
            drawing::color(ui::line);
            drawing::line(left, top + height * i / 2, left + width,
                          top + height * i / 2);
        }
    }

    void draw_peak(int center, int top, double amplitude)
    {
        char text[24];
        snprintf(text, sizeof(text), "%.3f", amplitude);
        drawing::font(FL_HELVETICA_BOLD, 10);
        drawing::color(ui::accent);
        drawing::draw(text, center - 30, top - 22, 60, 18, FL_ALIGN_CENTER);
    }

    void draw_bar(int i, int center, double maximum, double scale)
    {
        if (i >= series_->terms())
            return;
        int bins = std::max(16, requested_);
        int bar_w = std::max(2, std::min(20, (w() - 36) / bins - 5));
        double amplitude = harmonic_amplitude(i);
        int bar_h = static_cast<int>((h() - 45) * amplitude / scale);
        if (bar_h <= 1)
            return;
        int top = y() + 18 + h() - 45 - bar_h;
        ui::round_fill(center - bar_w / 2, top, bar_w, bar_h,
                       std::min(4, bar_w / 2), ui::accent);
        if (amplitude > maximum * 0.99)
            draw_peak(center, top, amplitude);
    }

    void draw_bin_label(int i, int center, int bins)
    {
        bool tick = i == 0 || i == bins - 1
                    || (bins <= 24 ? (i + 1) % 4 == 0 : (i + 1) % 10 == 0);
        if (!tick)
            return;
        char text[24];
        snprintf(text, sizeof(text), "%d", i + 1);
        drawing::font(FL_HELVETICA, 10);
        drawing::color(ui::muted);
        drawing::draw(text, center - 18, y() + 18 + h() - 45 + 8, 36, 17,
                      FL_ALIGN_CENTER);
    }

    void draw_bars(double maximum, double scale)
    {
        int bins = std::max(16, requested_);
        int left = x() + 22, width = w() - 36;
        for (int i = 0; i < bins; ++i) {
            int center = left + width * (2 * i + 1) / (2 * bins);
            draw_bar(i, center, maximum, scale);
            draw_bin_label(i, center, bins);
        }
    }

    void draw()
    {
        drawing::Scope paint(this);
        drawing::push_clip(x(), y(), w(), h());
        drawing::color(ui::paper);
        drawing::rectf(x(), y(), w(), h());
        double maximum = maximum_amplitude();
        double scale = maximum > 1e-12 ? maximum * 1.25 : 1.0;
        draw_grid();
        draw_bars(maximum, scale);
        drawing::pop_clip();
    }

public:
    Spectrum(const fourier::Series *series)
        : Fl_Widget(0, 0, 700, 150), series_(series), requested_(15)
    {}
    void requested(int n)
    {
        requested_ = n;
        redraw();
    }
};

class CoefficientTable : public Fl_Table {
    const fourier::Series *series_;

protected:
    double cell_value(int r, int c) const
    {
        const fourier::Harmonic &term = series_->harmonic(r);
        double value = c == 1 ? term.cosine : (c == 2 ? term.sine : term.rmse);
        return std::fabs(value) < 0.000005 ? 0.0 : value;
    }

    void cell_text(char *text, size_t size, TableContext context, int r,
                   int c) const
    {
        if (context == CONTEXT_COL_HEADER) {
            const char *titles[] = { "HARMONIC", "COSINE  a_n", "SINE  b_n",
                                     "RMS ERROR" };
            snprintf(text, size, "%s", titles[c]);
        } else if (c == 0)
            snprintf(text, size, "%02d", r + 1);
        else if (r < series_->terms())
            snprintf(text, size, "%.5f", cell_value(r, c));
        else
            snprintf(text, size, "-");
    }

    void draw_background(TableContext context, int r, int c, int X, int Y,
                         int W, int H)
    {
        drawing::color(context == CONTEXT_COL_HEADER
                           ? ui::canvas
                           : (is_selected(r, c) ? ui::tint : ui::paper));
        drawing::rectf(X, Y, W, H);
        drawing::color(ui::line);
        drawing::line(X, Y + H - 1, X + W, Y + H - 1);
    }

    void draw_content(TableContext context, int r, int c, int X, int Y, int W,
                      int H)
    {
        char text[80];
        cell_text(text, sizeof(text), context, r, c);
        drawing::font(context == CONTEXT_COL_HEADER ? FL_HELVETICA_BOLD
                                                    : FL_HELVETICA,
                      context == CONTEXT_COL_HEADER ? 10 : 12);
        drawing::color(context == CONTEXT_COL_HEADER || r >= series_->terms()
                           ? ui::muted
                           : ui::ink);
        drawing::draw(text, X + 10, Y, W - 20, H, FL_ALIGN_LEFT);
    }

    void draw_cell(TableContext context, int r, int c, int X, int Y, int W,
                   int H)
    {
        if (context != CONTEXT_COL_HEADER && context != CONTEXT_CELL)
            return;
        drawing::Scope paint(this);
        drawing::push_clip(X, Y, W, H);
        draw_background(context, r, c, X, Y, W, H);
        draw_content(context, r, c, X, Y, W, H);
        drawing::pop_clip();
    }

public:
    CoefficientTable(const fourier::Series *series)
        : Fl_Table(0, 0, 700, 150), series_(series)
    {
        cols(4);
        rows(0);
        col_header(1);
        col_header_height(29);
        box(FL_NO_BOX); // Filled boxes would cover the table's scrollbars.
        color(ui::paper);
        vscrollbar->color(ui::canvas);
        vscrollbar->selection_color(fl_rgb_color(207, 208, 224));
        hscrollbar->color(ui::canvas);
        hscrollbar->selection_color(fl_rgb_color(207, 208, 224));
        end();
    }
    void resize(int X, int Y, int W, int H)
    {
        Fl_Table::resize(X, Y, W, H);
        col_width(0, 115);
        int remaining = W - 115 - Fl::scrollbar_size();
        col_width(1, remaining / 3);
        col_width(2, remaining / 3);
        col_width(3, remaining - 2 * (remaining / 3));
    }
    void reset(int count)
    {
        rows(count);
        row_height_all(31);
        row_position(0);
        redraw();
    }
};

class ViewToggle : public Fl_Widget {
    int value_;

protected:
    void draw()
    {
        drawing::Scope paint(this);
        ui::round_fill(x(), y(), w(), h(), 9, ui::canvas);
        int selected_x = x() + value_ * (w() / 2);
        ui::round_fill(selected_x + 3, y() + 3, w() / 2 - 6, h() - 6, 7,
                       ui::paper);
        const char *labels[] = { "Spectrum", "Coefficients" };
        for (int i = 0; i < 2; ++i) {
            drawing::font(i == value_ ? FL_HELVETICA_BOLD : FL_HELVETICA, 11);
            drawing::color(i == value_ ? ui::ink : ui::muted);
            drawing::draw(labels[i], x() + w() * i / 2, y(), w() / 2, h(),
                          FL_ALIGN_CENTER);
        }
    }

public:
    ViewToggle() : Fl_Widget(0, 0, 228, 34), value_(0) {}
    int value() const { return value_; }
    void value(int n)
    {
        value_ = n;
        redraw();
    }
    int handle(int event)
    {
        if (event == FL_PUSH) {
            take_focus();
            value(Fl::event_x() >= x() + w() / 2 ? 1 : 0);
            do_callback();
            return 1;
        }
        if (event == FL_KEYDOWN
            && (Fl::event_key() == FL_Left || Fl::event_key() == FL_Right)) {
            value(1 - value_);
            do_callback();
            return 1;
        }
        if (event == FL_FOCUS || event == FL_UNFOCUS)
            return 1;
        return 0;
    }
};

class Inspector : public Fl_Group {
    static void view_cb(Fl_Widget *, void *data)
    {
        Inspector *panel = static_cast<Inspector*>(data);
        if (panel->toggle->value()) {
            panel->spectrum->hide();
            panel->table->show();
        } else {
            panel->table->hide();
            panel->spectrum->show();
        }
        panel->redraw();
    }

protected:
    void draw()
    {
        drawing::Scope paint(this);
        drawing::push_clip(x(), y(), w(), h());
        // A child can redraw only a few table cells. Preserve the existing
        // background and other cells unless the entire panel is damaged.
        if (damage() & ~FL_DAMAGE_CHILD) {
            ui::card(x(), y(), w(), h());
            ui::text(toggle->value() ? "Inside the series"
                                     : "Frequency spectrum",
                     x() + 22, y() + 30, 16, ui::ink, FL_HELVETICA_BOLD);
            ui::text(toggle->value()
                         ? "Coefficients and error after each harmonic."
                         : "Each bar is the strength of a harmonic.",
                     x() + 22, y() + 50, 11, ui::muted);
        }
        drawing::flush();
        draw_children();
        drawing::pop_clip();
    }

public:
    ViewToggle *toggle;
    Spectrum *spectrum;
    CoefficientTable *table;
    Inspector(const fourier::Series *series) : Fl_Group(0, 0, 700, 220)
    {
        toggle = new ViewToggle();
        toggle->callback(view_cb, this);
        spectrum = new Spectrum(series);
        table = new CoefficientTable(series);
        table->hide();
        end();
    }
    void resize(int X, int Y, int W, int H)
    {
        Fl_Widget::resize(X, Y, W, H);
        toggle->resize(X + W - 250, Y + 17, 228, 34);
        spectrum->resize(X + 16, Y + 65, W - 32, H - 78);
        table->resize(X + 16, Y + 65, W - 32, H - 81);
        redraw();
    }
};

struct App {
    fourier::Series series;
    Header *header;
    Sidebar *sidebar;
    WaveSelector *waveform;
    StudioSlider *amplitude, *phase, *harmonics;
    SampleChoice *samples;
    ActionButton *animate, *reset, *save;
    Metric *error, *energy, *terms;
    WaveformPlot *plot;
    Inspector *inspector;
    int requested;
    bool playing;
    App() : requested(15), playing(false) {}
};

static void animation_tick(void *data);

static double captured_energy(const fourier::Series &series)
{
    double energy = 0.0;
    for (int i = 0; i < series.samples(); ++i)
        energy += series.target(i) * series.target(i);
    if (energy == 0.0)
        return 100.0;
    double remaining = series.rmse() * series.rmse() * series.samples();
    return std::max(0.0, std::min(100.0, 100.0 * (1.0 - remaining / energy)));
}

static void refresh(App *a)
{
    char value[48];
    snprintf(value, sizeof(value), "%.4f", a->series.rmse());
    a->error->display(value, "sampled difference from target");
    snprintf(value, sizeof(value), "%.1f%%", captured_energy(a->series));
    a->energy->display(value, "of the sampled signal");
    if (a->series.terms() == a->requested)
        snprintf(value, sizeof(value), "%d", a->requested);
    else
        snprintf(value, sizeof(value), "%d / %d", a->series.terms(),
                 a->requested);
    a->terms->display(value, "sine + cosine frequency pairs");
    a->animate->copy_label(
        a->playing
            ? "Pause"
            : (a->series.terms() < a->requested ? "Continue" : "Animate"));
    a->plot->state(a->playing, a->requested);
    a->inspector->spectrum->requested(a->requested);
    a->inspector->table->redraw();
    a->sidebar->redraw();
}

static void begin_series(App *a)
{
    a->requested = static_cast<int>(a->harmonics->value());
    a->series.reset(static_cast<fourier::Waveform>(a->waveform->value()),
                    a->amplitude->value(),
                    a->phase->value() * fourier::pi / 180.0,
                    256 << a->samples->value());
    a->inspector->table->reset(a->requested);
}

static void rebuild(App *a)
{
    a->playing = false;
    Fl::remove_timeout(animation_tick, a);
    begin_series(a);
    for (int i = 0; i < a->requested; ++i)
        a->series.add_harmonic();
    refresh(a);
}

static void settings_cb(Fl_Widget *, void *data)
{
    rebuild(static_cast<App*>(data));
}

static void animate_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);
    Fl::remove_timeout(animation_tick, a);
    if (a->playing)
        a->playing = false;
    else {
        if (a->series.terms() >= a->requested)
            begin_series(a);
        a->playing = true;
        Fl::add_timeout(0.075, animation_tick, a);
    }
    refresh(a);
}

static void animation_tick(void *data)
{
    App *a = static_cast<App*>(data);
    if (!a->playing)
        return;
    if (!a->series.add_harmonic() || a->series.terms() >= a->requested)
        a->playing = false;
    else
        Fl::repeat_timeout(0.075, animation_tick, a);
    refresh(a);
}

static void reset_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);
    a->waveform->value(0);
    a->amplitude->value(1.0);
    a->phase->value(0.0);
    a->harmonics->value(15);
    a->samples->value(2);
    rebuild(a);
}

static bool write_csv(FILE *file, const fourier::Series &series)
{
    if (fprintf(file, "x,target,approximation,error\n") < 0)
        return false;
    for (int i = 0; i < series.samples(); ++i) {
        if (fprintf(file, "%.17g,%.17g,%.17g,%.17g\n", series.x(i),
                    series.target(i), series.approximation(i),
                    series.target(i) - series.approximation(i))
            < 0)
            return false;
    }
    return true;
}

static void configure_export(Fl_Native_File_Chooser &chooser)
{
    chooser.title("Export Fourier samples");
    chooser.type(Fl_Native_File_Chooser::BROWSE_SAVE_FILE);
    chooser.options(Fl_Native_File_Chooser::SAVEAS_CONFIRM);
    chooser.filter("CSV files\t*.csv");
    chooser.preset_file("fourier_samples.csv");
    char directory[FL_PATH_MAX];
    fl_filename_absolute(directory, sizeof(directory), ".");
    chooser.directory(directory);
}

static void export_csv(const char *path, const fourier::Series &series)
{
    FILE *file = fopen(path, "w");
    if (!file) {
        fl_alert("Could not open the CSV file for writing.");
        return;
    }
    bool ok = write_csv(file, series);
    if (fclose(file) != 0)
        ok = false;
    if (!ok)
        fl_alert("Could not finish writing the CSV file.");
}

static void save_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);
    // The chooser runs a nested event loop. Export a consistent snapshot.
    const fourier::Series snapshot = a->series;
    Fl_Native_File_Chooser chooser;
    configure_export(chooser);
    int result = chooser.show();
    if (result == 1)
        return;
    if (result == -1) {
        fl_alert("Could not open the file chooser: %s", chooser.errmsg());
        return;
    }
    export_csv(chooser.filename(), snapshot);
}

static void close_cb(Fl_Widget *widget, void *data)
{
    App *a = static_cast<App*>(data);
    a->playing = false;
    Fl::remove_timeout(animation_tick, a);
    widget->hide();
}

static void layout(App &a, int width, int height)
{
    a.header->resize(0, 0, width, 90);
    a.sidebar->resize(24, 104, ui::sidebar_w, height - 128);
    a.save->resize(width - 160, 28, 136, 42);
    int content_w = width - ui::content_x - ui::margin;
    int metric_w = (content_w - 32) / 3;
    a.error->resize(ui::content_x, 104, metric_w, 96);
    a.energy->resize(ui::content_x + metric_w + 16, 104, metric_w, 96);
    a.terms->resize(ui::content_x + 2 * (metric_w + 16), 104,
                    content_w - 2 * (metric_w + 16), 96);
    int available = height - 212 - ui::margin - 16;
    int plot_h = available * 64 / 100;
    a.plot->resize(ui::content_x, 212, content_w, plot_h);
    a.inspector->resize(ui::content_x, 212 + plot_h + 16, content_w,
                        available - plot_h);
}

class StudioWindow : public Fl_Double_Window {
    App *app_;

public:
    StudioWindow()
        : Fl_Double_Window(ui::window_w, ui::window_h, "Fourier Studio"),
          app_(0)
    {
        color(ui::canvas);
        // All geometry is handled by layout(); do not also scale children.
        resizable(0);
        size_range(ui::min_w, ui::min_h);
    }
    void bind(App *a)
    {
        app_ = a;
        layout(*app_, w(), h());
    }
    void resize(int X, int Y, int W, int H)
    {
        Fl_Double_Window::resize(X, Y, W, H);
        if (app_)
            layout(*app_, W, H);
    }
};

static void build_amplitude(App &a)
{
    a.amplitude = new StudioSlider(268, "Amplitude", 0);
    a.amplitude->bounds(0.1, 5.0);
    a.amplitude->step(0.05);
    a.amplitude->value(1.0);
}

static void build_phase(App &a)
{
    a.phase = new StudioSlider(348, "Phase shift", 1);
    a.phase->bounds(-180, 180);
    a.phase->step(1);
    a.phase->value(0);
    a.phase->tooltip("Evaluate the waveform at x + phase. "
                     "Use arrow keys for precise changes.");
}

static void build_harmonics(App &a)
{
    a.harmonics = new StudioSlider(428, "Harmonics", 2);
    a.harmonics->bounds(1, 100);
    a.harmonics->step(1);
    a.harmonics->value(15);
    a.harmonics->tooltip("Include frequencies 1 through n. "
                         "Arrow keys change one harmonic at a time.");
}

static void build_sidebar_buttons(App &a)
{
    a.animate = new ActionButton(46, 602, 140, 44, "Animate", true);
    a.animate->callback(animate_cb, &a);
    a.animate->shortcut(' ');
    a.animate->tooltip("Build the signal one harmonic at a time. "
                       "Space starts or pauses the animation.");
    a.reset = new ActionButton(194, 602, 68, 44, "Reset", false);
    a.reset->callback(reset_cb, &a);
    a.reset->shortcut(FL_CTRL + 'r');
    a.reset->tooltip("Restore the original square wave settings. Ctrl+R.");
}

static void build_sidebar(App &a)
{
    a.header = new Header();
    a.sidebar = new Sidebar(&a.series);
    a.waveform = new WaveSelector();
    build_amplitude(a);
    build_phase(a);
    build_harmonics(a);
    a.samples = new SampleChoice();
    a.samples->tooltip("More samples improve the numerical "
                       "coefficient estimates.");
    a.waveform->callback(settings_cb, &a);
    a.amplitude->callback(settings_cb, &a);
    a.phase->callback(settings_cb, &a);
    a.harmonics->callback(settings_cb, &a);
    a.samples->callback(settings_cb, &a);
    build_sidebar_buttons(a);
    a.sidebar->end();
}

static void build_export(App &a)
{
    a.save = new ActionButton(0, 28, 136, 42, "Export CSV", false, true);
    a.save->callback(save_cb, &a);
    a.save->shortcut(FL_CTRL + 'e');
    a.save->tooltip("Export the current target, "
                    "reconstruction and error. Ctrl+E.");
}

static void build_metrics(App &a)
{
    a.error = new Metric("RMS ERROR");
    a.error->tooltip("Root mean square error, "
                     "measured at the sampled points.");
    a.energy = new Metric("ENERGY CAPTURED");
    a.energy->tooltip("Fraction of sampled signal energy "
                      "explained by the series, including its mean.");
    a.terms = new Metric("HARMONICS");
}

static void build_ui(App &a, StudioWindow &win)
{
    build_sidebar(a);
    build_export(a);
    build_metrics(a);
    a.plot = new WaveformPlot(&a.series);
    a.inspector = new Inspector(&a.series);
    win.end();
    win.callback(close_cb, &a);
    win.bind(&a);
    rebuild(&a);
}

#ifndef FOURIER_STUDIO_TEST
int main()
{
    Fl::set_font(FL_HELVETICA, " Inter");
    Fl::set_font(FL_HELVETICA_BOLD, "BInter");
    Fl::scheme("gtk+");
    Fl::background(246, 246, 249);
    Fl::background2(255, 255, 255);
    Fl::foreground(37, 40, 57);
    Fl::scrollbar_size(12);
    Fl_Tooltip::delay(0.55);
    Fl_Tooltip::color(ui::ink);
    Fl_Tooltip::textcolor(ui::paper);
    Fl_Tooltip::size(12);
    App a;
    StudioWindow win;
    build_ui(a, win);
    win.show();
    int result = Fl::run();
    Fl::remove_timeout(animation_tick, &a);
    return result;
}
#endif
menus.cppC++ / 139 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Menu_.H>
#include <FL/Fl_Menu_Bar.H>
#include <FL/Fl_Menu_Button.H>
#include <FL/Fl_Choice.H>
#include <FL/Fl_Tree.H>
#include <FL/Fl_Tree_Item.H>

enum {
    spacing = 20,
    menu_h = 30,
    row_h = 35,
    button_w = 170,
    choice_w = 180,
    tree_h = 260,
    status_h = 40,
    win_w = 600,

    row_y = menu_h + spacing,
    choice_x = win_w - spacing - choice_w,
    tree_y = row_y + row_h + spacing,
    status_y = tree_y + tree_h + spacing,
    win_h = status_y + status_h + spacing
};

static void menu_cb(Fl_Widget *w, void *data)
{
    Fl_Menu_ *menu = static_cast<Fl_Menu_*>(w);
    Fl_Box *status = static_cast<Fl_Box*>(data);

    const Fl_Menu_Item *item = menu->mvalue();

    if (item) {
        status->copy_label(item->label());
        printf("Menu: %s\n", item->label());
    }
}

static void quit_cb(Fl_Widget *, void *data)
{
    Fl_Window *win = static_cast<Fl_Window*>(data);
    win->hide();
}

static void choice_cb(Fl_Widget *w, void *data)
{
    Fl_Choice *choice = static_cast<Fl_Choice*>(w);
    Fl_Box *status = static_cast<Fl_Box*>(data);

    const Fl_Menu_Item *item = choice->mvalue();

    if (item) {
        status->copy_label(item->label());
        printf("Choice: %s\n", item->label());
    }
}

static void tree_cb(Fl_Widget *w, void *data)
{
    Fl_Tree *tree = static_cast<Fl_Tree*>(w);
    Fl_Box *status = static_cast<Fl_Box*>(data);

    Fl_Tree_Item *item = tree->callback_item();

    if (!item)
        return;

    const char *action = "Changed";

    switch (tree->callback_reason()) {
    case FL_TREE_REASON_SELECTED:
        action = "Selected";
        break;

    case FL_TREE_REASON_DESELECTED:
        action = "Deselected";
        break;

    case FL_TREE_REASON_OPENED:
        action = "Opened";
        break;

    case FL_TREE_REASON_CLOSED:
        action = "Closed";
        break;

    default:
        break;
    }

    char text[256];
    sprintf(text, "%s: %s", action, item->label());
    status->copy_label(text);
    puts(text);
}

int main()
{
    Fl_Window win(win_w, win_h, "FLTK menu examples");

    Fl_Box status(spacing, status_y, win_w - 2 * spacing, status_h, "Ready");
    status.box(FL_DOWN_BOX);
    status.align(FL_ALIGN_LEFT | FL_ALIGN_INSIDE);

    Fl_Menu_Bar bar(0, 0, win_w, menu_h);
    bar.add("&File/&Hello");
    bar.add("&File/&Quit", FL_CTRL + 'q', quit_cb, &win);
    bar.add("&Help/&About");
    bar.callback(menu_cb, &status);

    Fl_Menu_Button button(spacing, row_y, button_w, row_h, "Actions");
    button.add("Show message");
    button.add("Reset message");
    button.callback(menu_cb, &status);

    Fl_Choice choice(choice_x, row_y, choice_w, row_h, "Color:");
    choice.add("Red");
    choice.add("Green");
    choice.add("Blue");
    choice.value(0);
    choice.callback(choice_cb, &status);

    Fl_Tree tree(spacing, tree_y, win_w - 2 * spacing, tree_h);
    tree.root_label("Topics");
    tree.add("Projects/GUI/FLTK");
    tree.add("Projects/GUI/Qt");
    tree.add("Projects/CLI");
    tree.add("Languages/C++");
    tree.add("Languages/Assembly");
    tree.callback(tree_cb, &status);

    win.end();
    win.show();

    return Fl::run();
}
scroll.cppC++ / 83 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Scroll.H>
#include <FL/Fl_Pack.H>

enum {
    spacing = 15,
    gap = 8,
    title_h = 30,
    row_h = 42,
    row_count = 15,
    scroll_w = 460,
    scroll_h = 260,
    pack_w = scroll_w + 200,
    pack_h = row_count * row_h + (row_count - 1) * gap,
    toolbar_h = 45,
    toolbar_button_w = 135,

    scroll_x = spacing,
    scroll_y = spacing + title_h + spacing,
    toolbar_y = scroll_y + scroll_h + spacing,

    win_w = scroll_w + 2 * spacing,
    win_h = toolbar_y + toolbar_h + spacing
};

static void button_cb(Fl_Widget *w, void *)
{
    printf("Clicked: %s\n", w->label());
    fflush(stdout);
}

int main()
{
    Fl_Window win(win_w, win_h, "Fl_Scroll and Fl_Pack");

    Fl_Box title(spacing, spacing, scroll_w, title_h,
                 "Scroll in both directions");

    Fl_Scroll scroll(scroll_x, scroll_y, scroll_w, scroll_h);
    scroll.box(FL_DOWN_FRAME);
    scroll.type(Fl_Scroll::BOTH);

    Fl_Pack vertical(scroll_x + gap, scroll_y + gap, pack_w, pack_h);
    vertical.type(Fl_Pack::VERTICAL);
    vertical.spacing(gap);

    for (int i = 0; i < row_count; ++i) {
        char label[80];
        sprintf(label, "Button %d - Click me!", i + 1);

        Fl_Button *button = new Fl_Button(scroll_x + gap, scroll_y + gap,
                                          pack_w, row_h);
        button->copy_label(label);
        button->callback(button_cb);
    }

    vertical.end();
    scroll.end();

    Fl_Pack horizontal(spacing, toolbar_y, scroll_w, toolbar_h);
    horizontal.type(Fl_Pack::HORIZONTAL);
    horizontal.spacing(gap);

    Fl_Button first(spacing, toolbar_y, toolbar_button_w, toolbar_h, "First");
    first.callback(button_cb);

    Fl_Button second(spacing, toolbar_y, toolbar_button_w, toolbar_h, "Second");
    second.callback(button_cb);

    Fl_Button third(spacing, toolbar_y, toolbar_button_w, toolbar_h, "Third");
    third.callback(button_cb);

    horizontal.end();

    win.end();
    win.show();

    return Fl::run();
}
studio_drawing.hC / 539 lines
#ifndef STUDIO_DRAWING_H
#define STUDIO_DRAWING_H

#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <dlfcn.h>
#include <cairo/cairo.h>
#include <cairo/cairo-xlib.h>
#include <FL/x.H>
#include <FL/fl_draw.H>

struct _PangoLayout;
struct _PangoFontDescription;

// The existing Makefile links FLTK. Load the desktop's Cairo/Pango libraries
// at runtime, and retain native drawing if they are unavailable.
namespace drawing {
typedef ::_PangoLayout PangoLayout;
typedef ::_PangoFontDescription PangoFontDescription;

#define LOAD_CAIRO(name) bind(cairo_library_, name, "cairo_" #name)

class Api {
    template <class T> bool bind(void *library, T &function, const char *name)
    {
        void *symbol = dlsym(library, name);
        if (!symbol || sizeof(function) != sizeof(symbol))
            return false;
        std::memcpy(&function, &symbol, sizeof(function));
        return true;
    }
    void *cairo_library_, *pango_library_;

public:
    bool ready;
    cairo_surface_t *(*xlib_surface_create)(Display *, Drawable, Visual *, int,
                                            int);
    void (*surface_destroy)(cairo_surface_t *);
    void (*surface_flush)(cairo_surface_t *);
    void (*surface_mark_dirty)(cairo_surface_t *);
    cairo_status_t (*surface_status)(cairo_surface_t *);
    cairo_t *(*create)(cairo_surface_t *);
    void (*destroy)(cairo_t *);
    void (*save)(cairo_t *);
    void (*restore)(cairo_t *);
    void (*rectangle)(cairo_t *, double, double, double, double);
    void (*clip)(cairo_t *);
    void (*new_path)(cairo_t *);
    void (*move_to)(cairo_t *, double, double);
    void (*line_to)(cairo_t *, double, double);
    void (*curve_to)(cairo_t *, double, double, double, double, double, double);
    void (*close_path)(cairo_t *);
    void (*arc)(cairo_t *, double, double, double, double, double);
    void (*translate)(cairo_t *, double, double);
    void (*scale)(cairo_t *, double, double);
    void (*set_source_rgb)(cairo_t *, double, double, double);
    void (*set_line_width)(cairo_t *, double);
    void (*set_line_cap)(cairo_t *, cairo_line_cap_t);
    void (*set_line_join)(cairo_t *, cairo_line_join_t);
    void (*set_dash)(cairo_t *, const double *, int, double);
    void (*fill)(cairo_t *);
    void (*stroke)(cairo_t *);
    void (*set_antialias)(cairo_t *, cairo_antialias_t);
    void (*set_fill_rule)(cairo_t *, cairo_fill_rule_t);
    cairo_font_options_t *(*font_options_create)();
    void (*font_options_destroy)(cairo_font_options_t *);
    void (*font_options_set_antialias)(cairo_font_options_t *,
                                       cairo_antialias_t);
    void (*font_options_set_hint_style)(cairo_font_options_t *,
                                        cairo_hint_style_t);
    void (*font_options_set_hint_metrics)(cairo_font_options_t *,
                                          cairo_hint_metrics_t);
    void (*set_font_options)(cairo_t *, const cairo_font_options_t *);
    PangoLayout *(*create_layout)(cairo_t *);
    void (*layout_set_text)(PangoLayout *, const char *, int);
    void (*layout_set_font_description)(PangoLayout *,
                                        const PangoFontDescription *);
    void (*layout_get_size)(PangoLayout *, int *, int *);
    int (*layout_get_baseline)(PangoLayout *);
    PangoFontDescription *(*font_description_new)();
    void (*font_description_free)(PangoFontDescription *);
    void (*font_description_set_family)(PangoFontDescription *, const char *);
    void (*font_description_set_weight)(PangoFontDescription *, int);
    void (*font_description_set_absolute_size)(PangoFontDescription *, double);
    void (*show_layout)(cairo_t *, PangoLayout *);
    void (*object_unref)(void *);

private:
    bool load_surface_functions()
    {
        return LOAD_CAIRO(xlib_surface_create) && LOAD_CAIRO(surface_destroy)
               && LOAD_CAIRO(surface_flush) && LOAD_CAIRO(surface_mark_dirty)
               && LOAD_CAIRO(surface_status);
    }

    bool load_path_functions()
    {
        return LOAD_CAIRO(create) && LOAD_CAIRO(destroy) && LOAD_CAIRO(save)
               && LOAD_CAIRO(restore) && LOAD_CAIRO(rectangle)
               && LOAD_CAIRO(clip) && LOAD_CAIRO(new_path)
               && LOAD_CAIRO(move_to) && LOAD_CAIRO(line_to)
               && LOAD_CAIRO(curve_to) && LOAD_CAIRO(close_path);
    }

    bool load_paint_functions()
    {
        return LOAD_CAIRO(arc) && LOAD_CAIRO(translate) && LOAD_CAIRO(scale)
               && LOAD_CAIRO(set_source_rgb) && LOAD_CAIRO(set_line_width)
               && LOAD_CAIRO(set_line_cap) && LOAD_CAIRO(set_line_join)
               && LOAD_CAIRO(set_dash) && LOAD_CAIRO(fill) && LOAD_CAIRO(stroke)
               && LOAD_CAIRO(set_antialias) && LOAD_CAIRO(set_fill_rule);
    }

    bool load_font_options()
    {
        return LOAD_CAIRO(font_options_create)
               && LOAD_CAIRO(font_options_destroy)
               && LOAD_CAIRO(font_options_set_antialias)
               && LOAD_CAIRO(font_options_set_hint_style)
               && LOAD_CAIRO(font_options_set_hint_metrics)
               && LOAD_CAIRO(set_font_options);
    }

    bool load_layout_functions()
    {
        return bind(pango_library_, create_layout, "pango_cairo_create_layout")
               && bind(pango_library_, layout_set_text, "pango_layout_set_text")
               && bind(pango_library_, layout_set_font_description,
                       "pango_layout_set_font_description")
               && bind(pango_library_, layout_get_size, "pango_layout_get_size")
               && bind(pango_library_, layout_get_baseline,
                       "pango_layout_get_baseline");
    }

    bool load_font_functions()
    {
        return bind(pango_library_, font_description_new,
                    "pango_font_description_new")
               && bind(pango_library_, font_description_free,
                       "pango_font_description_free")
               && bind(pango_library_, font_description_set_family,
                       "pango_font_description_set_family")
               && bind(pango_library_, font_description_set_weight,
                       "pango_font_description_set_weight")
               && bind(pango_library_, font_description_set_absolute_size,
                       "pango_font_description_set_absolute_size")
               && bind(pango_library_, show_layout, "pango_cairo_show_layout")
               && bind(pango_library_, object_unref, "g_object_unref");
    }

public:
    Api() : cairo_library_(0), pango_library_(0), ready(false)
    {
        if (std::getenv("FOURIER_STUDIO_NATIVE_RENDER"))
            return;
        cairo_library_ = dlopen("libcairo.so.2", RTLD_NOW | RTLD_LOCAL);
        pango_library_ =
            dlopen("libpangocairo-1.0.so.0", RTLD_NOW | RTLD_LOCAL);
        if (!cairo_library_ || !pango_library_)
            return;
        ready = load_surface_functions() && load_path_functions()
                && load_paint_functions() && load_font_options()
                && load_layout_functions() && load_font_functions();
    }
    ~Api()
    {
        if (pango_library_)
            dlclose(pango_library_);
        if (cairo_library_)
            dlclose(cairo_library_);
    }
};

#undef LOAD_CAIRO

inline Api &api()
{
    static Api instance;
    return instance;
}
class Scope;
static Scope *current = 0;

class Scope {
    Scope *previous_;
    Scope(const Scope &);
    Scope &operator=(const Scope &);

public:
    cairo_surface_t *surface;
    cairo_t *context;
    PangoLayout *layout;
    PangoFontDescription *font;
    double width;
    bool first_vertex;

private:
    bool initialize_surface(Fl_Widget *widget)
    {
        if (!api().ready || !fl_display || !fl_window || !widget->window())
            return false;
        surface = api().xlib_surface_create(
            fl_display, fl_window, fl_visual->visual, widget->window()->w(),
            widget->window()->h());
        return api().surface_status(surface) == CAIRO_STATUS_SUCCESS;
    }

    void clip_widget(Fl_Widget *widget)
    {
        // Preserve FLTK's current damage/parent clip.
        int X, Y, W, H;
        ::fl_clip_box(widget->x(), widget->y(), widget->w(), widget->h(), X, Y,
                      W, H);
        api().rectangle(context, X, Y, W, H);
        api().clip(context);
    }

    void configure_font_options()
    {
        cairo_font_options_t *options = api().font_options_create();
        api().font_options_set_antialias(options, CAIRO_ANTIALIAS_GRAY);
        api().font_options_set_hint_style(options, CAIRO_HINT_STYLE_SLIGHT);
        api().font_options_set_hint_metrics(options, CAIRO_HINT_METRICS_OFF);
        api().set_font_options(context, options);
        api().font_options_destroy(options);
    }

    void initialize_context(Fl_Widget *widget)
    {
        context = api().create(surface);
        api().set_antialias(context, CAIRO_ANTIALIAS_BEST);
        api().set_line_width(context, 1.0);
        api().set_line_cap(context, CAIRO_LINE_CAP_ROUND);
        api().set_line_join(context, CAIRO_LINE_JOIN_ROUND);
        clip_widget(widget);
        configure_font_options();
    }

    void initialize_layout()
    {
        layout = api().create_layout(context);
        font = api().font_description_new();
        api().font_description_set_family(font, "Inter");
        api().font_description_set_weight(font, 400);
        api().font_description_set_absolute_size(font, 13.0 * 1024);
        api().layout_set_font_description(layout, font);
    }

public:
    Scope(Fl_Widget *widget)
        : previous_(current), surface(0), context(0), layout(0), font(0),
          width(1.0), first_vertex(true)
    {
        if (previous_ && previous_->surface)
            api().surface_flush(previous_->surface);
        current = this;
        if (!initialize_surface(widget))
            return;
        initialize_context(widget);
        initialize_layout();
    }
    ~Scope()
    {
        if (layout)
            api().object_unref(layout);
        if (font)
            api().font_description_free(font);
        if (surface)
            api().surface_flush(surface);
        if (context)
            api().destroy(context);
        if (surface)
            api().surface_destroy(surface);
        current = previous_;
        // Native children (e.g. table scrollbars) may have drawn to the same
        // drawable.
        if (current && current->surface)
            api().surface_mark_dirty(current->surface);
    }
};

inline bool active() { return current && current->context; }
inline cairo_t *context() { return current->context; }
inline void flush()
{
    if (active())
        api().surface_flush(current->surface);
}

inline void color(Fl_Color c)
{
    ::fl_color(c);
    if (!active())
        return;
    unsigned char r, g, b;
    Fl::get_color(c, r, g, b);
    api().set_source_rgb(context(), r / 255.0, g / 255.0, b / 255.0);
}

inline void font(Fl_Font f, int size)
{
    ::fl_font(f, size);
    if (!active())
        return;
    api().font_description_set_weight(current->font,
                                      f == FL_HELVETICA_BOLD ? 600 : 400);
    api().font_description_set_absolute_size(current->font, size * 1024.0);
    api().layout_set_font_description(current->layout, current->font);
}

inline void draw(const char *text, double x, double baseline)
{
    if (!active()) {
        ::fl_draw(text, static_cast<int>(x), static_cast<int>(baseline));
        return;
    }
    api().layout_set_text(current->layout, text, -1);
    double ascent = api().layout_get_baseline(current->layout) / 1024.0;
    api().move_to(context(), x, baseline - ascent);
    api().show_layout(context(), current->layout);
}

inline void draw(const char *text, int x, int y, int w, int h, Fl_Align align)
{
    if (!active()) {
        ::fl_draw(text, x, y, w, h, align);
        return;
    }
    api().layout_set_text(current->layout, text, -1);
    int width, height;
    api().layout_get_size(current->layout, &width, &height);
    double W = width / 1024.0, H = height / 1024.0;
    double X = align & FL_ALIGN_LEFT
                   ? x
                   : (align & FL_ALIGN_RIGHT ? x + w - W : x + (w - W) / 2.0);
    double Y = align & FL_ALIGN_TOP
                   ? y
                   : (align & FL_ALIGN_BOTTOM ? y + h - H : y + (h - H) / 2.0);
    api().move_to(context(), X, Y);
    api().show_layout(context(), current->layout);
}

inline void rectf(int x, int y, int w, int h)
{
    if (!active()) {
        ::fl_rectf(x, y, w, h);
        return;
    }
    api().rectangle(context(), x, y, w, h);
    api().fill(context());
}

inline void native_round_rect(int x, int y, int w, int h, int r)
{
    ::fl_rectf(x + r, y, w - 2 * r, h);
    ::fl_rectf(x, y + r, w, h - 2 * r);
    ::fl_pie(x, y, 2 * r, 2 * r, 0, 360);
    ::fl_pie(x + w - 2 * r, y, 2 * r, 2 * r, 0, 360);
    ::fl_pie(x, y + h - 2 * r, 2 * r, 2 * r, 0, 360);
    ::fl_pie(x + w - 2 * r, y + h - 2 * r, 2 * r, 2 * r, 0, 360);
}

inline void rounded_path(int x, int y, int w, int h, int r)
{
    double k = r * 0.5522847498307936;
    api().new_path(context());
    api().move_to(context(), x + r, y);
    api().line_to(context(), x + w - r, y);
    api().curve_to(context(), x + w - r + k, y, x + w, y + r - k, x + w, y + r);
    api().line_to(context(), x + w, y + h - r);
    api().curve_to(context(), x + w, y + h - r + k, x + w - r + k, y + h,
                   x + w - r, y + h);
    api().line_to(context(), x + r, y + h);
    api().curve_to(context(), x + r - k, y + h, x, y + h - r + k, x, y + h - r);
    api().line_to(context(), x, y + r);
    api().curve_to(context(), x, y + r - k, x + r - k, y, x + r, y);
    api().close_path(context());
}

inline void round_rect(int x, int y, int w, int h, int r, Fl_Color c)
{
    color(c);
    if (w <= 0 || h <= 0)
        return;
    r = std::min(r, std::min(w, h) / 2);
    if (!active()) {
        native_round_rect(x, y, w, h, r);
        return;
    }
    rounded_path(x, y, w, h, r);
    api().fill(context());
}

inline void pie(int x, int y, int w, int h, double start, double end)
{
    if (!active()) {
        ::fl_pie(x, y, w, h, start, end);
        return;
    }
    api().new_path(context());
    api().save(context());
    api().translate(context(), x + w / 2.0, y + h / 2.0);
    api().scale(context(), w / 2.0, h / 2.0);
    api().arc(context(), 0, 0, 1, start * 0.0174532925199433,
              end * 0.0174532925199433);
    api().restore(context());
    api().fill(context());
}

inline void line_style(int style, int width = 0)
{
    ::fl_line_style(style, width);
    if (!active())
        return;
    current->width = width ? width : 1;
    api().set_line_width(context(), current->width);
    double dashed[] = { 4, 3 }, dotted[] = { 1, 3 };
    if ((style & 255) == FL_DASH)
        api().set_dash(context(), dashed, 2, 0);
    else if ((style & 255) == FL_DOT)
        api().set_dash(context(), dotted, 2, 0);
    else
        api().set_dash(context(), 0, 0, 0);
}

inline void line(double x1, double y1, double x2, double y2)
{
    if (!active()) {
        ::fl_line(static_cast<int>(x1), static_cast<int>(y1),
                  static_cast<int>(x2), static_cast<int>(y2));
        return;
    }
    double snap = current->width == 1.0 ? 0.5 : 0.0;
    api().new_path(context());
    api().move_to(context(), x1 + snap, y1 + snap);
    api().line_to(context(), x2 + snap, y2 + snap);
    api().stroke(context());
}

inline void line(int x1, int y1, int x2, int y2, int x3, int y3)
{
    if (!active()) {
        ::fl_line(x1, y1, x2, y2, x3, y3);
        return;
    }
    double snap = current->width == 1.0 ? 0.5 : 0.0;
    api().new_path(context());
    api().move_to(context(), x1 + snap, y1 + snap);
    api().line_to(context(), x2 + snap, y2 + snap);
    api().line_to(context(), x3 + snap, y3 + snap);
    api().stroke(context());
}

inline void polygon(int x1, int y1, int x2, int y2, int x3, int y3)
{
    if (!active()) {
        ::fl_polygon(x1, y1, x2, y2, x3, y3);
        return;
    }
    api().new_path(context());
    api().move_to(context(), x1, y1);
    api().line_to(context(), x2, y2);
    api().line_to(context(), x3, y3);
    api().close_path(context());
    api().fill(context());
}

inline void push_clip(int x, int y, int w, int h)
{
    ::fl_push_clip(x, y, w, h);
    if (!active())
        return;
    api().save(context());
    api().rectangle(context(), x, y, w, h);
    api().clip(context());
}

inline void pop_clip()
{
    if (active())
        api().restore(context());
    ::fl_pop_clip();
}

inline void begin_line()
{
    if (!active()) {
        ::fl_begin_line();
        return;
    }
    api().new_path(context());
    current->first_vertex = true;
}

inline void vertex(double x, double y)
{
    if (!active()) {
        ::fl_vertex(x, y);
        return;
    }
    if (current->first_vertex)
        api().move_to(context(), x, y);
    else
        api().line_to(context(), x, y);
    current->first_vertex = false;
}

inline void end_line()
{
    if (!active()) {
        ::fl_end_line();
        return;
    }
    api().stroke(context());
}

inline void begin_complex_polygon()
{
    if (!active()) {
        ::fl_begin_complex_polygon();
        return;
    }
    begin_line();
}

inline void end_complex_polygon()
{
    if (!active()) {
        ::fl_end_complex_polygon();
        return;
    }
    api().close_path(context());
    api().set_fill_rule(context(), CAIRO_FILL_RULE_EVEN_ODD);
    api().fill(context());
    api().set_fill_rule(context(), CAIRO_FILL_RULE_WINDING);
}
} // namespace drawing
#endif

10.11.10 FLTK and OOP

An adapter can translate a plain FLTK callback into a virtual method on an object. A static bridge recovers the instance from callback context, while application subclasses override OnPress with their particular behavior.

The adapter turns FLTK's function-plus-void* callback into a virtual method:

#include <FL/Fl_Button.H>

class OOFLButton : public Fl_Button {
public:
    OOFLButton(int x, int y, int w, int h, const char *label = 0)
        : Fl_Button(x, y, w, h, label) { callback(CallbackFunction, 0); }
    virtual ~OOFLButton() {}
    virtual void OnPress() {}       // default: do nothing
private:
    static void CallbackFunction(Fl_Widget *w, void *user)
        { static_cast<OOFLButton*>(w)->OnPress(); }
};

Application classes then hold their data in fields:

#include <FL/Fl_Window.H>

enum { spacing = 5, button_w = 200, button_h = 40, font_size = 20 };

class ButtonCommon : public OOFLButton {
public:
    ButtonCommon(int row, const char *label)
        : OOFLButton(spacing, spacing + row * (button_h + spacing),
                     button_w, button_h, label)
        { labelsize(font_size); }
};

class SayButton : public ButtonCommon {
    const char *message;
public:
    SayButton(int row, const char *label, const char *a_message)
        : ButtonCommon(row, label), message(a_message) {}
    virtual void OnPress() { printf("%s\n", message); fflush(stdout); }
};

class ExitButton : public ButtonCommon {
public:
    ExitButton(int row, const char *label) : ButtonCommon(row, label) {}
    virtual void OnPress() { window()->hide(); }
};
Show the complete program
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
#include <stdio.h>

class OOFLButton : public Fl_Button {
public:
    OOFLButton(int x, int y, int w, int h, const char *label = 0)
        : Fl_Button(x, y, w, h, label) { callback(CallbackFunction, 0); }
    virtual ~OOFLButton() {}
    virtual void OnPress() {}
private:
    static void CallbackFunction(Fl_Widget *w, void *user)
        { static_cast<OOFLButton*>(w)->OnPress(); }
};

enum { spacing = 5, button_w = 200, button_h = 40, font_size = 20 };

class ButtonCommon : public OOFLButton {
public:
    ButtonCommon(int row, const char *label)
        : OOFLButton(spacing, spacing + row * (button_h + spacing),
                     button_w, button_h, label)
        { labelsize(font_size); }
};

class SayButton : public ButtonCommon {
    const char *message;
public:
    SayButton(int row, const char *label, const char *a_message)
        : ButtonCommon(row, label), message(a_message) {}
    virtual void OnPress() { printf("%s\n", message); fflush(stdout); }
};

class ExitButton : public ButtonCommon {
public:
    ExitButton(int row, const char *label) : ButtonCommon(row, label) {}
    virtual void OnPress() { window()->hide(); }
};

int main(int argc, char **argv)
{
    Fl_Window *win = new Fl_Window(button_w + 2 * spacing,
                                   3 * button_h + 4 * spacing, "OOFL demo");
    new SayButton(0, "Say hello", "Hello, world!");
    new SayButton(1, "Say goodbye", "Goodbye, world!");
    new ExitButton(2, "Quit");
    win->end();
    win->show(argc, argv);
    return Fl::run();
}
Detailed notes - 10.11.10: FLTK and OOP

1

inspect the toolkit as an example of architectural paradigms

2

the author considers parts of FLTK only partly object-oriented

  • base classes sometimes implement many optional behaviors
  • some derived widgets mainly select modes already implemented by a base
  • this is an assessment against his preferred OOP model

3

he also contrasts callback functions with object/message interaction

4

ordinary callback registration combines function address and void* context

  • callback casts that context back to the expected type
  • caller and callback must agree about its type and lifetime

5

an object-oriented alternative passes an object with a virtual method

  • object fields hold its context
  • service sends a message by calling that method
  • a derived override supplies application-specific behavior

6

for widgets, derive a class and override an event-reaction method

  • keep the reaction's data in that object's fields

7

an adapter layer can provide that interface over FLTK callbacks

  • the example uses an OOFL prefix for reusable adapter classes
  • application-specific subclasses then supply their own behavior

8

rewrite the earlier speaking-buttons demo with unchanged visible behavior

  • change its decomposition and event interface

9

OOFLButton derives from Fl_Button

  • constructor registers one bridge callback
  • callback invokes virtual OnPress()
  • default OnPress does nothing; subclasses override it

10

a no-op default is meaningful here

  • the author therefore chooses a concrete virtual method
  • pure virtual would instead require every concrete subclass to override

11

a normal non-static member cannot match the plain callback pointer type

  • it has an implicit object parameter

private static CallbackFunction matches FLTK's callback signature

  • use its Fl_Widget* argument to recover the OOFLButton
  • the adapter constructor establishes the precondition for that cast
  • dispatch OnPress virtually on that object

12

the adapter explicitly declares a virtual destructor

  • preserves polymorphic lifetime behavior
  • FLTK's base already supplies virtual destruction in this example

13

the reusable adapter contains no application-specific action

  • short methods can stay in its class definition
  • a real project can place the adapter in its own module

14

application subclasses divide the two button roles

  • SayButton prints a message
  • ExitButton requests termination

15

ButtonCommon centralizes shared position, dimensions and label font

  • an example of deriving primarily for a constructor

SayButton stores its message pointer and implements OnPress with output

  • the example uses permanent string literals, so pointer retention is safe

ExitButton's override performs its exit action

  • the source calls exit(0); hiding the window can instead permit normal event-loop return as discussed earlier

main now constructs the window and three already-configured buttons

  • no separate per-button callback/context setup remains there
  • object fields and virtual methods replace repeated void* conversions
  • the adapter's internal bridge cast remains localized
Tests & experiments (3 files) - 10.11.10: FLTK and OOP
Section test10 (10-11)In catalog
MakefileMake / 13 lines
FLTK_DIR = $(HOME)/.app/fltk-1.3.11

CPPFLAGS = -I$(FLTK_DIR)
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDFLAGS = -L$(FLTK_DIR)/lib
LDLIBS = $(shell $(FLTK_DIR)/fltk-config --ldflags)

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
buttons.cppC++ / 60 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>

class OOFLButton : public Fl_Button {
public:
    OOFLButton(int x, int y, int w, int h, const char *lb = 0)
        : Fl_Button(x, y, w, h, lb)
        { callback(CallbackFunction, 0); }
    virtual ~OOFLButton() {}
    virtual void OnPress() {}
private:
    static void CallbackFunction(Fl_Widget *w, void *user)
        { static_cast<OOFLButton*>(w)->OnPress(); }
};


enum {
    spacing = 5,
    button_w = 200,
    button_h = 40,
    font_size = 20,
    num_buttons = 3
};

class ButtonCommon : public OOFLButton {
public:
    ButtonCommon(int y, const char *lb)
        : OOFLButton(spacing, y, button_w, button_h, lb)
        { labelsize(font_size); }
};

class SayButton : public ButtonCommon {
    const char *msg;
public:
    SayButton(int y, const char *lb, const char *amsg)
        : ButtonCommon(y, lb), msg(amsg) {}
    virtual void OnPress() { printf("%s\n", msg); }
};

class ExitButton : public ButtonCommon {
public:
    ExitButton(int y): ButtonCommon(y, "Quit") {}
    virtual void OnPress() { exit(0); }
};

int main()
{
    int win_w = button_w + 2 * spacing;
    int win_h = num_buttons * (spacing + button_h) + spacing;
    Fl_Window win(win_w, win_h, "buttons demo");

    new SayButton(spacing, "Say hello", "Hello, world!");
    new SayButton(2 * spacing + button_h, "Say goodbye",
                  "Goodbye, world!");
    new ExitButton(3 * spacing + 2 * button_h);
    win.end();
    win.show();
    return Fl::run();
}
buttons1.cppC++ / 70 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>

class OOFLButton : public Fl_Button {
public:
    OOFLButton(int x, int y, int w, int h, const char *lb = 0)
        : Fl_Button(x, y, w, h, lb)
        { callback(CallbackFunction, 0); }
    virtual ~OOFLButton() {}
    virtual void OnPress() {}
private:
    static void CallbackFunction(Fl_Widget *w, void *user)
        { static_cast<OOFLButton*>(w)->OnPress(); }
};


enum {
    spacing = 5,
    button_w = 200,
    button_h = 40,
    font_size = 20,
    num_buttons = 3
};

class ButtonCommon : public OOFLButton {
public:
    ButtonCommon(int y, const char *lb)
        : OOFLButton(spacing, y, button_w, button_h, lb)
        { labelsize(font_size); }
};

class SayButton : public ButtonCommon {
    const char *msg;
public:
    SayButton(int y, const char *lb, const char *amsg)
        : ButtonCommon(y, lb), msg(amsg) {}
    virtual void OnPress() { printf("%s\n", msg); }
};

class ExitButton : public ButtonCommon {
public:
    ExitButton(int y): ButtonCommon(y, "Quit") {}
    virtual void OnPress()
    {
        Fl_Widget *w = this;
        Fl_Widget *p;
        do {
            p = w->parent();
            if (p)
                w = p;
        } while(p);
        w->hide();
    }
};

int main()
{
    int win_w = button_w + 2 * spacing;
    int win_h = num_buttons * (spacing + button_h) + spacing;
    Fl_Window win(win_w, win_h, "buttons demo");

    new SayButton(spacing, "Say hello", "Hello, world!");
    new SayButton(2 * spacing + button_h, "Say goodbye",
                  "Goodbye, world!");
    new ExitButton(3 * spacing + 2 * button_h);
    win.end();
    win.show();
    return Fl::run();
}

10.11.11 (*) Using an application-owned event loop

An application can integrate GUI processing with other event sources through toolkit callbacks or a carefully managed external loop. The book's X11-specific recipe also needs queued events, timers, and redraw work handled beyond socket readiness.

With the descriptor handlers from 10.10, FLTK becomes one more event source in an application-owned loop (X11 only, and version-dependent):

#include <FL/Fl.H>
#include <FL/x.H>

class FltkHandler : public FdHandler {
public:
    FltkHandler(int fd) : FdHandler(fd, false) {}   // Xlib owns the socket
    virtual void Handle(bool r, bool w) {
        Fl::wait(0.0);          // dispatch whatever is ready, then return
        Fl::flush();
    }
};

bool attach_fltk(EventSelector *selector)
{
    Display *display = XOpenDisplay(0);
    if (!display)
        return false;
    fl_open_display(display);
    selector->Add(new FltkHandler(ConnectionNumber(display)));
    return true;
}
Detailed notes - 10.11.11: (*) Using an application-owned event loop

1

GUI toolkits commonly offer their own main event loop

  • the author prefers the application to control this architectural choice

2

other event sources may need equal attention

  • e.g. network clients serving many outstanding connections
  • blocking network work inside GUI callbacks would stop responsiveness

3

one route is to register other events with FLTK

  • add_fd/remove_fd for descriptor readiness
  • add_timeout/remove_timeout/repeat_timeout for scheduled callbacks

4

the source then explores an external loop instead

  • its particular integration is specific to the FLTK/X11 environment examined in the book

5

idea: open the X connection under application control

  • share that Display with FLTK
  • monitor its connection descriptor alongside other event sources
  • give FLTK opportunities to dispatch its events

6

the book's recipe:

  • XOpenDisplay(0) obtains a Display*; test for failure
  • ConnectionNumber(display) obtains the connection descriptor
  • fl_open_display(display) supplies that connection to FLTK
  • when it is readable, call Fl::wait(0.0) without blocking
  • the previous chapter's descriptor-handler design can host that action

a complete integration must also account for already queued events, timers,

pending redraws and library work that does not create fresh socket readiness

7

the author warns that this low-level recipe may change across versions

  • Fl::flush requests pending drawing work to be sent/displayed
  • event-loop pumping and flushing need to match the library's contract
  • treat the example as an architectural illustration, not a portable promise that one socket callback handles every FLTK event source
Tests & experiments (5 files) - 10.11.11: (*) Using an application-owned event loop
Section test11 (10-11)In catalog
MakefileMake / 13 lines
FLTK_DIR = $(HOME)/.app/fltk-1.3.11

CPPFLAGS = -I$(FLTK_DIR)
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDFLAGS = -L$(FLTK_DIR)/lib
LDLIBS = $(shell $(FLTK_DIR)/fltk-config --ldflags)

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
fltk_fd1.cppC++ / 90 lines
#include <cstdio>
#include <unistd.h>

#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Button.H>

struct App {
    Fl_Window *window;
    Fl_Box *timer;
    Fl_Box *input;
    int seconds;
};

// Called when standard input becomes readable.
static void input_cb(int fd, void *data)
{
    App *a = static_cast<App*>(data);

    char buffer[256];
    ssize_t n = read(fd, buffer, sizeof(buffer) - 1);

    if (n > 0) {
        buffer[n] = '\0';
        a->input->copy_label(buffer);
    } else if (n == 0) {
        // EOF: standard input has been closed.
        Fl::remove_fd(fd);
        a->input->copy_label("Input closed");
    }
}

// Called after one second.
static void timer_cb(void *data)
{
    App *a = static_cast<App*>(data);

    ++a->seconds;

    char text[80];
    std::snprintf(text, sizeof(text),
                  "Elapsed: %d seconds", a->seconds);

    a->timer->copy_label(text);

    // Schedule the next invocation.
    Fl::repeat_timeout(1.0, timer_cb, data);
}

// Called when the user closes the window.
static void close_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);

    Fl::remove_fd(STDIN_FILENO);
    Fl::remove_timeout(timer_cb, data);

    a->window->hide();
}

int main()
{
    Fl_Window window(450, 200, "FLTK event loop");

    Fl_Box timer(20, 20, 410, 50, "Elapsed: 0 seconds");
    timer.box(FL_DOWN_BOX);

    Fl_Box input(20, 80, 410, 50, "Type something in the terminal");
    input.box(FL_DOWN_BOX);

    Fl_Button quit(175, 145, 100, 35, "Quit");

    window.end();

    App app = { &window, &timer, &input, 0 };

    window.callback(close_cb, &app);
    quit.callback(close_cb, &app);

    // Watch standard input (file descriptor 0).
    Fl::add_fd(STDIN_FILENO, FL_READ, input_cb, &app);

    // Schedule the first timer invocation.
    Fl::add_timeout(1.0, timer_cb, &app);

    window.show();

    return Fl::run();
}
fltk_fd2.cppC++ / 93 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Output.H>
#include <FL/Fl_Button.H>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

struct State {
    Fl_Box *counter;
    Fl_Output *input;
    unsigned int ticks;
    bool running;
    bool input_open;
};

void on_timeout(void *data)
{
    State *state = static_cast<State*>(data);
    char text[64];
    snprintf(text, sizeof(text), "Timer ticks: %u", ++state->ticks);
    state->counter->copy_label(text);

    // A timeout fires once. Schedule the next tick from this callback.
    Fl::repeat_timeout(1.0, on_timeout, state);
}

void on_input(int fd, void *data)
{
    State *state = static_cast<State*>(data);
    char text[256];

    // Read only available bytes; getline() could wait for a whole line.
    int count = read(fd, text, sizeof(text) - 1);
    if (count > 0) {
        while (count > 0 && (text[count - 1] == '\n' || text[count - 1] == '\r'))
            --count;
        text[count] = '\0';
        state->input->value(text);
    } else if (count == 0 ||
               (errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK)) {
        // EOF stays readable: remove the handler to avoid a busy loop.
        state->input->value(count == 0 ? "End of input" : strerror(errno));
        Fl::remove_fd(fd);
        state->input_open = false;
    }
}

void on_pause(Fl_Widget *button, void *data)
{
    State *state = static_cast<State*>(data);
    if (state->running) {
        Fl::remove_fd(STDIN_FILENO);
        Fl::remove_timeout(on_timeout, state);
        button->label("Resume");
    } else {
        if (state->input_open)
            Fl::add_fd(STDIN_FILENO, FL_READ, on_input, state);
        Fl::add_timeout(1.0, on_timeout, state);
        button->label("Pause");
    }
    state->running = !state->running;
}

int main()
{
    Fl_Window window(480, 210, "FLTK: file descriptor and timer");
    Fl_Box instructions(20, 15, 440, 30,
                        "Type in the launching terminal, then press Enter.");
    instructions.labelsize(14);
    Fl_Box counter(20, 60, 440, 30, "Timer ticks: 0");
    counter.labelsize(18);
    Fl_Output input(80, 105, 380, 30, "Input:");
    Fl_Button pause(180, 160, 120, 30, "Pause");
    window.end();

    State state = { &counter, &input, 0, true, true };
    pause.callback(on_pause, &state);

    // FLTK watches stdin and calls on_input when it is readable.
    Fl::add_fd(STDIN_FILENO, FL_READ, on_input, &state);
    // Start the first tick; on_timeout schedules subsequent ticks.
    Fl::add_timeout(1.0, on_timeout, &state);

    window.show();
    int result = Fl::run(); // FLTK owns the main loop; no polling or threads.

    Fl::remove_fd(STDIN_FILENO);
    Fl::remove_timeout(on_timeout, &state);
    return result;
}
fltk_fd3-own-loop.cppC++ / 63 lines
#include <cstdio>
#include <cerrno>
#include <sys/select.h>

#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
#include <FL/x.H>

// Called once per second.
void tick(void *data)
{
    Fl_Box *box = static_cast<Fl_Box*>(data);
    static int seconds = 0;

    char text[64];
    std::sprintf(text, "Seconds: %d", ++seconds);
    box->copy_label(text);

    Fl::repeat_timeout(1.0, tick, data);
}

int main()
{
    // 1. Open the X11 connection ourselves.
    Display *display = XOpenDisplay(0);
    if (!display) {
        std::fprintf(stderr, "Cannot open X display\n");
        return 1;
    }

    // 2. Obtain the X server's socket descriptor.
    int fd = ConnectionNumber(display);

    // 3. Give the existing connection to FLTK.
    fl_open_display(display);

    Fl_Window window(300, 150, "My event loop");
    Fl_Box box(20, 40, 260, 60, "Seconds: 0");
    window.end();
    window.show();

    Fl::add_timeout(1.0, tick, &box);

    // 4. Our own main event loop.
    while (window.shown()) {
        fd_set fds;
        FD_ZERO(&fds);
        FD_SET(fd, &fds);

        timeval timeout = { 0, 50000 }; // 50 ms

        int result = select(fd + 1, &fds, 0, 0, &timeout);
        if (result < 0 && errno != EINTR)
            break;

        // 5. Let FLTK handle pending events and timers.
        Fl::wait(0.0);
    }

    Fl::remove_timeout(tick, &box);
    return 0;
}
fltk_fd4-won-loop.cppC++ / 119 lines
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/select.h>

#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
#include <FL/x.H>

struct App {
    Fl_Window *window;
    Fl_Box *message;
    Fl_Box *timer;
    int seconds;
    bool input_open;
};

static int connect_x11()
{
    Display *display = XOpenDisplay(0);
    if (!display)
        return -1;

    int fd = ConnectionNumber(display);
    fl_open_display(display);
    return fd;
}

static void timer_cb(void *data)
{
    App *a = static_cast<App*>(data);

    char text[64];
    sprintf(text, "Elapsed: %d seconds", ++a->seconds);
    a->timer->copy_label(text);

    Fl::repeat_timeout(1.0, timer_cb, data);
}

static void read_terminal(App *a)
{
    char text[256];
    int n = read(STDIN_FILENO, text, sizeof(text) - 1);

    if (n == 0) {
        a->input_open = false;
        a->message->copy_label("Input closed");
        return;
    }

    if (n < 0)
        return;

    text[n] = '\0';

    if (text[n - 1] == '\n')
        text[n - 1] = '\0';

    if (strcmp(text, "quit") == 0)
        a->window->hide();
    else
        a->message->copy_label(text);
}

static void event_loop(App *a, int xfd)
{
    Fl::add_timeout(1.0, timer_cb, a);

    while (a->window->shown()) {
        fd_set fds;
        FD_ZERO(&fds);
        FD_SET(xfd, &fds);

        if (a->input_open)
            FD_SET(STDIN_FILENO, &fds);

        timeval timeout = { 0, 50000 };
        int maxfd = xfd > STDIN_FILENO ? xfd : STDIN_FILENO;

        int result = select(maxfd + 1, &fds, 0, 0, &timeout);

        if (result < 0) {
            if (errno == EINTR)
                continue;
            perror("select");
            break;
        }

        if (result > 0 && a->input_open && FD_ISSET(STDIN_FILENO, &fds))
            read_terminal(a);

        Fl::wait(0.0);
    }

    Fl::remove_timeout(timer_cb, a);
}

int main()
{
    int xfd = connect_x11();
    if (xfd < 0) {
        fprintf(stderr, "Cannot connect to X11\n");
        return 1;
    }

    Fl_Window window(400, 180, "Terminal input");
    Fl_Box message(20, 20, 360, 60, "Type in the terminal");
    Fl_Box timer(20, 100, 360, 50, "Elapsed: 0 seconds");
    window.end();

    App app = { &window, &message, &timer, 0, true };

    window.show();
    event_loop(&app, xfd);

    return 0;
}

C++: further study

The chapter intentionally omits many C++ facilities, including the standard library and later language developments. Its suggested practice builds understanding of the covered mechanisms, while further study should match the requirements of actual projects.

Detailed notes - 10-closing: C++: further study

1

the chapter deliberately covers a limited historical subset

  • omits the standard library, multiple inheritance, namespaces, member pointers and other features

2

professional work may require the standard library and newer C++

  • the author's opposition to them is his preference
  • the chapter's employment claims reflect its publication period

3

if preparing for a specific role, learn its required missing facilities

  • practise them in code; reading alone does not establish proficiency
  • the source's advice about which standards to ignore is dated opinion

4

the author's alternative learning sequence is to build one or two useful

programs with the studied mechanisms before moving to other facilities

  • intended to develop understanding of how abstractions work
  • his blanket rejection of later C++ is not a language correctness rule

5

the author suggests Jeff Alger's C++ for Real Programmers as further reading

  • presented as a way to deepen understanding of the classical mechanisms
  • this is the source's recommendation, not an updated reading survey
Tests & experiments (2 files) - 10-closing: C++: further study
Section test12 (10)In catalog
MakefileMake / 13 lines
FLTK_DIR = $(HOME)/.app/fltk-1.3.11

CPPFLAGS = -I$(FLTK_DIR)
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDFLAGS = -L$(FLTK_DIR)/lib
LDLIBS = $(shell $(FLTK_DIR)/fltk-config --ldflags)

PROGS = $(basename $(wildcard *.cpp))

all: $(PROGS)

clean:
    rm -f *.o $(PROGS)
player.cppC++ / 59 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Box.H>

class Player {
    Fl_Box *status;

public:
    Player(Fl_Box *a_status) : status(a_status) {}

    void play()  { status->label("Playing"); }
    void pause() { status->label("Paused"); }
    void stop()  { status->label("Stopped"); }
};

// Pointer to any Player method returning void
// and taking no arguments.
typedef void (Player::*Action)();

struct Command {
    Player *player;
    Action action;
};

// One callback handles all three buttons.
void button_cb(Fl_Widget *, void *data)
{
    Command *cmd = static_cast<Command*>(data);
    (cmd->player->*(cmd->action))();
}

int main()
{
    Fl_Window window(340, 140, "Music Player");

    Fl_Box status(20, 15, 300, 40, "Stopped");

    Fl_Button play(20, 80, 90, 35, "Play");
    Fl_Button pause(125, 80, 90, 35, "Pause");
    Fl_Button stop(230, 80, 90, 35, "Stop");

    window.end();

    Player player(&status);

    Command commands[] = {
        { &player, &Player::play },
        { &player, &Player::pause },
        { &player, &Player::stop }
    };

    play.callback(button_cb, &commands[0]);
    pause.callback(button_cb, &commands[1]);
    stop.callback(button_cb, &commands[2]);

    window.show();
    return Fl::run();
}

Previous: Programming Paradigms Reading map Next: Functional and Logic Programming

Comments

Leave a comment Sign in All comments