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
C++: introduced by Bjarne Stroustrup as an extension of C
OOP and abstract data types: two related but distinct paradigms
C++ uses the same mechanisms for several purposes:
using these mechanisms does not by itself establish an OOP design
ADTs are useful independently of OOP
OOP also requires thinking in terms of objects and their messages
language features provide technical support for paradigms
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*
#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
C++ extends C, but is not a strict superset
correction to the example:
C++ requires declarations before function calls
C's permission to convert void* does not extend to all pointer types
the book uses 0 as a null pointer constant
several C++ additions are useful before introducing classes or ADTs
bool: false and true
ordinary character literals: type char in C++, type int in C
declarations can occur among statements and in a for initializer
// introduces a comment extending to the end of the line
these comparisons describe older C; later C also has these facilities
#include <stdio.h>
int main()
{
bool b = false;
int b2 = b;
printf("%d\n", b2);
return 0;
}
#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;
}
#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;
}
#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;
}
#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;
}
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.
__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
author's concern: teaching library use before language mechanisms
the author associates this teaching approach with Stroustrup's third edition, which uses container templates before explaining templates
the chapter grew from a separately published C++ booklet
the author considers alternatives inadequate for his low-level needs
two properties especially important to the author:
these motivate his interest in kernels and microcontroller firmware
the author argues for understanding what abstractions cost and require
the book deliberately omits STL and newer language additions
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
__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;
}
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.
start from familiar C structures and functions
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);
#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
member functions and classes support object-oriented programming
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
method: a function called for a particular object
calling a method corresponds to sending an object a message
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
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
};
a non-static member call supplies the object implicitly
this: pointer to the object receiving the call
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
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); }
};
#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
hiding implementation requires restricting direct access to members
public: accessible to clients
private: accessible to the class's own member functions
problem: a client can forget set or call magnitude first
constructor: instructions for initializing each new object
constructor name matches the class or structure name
str_complex(double a_re, double a_im): requires both components
constructors may be supplied implicitly in cases the language permits
str_complex z(2.7, 3.8): construction with the two arguments
a temporary can also receive the message immediately:
declaring a parameterized constructor suppresses an implicit no-argument
constructor
parenthesized initialization also works for built-in types
initialization and assignment are different operations
constructors initialize new objects
access control belongs to the type, not to each individual instance
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
#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;
}
#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;
}
#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;
}
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:
#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
access control is useful because it limits dependencies on representation
complex numbers: repeated magnitude calculation can become expensive
public re and im tie every client to Cartesian storage
private fields plus GetRe, GetIm, Magnitude and Argument:
Cartesian storage:
polar storage:
implementations can be switched and measured without rewriting clients
another representation: store both coordinate pairs
invariant: both pairs must describe the same complex number
access control prevents accidental misuse by cooperating programmers
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
#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;
}
#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;
}
#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;
}
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
class: a structure whose members are private by default
Complex stores re and im privately
class and struct have the same underlying capabilities
usual convention in this book:
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
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
#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;
}
destructor: controls cleanup when an object's lifetime ends
an object may own resources that clients cannot see
~A(): destructor for class A
File example:
local objects are destroyed on normal scope exit, including return
a production owner must also handle repeated OpenRO calls and copying
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
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.
#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
access control and lifetime operations support both OOP and ADTs
this section adds user-defined operations and lifetime control
goal: use a complicated abstraction as naturally as a built-in value
author's assessment: effective ADTs can greatly reduce work relative to C
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
overloading: a language mechanism used by several later features
functions can share a name when their parameter lists distinguish them
function signature includes its name and relevant parameter types
adding an overload can make an existing call ambiguous
overloading is static polymorphism
the author prefers distinct names for ordinary functions
constructors need overloading because their names match their class
operator functions also share prescribed names
author's recommendation: avoid ordinary-function overloading
mixed-language projects expose an additional issue
a linker resolves labels and addresses, not high-level function overloads
name mangling: encoding C++ naming information into linker symbols
a mangled name can encode the function and its parameter types
binary compatibility depends on the compiler's ABI
C and C++ declarations can look alike but produce different symbols
extern "C": gives declarations C language linkage
two ways to expose a C header to C++:
shared header:
nested scopes also require distinguishable linker names
author's language-design criticism:
these are proposed alternatives, not facilities offered by C++
the author treats these costs as lessons for future language design
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
double foo(double a, int b)
{
return a * b;
}
int main()
{
foo(3, 1);
return 0;
}
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
%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
#ifndef MODULE_H
#define MODULE_H
#ifdef __cplusplus
extern "C" {
#endif
double foo(double a, int b);
#ifdef __cplusplus
}
#endif
#endif
#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;
}
#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;
}
#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;
}
#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.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.asm ;;
%include "kernel.inc"
global quit
section .text
quit: kernel 1, 0
;; 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
#include <cstdio>
#include "module.h"
int main()
{
double res = foo(2, 3);
printf("%g\n", res);
return 0;
}
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
a useful Complex type needs arithmetic as well as component queries
operator+: a member function implementing addition for the type
complex arithmetic:
(c1+c2).Magnitude(): call a method on the sum
many operator symbols can be overloaded, but not every language operation
operator selection by operand type is static polymorphism
terminology matters: a statement is a structural unit of program text
an operator belongs inside an expression
the English term operator follows mathematical usage
Russian terminology uses a misleadingly similar word for statement
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
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
Complex's two-argument constructor cannot initialize Complex sum
add Complex() alongside Complex(double, double)
default constructor: callable without arguments
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
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
implicit conversions allow a value where another type is expected
converting A to B means constructing a B from the supplied A
Complex(double a): store a as the real part and zero as the imaginary part
explicit can disallow this implicit use of a constructor
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
references are central to the following ADT mechanisms
a reference aliases an object
int &r = i: r and i designate the same integer
a reference definition needs an initializer
reference parameters let a function work on the caller's objects
C max_min example:
C++ max_min uses float& for the two result parameters
preconditions: nonempty valid array and suitable distinct result variables
a function can return a reference to a located object
CFLAGS = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.c *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
#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;
}
#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;
}
#include <cstdio>
int main()
{
int i = 0;
int *p = &i;
int &r = i;
i++;
(*p)++;
r++;
printf("%d\n", r);
return 0;
}
#include <cstdio>
int main()
{
// int &r;
// printf("%d\n", r);
return 0;
}
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); }
};
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:
a reference is never reseated; const qualifies the referred-to access
const-reference parameters avoid copying while preventing direct changes
through that parameter
CFLAGS = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.c *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
#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;
}
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 */
the author considers references an especially important C++ innovation
lvalue: an expression that identifies an object or other identity
author's explanatory model: treat such expressions as references
in this model, value use reads the referenced object
const references illustrate access that identifies an object but cannot modify it
(x < y ? x : y) = z selects an integer object and assigns to it
CFLAGS = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.c *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
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;
}
#include <cstdio>
int main()
{
int x = 1, y = 2, z = 3;
(x < y ? x : y) = z;
return 0;
}
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
};
const A* permits access to A without modification through that pointer
the same issue arises for const references and const objects
put const after a member function's parameter list
mark query operations const when their meaning permits it
CFLAGS = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.c *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
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) |
C allocation functions supply and release storage
malloc and free do not by themselves perform those object operations
new T: obtain storage and create a T
delete p: destroy that object and release its allocated storage array forms: new T[n] and delete[] p
match allocation and release forms exactly
mismatching them has undefined behavior, regardless of apparent success
an implementation seeming to tolerate a mismatch proves nothing
CFLAGS = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.c *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
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
};
Cls1 owns an array through an int* member
passing a Cls1 by value creates another object
unplanned sharing breaks ownership
copy constructor: define how a new object is made from an existing one
a copy constructor cannot take its own type by value
CFLAGS = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.c *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
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;
}
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
an explicitly written unnamed object is convenient for a single use
implicit conversions can also create temporary objects
a + b + c groups as (a + b) + c
the book calls explicitly written temporaries anonymous objects
binding a suitable local const reference can extend a temporary's lifetime
an ordinary non-const lvalue reference cannot bind to a temporary
use const references when modification through a parameter is unnecessary
CFLAGS = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.c *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
#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;
}
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
a function declaration can supply defaults for omitted trailing arguments
default expressions have their own lookup and evaluation rules
the author questions calling default arguments static polymorphism
special constructor categories depend on how they can be called
Complex(double re = 0, double im = 0) serves three purposes
CFLAGS = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.c *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
#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;
}
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
};
method bodies can be as large as ordinary function bodies
long bodies inside a class obscure its interface
classes shared by modules normally have definitions in headers
keep declarations in the class and place longer definitions separately
ClassName::MethodName identifies an out-of-class member definition
class scope separates its member names from unrelated names
::func selects func in global scope
:: qualifies names rather than computing a scope from an expression
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)
#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);
}
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;
};
#include <cstdio>
void func()
{
printf("hello there\n");
}
int main()
{
::func();
return 0;
}
#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;
}
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.
very short accessors might appear expensive if each required a full call
inlining substitutes the function's operations at a call site
methods defined inside the class are implicitly inline in the book's model
inline may also be written on an ordinary or out-of-class function
inline does not force machine-code substitution
an inline function used across translation units needs its definition available where required, conventionally in a header
a function may have both inlined call sites and callable emitted code
short methods can therefore expose a clean interface without necessarily
adding call overhead
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)
#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);
}
#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);
}
#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;
}
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; }
};
members already need to be constructed before the constructor body runs
member initializer list follows the constructor header after a colon
members initialize in declaration order, not initializer-list order
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)
#include <cstdio>
#include "complex.hpp"
void Complex::Print() const
{
printf("%g%+gi\n", re, im);
}
#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);
}
#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;
}
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)
a member Complex::operator+ can accept t + 0.5 through conversion
a non-member operator+(const Complex&, const Complex&) treats both operands as parameters
binary member form: a.operator+(b)
non-member form: operator+(a, b)
non-member operations can extend a type's usable notation
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)
#include <cstdio>
#include "complex.hpp"
void Complex::Print() const
{
printf("%g%+gi\n", re, im);
}
#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
#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;
}
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
};
friend grants selected external code access to private implementation
friendship expands the code responsible for preserving invariants
a non-member operator may need representation access
declare the operator's prototype with friend inside Complex
ordinary functions and whole classes can also be friends
a non-member operator function need not be a friend
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)
#include <cstdio>
#include "complex.hpp"
void Complex::Print() const
{
printf("%g%+gi\n", re, im);
}
#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
#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;
}
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
some overloadable operators have additional declaration rules
assignment is an expression operation in C and C++
them
an assignment operation normally returns the assigned-to object
compound operations are independent overloads
assignment may accept a different source type
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)
#include <cstdio>
#include "complex.hpp"
void Complex::Print() const
{
printf("%g%+gi\n", re, im);
}
#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
#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;
}
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()
ordinary record-like classes remain usable without handwritten constructors
implicit copying initializes members from corresponding source members
this section describes the book's older subset of special-member rules
a default constructor is implicitly declared if no constructor was declared
default construction initializes class-type members through their defaults
an implicit destructor destroys members as required by their types
implicit copy assignment assigns corresponding members
omitting a copy constructor does not prohibit copying old-subset technique: declare copying and assignment private
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)
#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;
}
class A {
public:
A() {}
private:
A(const A &ref) {}
void operator=(const A &ref) {}
};
int main()
{
A a1, a2;
// a2 = a1;
}
#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;
}
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
built-in a[b] corresponds to *(a+b)
IntArray example: storage grows as an index requires
private p and size hold storage and current capacity
operator[] returns int& so an element can be read or modified
Resize:
correctness requirements omitted by the short example:
indexing need not use integers or physically contiguous storage
the modifying index operation cannot serve a const IntArray
members may be overloaded by trailing const
the read-only overload should not resize
int operator[](unsigned int idx) const supplies that behavior
const overloading is available for other member functions too
the author rejects general array-like container classes for his style
CFLAGS = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.c *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
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;
}
#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;
}
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--
prefix and postfix ++/-- need separate overloads
prefix member form has no explicit parameters
postfix form adds a dummy int parameter
the example's calls select first, third, second, fourth in that order
usual prefix behavior: update and return the updated object by reference
usual postfix behavior:
never return a reference to the local saved copy
CFLAGS = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.c *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
#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;
}
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
operator-> supports objects that behave like pointers
in p->a, p is an expression but a is a fixed member name
operator-> is a member with no explicit parameters
Pointer_s1 owns an optional s1 pointer
local owner: acquired objects are cleaned up on normal function exit
requirements for a correct owner:
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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.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;
}
#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;
}
#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;
}
#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;
}
#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;
}
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;
}
#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;
}
#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;
}
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
operator() lets an object use function-call notation
Fun overloads calls with zero, one and two integer arguments
a callable object is often called a function object or functor
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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);
}
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
constructors define conversion into their class
conversion members provide conversion out of the source class
operator int() const defines conversion from the class to int
multiple implicit conversion paths can produce ambiguity
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
class A {
int i;
public:
operator int() const { return i; }
};
int main()
{
A a;
int x;
x = a;
return 0;
}
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
#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
sparse array: most positions contain a common value, usually zero
SparseArrayInt exposes integer indexing
const indexing is straightforward
modifiable indexing has two different uses: read and write
creating a zero entry on every access would make assignment possible
remembering the last accessed node could permit later cleanup
operator[] cannot directly ask whether its result will be read or assigned
return a small intermediate proxy object instead
proxy conversion to int implements reading
proxy assignment implements writing
other modifying syntax needs corresponding proxy overloads
Interm helpers:
SparseArrayInt disables copying and assignment in this example
proxy implementation:
Provide: search first, otherwise prepend a new node
Remove: use a pointer to the link that leads to the selected node
additional proxy case requiring an explicit operation:
// 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;
}
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
#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;
}
#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;
}
#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;
}
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
static members belong to the class independently of individual objects
a static data member has static storage duration and class scope
one shared data member exists for the class
static int the_static_field inside the class is a declaration
this resembles an extern declaration of a global variable
define it once outside the class: int A::the_static_field = 0
public static members can be named through an object or as A::member
the author recommends static data mainly for immutable shared information
static method: a class-scoped function without an implicit receiver
call through Cls::TheStaticMethod(...) or through an object
static methods retain the class's private access rights
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
#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;
}
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.
the author distinguishes the useful exception idea from its implementation
some projects deliberately disable exceptions
exceptions can reduce the work needed for complete error propagation
exception handling is not unique to C++
the author proposes identifying exceptions by stable object addresses
understanding exceptions remains useful for other languages and designs
the author recommends reserving throws for exceptional failures
understand the mechanism's consequences before adopting it
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
#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;
}
.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
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;
}
operations can fail because external preconditions do not hold
detecting failure is easier than deciding the appropriate response
error reporting depends on the surrounding application
the same failure can be fatal, recoverable or expected
policy belongs at the level that understands the whole operation
return-code propagation requires work at every intermediate call
the effort tempts programmers to omit checks
exception mechanisms provide language support for this propagation task
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);
}
}
a return type may have no spare value for reporting failure
exceptions add a different completion route
exceptions are independent of the OOP paradigm
a throw searches active calling contexts for a matching handler
main can provide a useful outer handling boundary
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
throw expression creates an exception
line_count_in_file example:
this counts newline characters, not an unterminated final text line
throw 27 would instead create an int exception
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
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);
}
handle a failure where the required recovery policy is known
a handler surrounds an interval of execution
try { ... } is followed by one or more catch clauses
file-counting main:
on a throw, neither the worker's remainder nor try's remainder executes
an exception can originate arbitrarily far down the call chain
the thrown C++ string literal produces a const char* exception
multiple handlers are considered in written order
handler matching has different conversion rules from function calls
a catch clause handles throws from its associated try execution
without a matching handler, propagation continues outward
throw; rethrows the currently handled exception
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;
}
catch(...) accepts an exception regardless of its type
cleanup-and-rethrow example:
without this cleanup, a raw pointer's scope exit would leak its allocation
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
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.
#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
failures often need several pieces of context
unrelated subsystems may throw the same built-in type
dedicated exception classes solve both problems
the exception object must survive the throwing function's scope
FileException stores errno, a copied filename and a copied comment
catch(const FileException &ex) avoids a second handler-parameter copy
ownership details still need completion in production code
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
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
}
stack unwinding destroys fully constructed automatic objects it leaves
if f has a local A and calls g, a throw from g can unwind f
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
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);
}
handler matching does not perform arbitrary numeric conversions
an exception object can be caught by reference
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
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.
methods and hidden state alone do not exhaust the book's view of OOP
inheritance adds related types and substitutable interfaces
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; }
};
domain entities often fall into successively narrower categories
properties of a category apply to its subcategories
choose categories and assumptions that actually fit the modeled domain
related structures need both shared and specialized fields and operations
first examine inherited data, then add inherited methods and behavior
CFLAGS = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.c *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
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
inheritance specializes a more general concept
student derives from person
person: base/parent; student: derived/child
a student can be accessed through its person part
the reverse is not automatic: an arbitrary person need not be a student
the author calls this pointer or reference polymorphism
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
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
inheritance works with both class and struct declarations
public inheritance exposes the base interface as part of the derived type
private inheritance makes that relationship an implementation detail
default inheritance: public for struct, private for class
a derived class does not automatically gain the base's private access
protected members form an interface for derived classes
protected is a published contract for subclasses
inherited ordinary methods retain their base implementation
the inherited method receives a base view of this
public derivation means the specialized object accepts its base's messages
two compatible views:
CXXFLAGS = -g -Wall -O0 -ansi -pedantic -DERRORS
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
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
base construction precedes use by the derived constructor body
destruction reverses the order
the compiler arranges the base destructor after derived cleanup constructor arguments for the base go in the initializer list
CXXFLAGS = -g -Wall -O0 -ansi -pedantic -DERRORS
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
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;
}
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.
a derived object may need a different reaction to a shared message
graphics example: Pixel has coordinates, color, Show, Hide and Move
Move algorithm:
Circle initially derives from Pixel and adds radius
inherited Move would be ideal because its algorithm does not change
that ordinary binding would erase and draw a point for a circle
declare Show and Hide virtual in the base
common implementation: a virtual-function table
derived classes have corresponding tables with appropriate overrides
Move now works through the shared algorithm
provide a virtual destructor for this polymorphic owning interface
virtual dispatch also works for calls outside the class
p->Show() through Pixel* or Circle* selects the appropriate final override
CXXFLAGS = -g -Wall -O0 -ansi -pedantic -DERRORS
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
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
a circle is not a kind of pixel
the shared Move algorithm uses the anchor independently of shape
introduce a general figure base and derive both Pixel and Circle from it
a shape without a particular form has no useful generic drawing body
the base can still implement Move using a required Show/Hide interface
virtual void f() = 0 declares a pure virtual member
= 0 is the fixed declaration syntax
a class with an unimplemented pure virtual obligation is abstract
GraphObject stores anchor/color and declares pure virtual Show and Hide
Pixel and Circle derive independently from GraphObject
CXXFLAGS = -g -Wall -O0 -ansi -pedantic -DERRORS
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
class A {
virtual void f() = 0;
};
class B : public A {
virtual void f() {}
};
int main()
{
B b;
return 0;
}
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
construction proceeds through base and derived stages
virtual calls on the object under construction/destruction use the current
class's stage, not a more-derived override
do not rely on a descendant to finish work called virtually by a base constructor or destructor
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
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);
}
};
a derived class can add only a convenient construction procedure
PolygonalChain stores relative vertex offsets in a private linked list
as an owning class, copying needs either a real deep copy or prohibition
axis-aligned square of side a is a closed five-vertex chain
Square's constructor initializes PolygonalChain, then adds those vertices
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
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
polymorphic deletion needs the destruction behavior of the actual object
GraphObject* can hold the result of new Square(...)
without a virtual base destructor, this base-pointer deletion has undefined
behavior; it is not merely a guaranteed call to the wrong destructor
the author recommends virtual destructors on polymorphic base classes
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
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;
#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)
a scene may contain an unknown mixture of concrete graphical objects
store an array of GraphObject* after determining scene_length
cleanup:
behavior selected from the actual runtime type is dynamic polymorphism
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
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
private destruction restricts access to members and friends protected destruction also permits the relevant derived-class contexts
ordinary outside automatic objects need an accessible destructor
delete this requires a compatible dynamic allocation and careful ownership
private destruction also prevents ordinary derived
construction/destruction
unless friendship grants the needed access
applying the access policy throughout a hierarchy can enforce controlled
destruction for ordinary clients
this is a specialized lifetime-design tool
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
class A {
~A() {}
public:
void Disappear() { delete this; }
};
int main()
{
A *p = new A;
p->Disappear();
return 0;
}
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
a declaration named f in a derived scope can hide base declarations named f
a derived f(const char*) also hides a base f(int, int)
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
#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;
}
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 */
}
};
explicit class qualification suppresses virtual dispatch for that call
example: b.g() and b.f() print second
useful when an override extends the base operation
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
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
C-style casts can conceal several different kinds of conversion
C++ named casts make the intended conversion category visible
const_cast changes appropriate const/volatile qualification
static_cast can perform a permitted base-to-derived pointer/reference cast
correction: static_cast also supports many ordinary conversions
reinterpret_cast expresses specified low-level reinterpretations
dynamic_cast can check a polymorphic downcast at runtime
the runtime check uses type information associated with polymorphic objects
the author discourages routine repeated dynamic_cast use
failed dynamic_cast to a reference throws std::bad_cast
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
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;
}
#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;
}
#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;
}
#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;
}
#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;
}
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;
}
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.
inheritance supplies another relationship used by exception handlers
catch(const A&) accepts A and a suitably publicly derived B
Error can be the root of a failure classification
more specific subclasses allow more specific handling
order catches from specific to general when both are present
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
#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;
}
#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;
}
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.
duplicating nearly identical code creates repeated maintenance work
ordinary functions remove duplication when only values differ
varying types are harder to express with an ordinary function
template: a parameterized definition used to produce functions or classes
templates support parametric polymorphism
templates also support metaprogramming
// 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
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
#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;
}
#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;
}
#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;
}
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>
bubble-sort example:
integer and double versions otherwise have the same algorithm
template<class T> makes those types parameters of sort
sort<int> and sort<double> request concrete function specializations
instantiation produces the required function from the template
template argument deduction can infer T from the array argument
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
#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;
}
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;
}
#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
generalize SparseArrayInt instead of copying it for every element type
a generic element type need not have a usable numeric zero
the possible operations on an unknown T are not limited to integer operators
accept generic values through const references where appropriate
SparseArray<T> stores Item nodes with T values, plus first and defval
correction to the listing:
the full remaining example implementation is in the accompanying archive
an unknown element type makes a complete proxy interface difficult
class-template member bodies are generally instantiated when required
arbitrary fields and methods cannot all be forwarded by this proxy
const indexing returning T by value has another trap
changing a parameter from mutable reference to const reference can expose
that difference without producing a diagnostic
for a reference-like read interface, return const T& from const indexing
for pointer-like element types, forwarding operator-> can be useful
this template still imposes concrete requirements on T
document a template's requirements
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
#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
#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;
}
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)
#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;
}
#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
#include <stdio.h>
#include "complex.hpp"
#include "sparse.hpp"
int main()
{
SparseArray<Complex> s(Complex(0, 0));
return 0;
}
#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;
}
#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
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)
#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;
}
#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
#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;
}
#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
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)
#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;
}
#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
#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;
}
#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
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)
#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;
}
#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
#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;
}
#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
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)
#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;
}
#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
#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;
}
#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
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)
#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;
}
#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
#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;
}
#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
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
#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;
}
#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;
}
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
#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
specialization supplies a different implementation for selected arguments
string-pointer sorting needs lexical comparison, not pointer comparison
explicit specialization begins template<>
class specialization can replace representation as well as operations
partial class specialization leaves some parameters variable
function templates do not permit partial specialization
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
#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;
}
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)
#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;
}
#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
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)
#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;
}
#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
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)
#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;
}
#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
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)
#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;
}
#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
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
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)
#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;
}
#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
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));
}
#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]
templates allow the earlier fold idea to apply to several representations
sequence elements have a consistent element type for each instantiation
a position abstraction must support three actions
linked list: a node pointer supplies position; null means empty
array position also needs a boundary
other possible sequences include file input and generated values Pos interface: Get, Next and Empty
ListPosition<item, elem> stores a node pointer
ArrayPosition<elem> stores pointer and remaining count
generic folds take Pos, Elem and Res template parameters
right fold:
left fold:
sum and product use corresponding combining functions
make_il takes an integer and a tail pointer, allocates a new head
each result node points to the already constructed tail
the same prod function folds the resulting list
printing is a side effect, but the example can still use a fold
other possible folds construct copies, reverse lists, filter or transform
these particular tasks may be simpler as direct loops
#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;
}
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
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) {}
};
#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
templates can accept permitted compile-time values as well as types
MultiMatrix<T, init_val, dim>: an automatically growing N-dimensional array
general indexing returns a reference to a matrix of dim-1 dimensions
store pointers to lower-dimensional matrices
Array<T> supplies the common growing one-dimensional storage
MultiMatrix's general form uses Array<child*> initialized with null
MultiMatrix owns the pointed-to children
const access must not dereference a null child pointer
one-dimensional specialization wraps Array<T> initialized with init_val
for dim == 1, inheritance from Array<T> can remove forwarding methods
matrices
storing child matrices directly would complicate resizing
MultiMatrix<int, -1, 5> demonstration:
non-type template arguments must obey the selected language version's rules
the author again objects to generic containers as a design practice
// 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
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
/* 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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
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.
organize the language mechanisms just studied by the ways of thinking they support
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.
apply the earlier seven-level scale of language/paradigm compatibility
the author argues that C++ strictly imposes few programming styles
C++ strongly encourages imperative programming in practice
the author classifies several paradigms as actively rewarded
ordinary preprocessing is supported, though not preferred in this account
many additional paradigms can be expressed with suitable effort or libraries
the author gives no definite example of an entirely prohibited paradigm
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);
}
distinguish support for objects/messages from support for abstract values
shared mechanisms:
ADT-oriented mechanisms in the author's classification:
these help an abstract type behave naturally beside built-in types
methods make the object/message interpretation explicit
the author's fuller OOP model adds inheritance and virtual dispatch
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
/* 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;
}
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;
}
two common descriptions of polymorphism:
the narrower operation-selection definition omits ordinary base conversion
the author accepts both uses of polymorphism
crucial distinction: when selection occurs
virtual methods provide the chapter's runtime dispatch mechanism
ordinary function/operator overloading is ad hoc static polymorphism
templates provide parametric static polymorphism
base pointer/reference conversion also belongs to the author's static category when using his broader definition of polymorphism
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.
method call and message sending describe the same interaction at different
levels of explanation
view a class as a set of objects satisfying its conditions
inheritance specializes a general case
implementation containment points in the opposite direction
keep these two models separate
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.
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);
};
the book distinguishes C-style entities from class-related names
ordinary functions and variables retain lowercase_with_underscores
one cited convention uses UpperCamelCase for classes
the author instead uses UpperCamelCase for both classes and methods
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; }
};
access labels add a formatting choice
avoid making equally nested members appear at different depths
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)
{
}
initializer lists distinguish constructor formatting from ordinary functions
usual out-of-class style: initializer list starts on its own indented line
keep continuation indentation regular
one compact option: align a leading colon and subsequent leading commas
long horizontal lists can wrap at sensible boundaries
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
};
member bodies may be inside or outside the class definition
keep the class's visible interface compact
header bodies can increase compilation work across modules
short accessor bodies can share a line with their declaration
if compression obscures the code, move the definition outside the class
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;
}
}
#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;
}
objects are a natural option when a task is organized around events
example: select-based TCP chat server
example omits command features such as rename, list users, and leave
one object owns the event-selection loop
lower layer supports descriptor readability and writability
timeout and signal events would need additional abstractions
first layer:
application layer:
FdHandler describes how to react to descriptor events
selector and derived handlers need access to the descriptor
ownership is explicit
interest in readiness can change during operation
Handle(read_ready, write_ready) is pure virtual
EventSelector registration storage:
BreakLoop requests orderly loop termination
EventSelector interface: Add, Remove, BreakLoop, Run
Add:
Remove:
Run:
Implementation conditions:
Upper-layer ownership:
ChatServer is the application-level manager of each ChatSession
server needs a prepared listening descriptor before construction
session's name field also identifies its protocol stage
SendAll(message, except) broadcasts to the session list
named limits in the example:
Session helpers:
Server startup:
Server lifetime:
Accept handling:
RemoveSession:
SendAll:
Session Send:
Session lifetime:
Handle:
ReadAndIgnore:
ReadAndCheck:
CheckLines:
ProcessLine:
Program entry:
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
#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);
}
#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
chat.o: chat.cpp chat.hpp sockets.hpp
main.o: main.cpp chat.hpp sockets.hpp
sockets.o: sockets.cpp sockets.hpp
#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;
}
#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);
}
#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
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
#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;
}
#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;
}
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
#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;
}
#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
chat.o: chat.cpp chat.hpp sockets.hpp
main.o: main.cpp sockets.hpp chat.hpp
sockets.o: sockets.cpp sockets.hpp
#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;
}
#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();
}
}
#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
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.
many users expect a graphical interface
programmers need to provide a GUI when the application requires one
OOP and graphical interfaces have a close historical connection
building directly on a window system requires much detailed work
widget libraries implement this common machinery
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
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
FLTK: Fast Light Toolkit, a C++ widget library
the examples target the FLTK 1.3 series, especially 1.3.5
the source describes installing development headers and libraries
window: a rectangular graphical-system surface
widget: a distinct interface element
FLTK treats a window as one kind of widget
hello example: a window titled hello, containing Hello, World!
include the headers for each class used
Fl_Window derives from Fl_Group
Fl_Box constructor takes x, y, width, height and optional label
labelsize(36) enlarges the displayed text
end() completes construction of the group's contents show() displays the window, establishing graphical-system access as needed
Fl::run() enters the event loop
the source builds with g++ and links -lfltk
the initial window moves but has no configured resizing behavior
the short example embeds dimensions and font size as literal constants
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)
#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();
}
#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();
}
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
}
#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();
}
Fl_Box is normally an output widget
input widgets respond to user actions
users may understand graphical controls differently from their developers
Fl_Button constructor follows the common widget pattern
FLTK supplies the button's pressed/released visual feedback
callback signature: void function(Fl_Widget *w, void *user)
register a function and context with the widget's callback method
the example prints to stdout to keep event handling visible and short
three buttons: Say hello, Say goodbye and Quit
Fl::run finishes when no displayed application windows remain
finding the intended window:
layout uses named width, height, spacing and font-size constants
retain button pointers to configure callbacks
finish the group, show the window and run the event loop
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)
#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();
}
#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();
}
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();
}
#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();
}
several controls derive from Fl_Button
Fl_Check_Button: a checkbox with a label
radio buttons represent mutually exclusive choices
Fl_Radio_Round_Button supplies the familiar circular indicator
FLTK radio grouping follows the common parent widget
the demonstration combines radio buttons, a checkbox and ordinary buttons
pass all relevant widget pointers in a controls structure
parallel constant arrays associate radio positions with colors and labels
Set callback:
derive layout from six named dimensions/style values
box setup:
register Set with the controls pointer, then end/show/run the window
the same callback could be registered on the options for immediate updates
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)
#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();
}
#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();
}
#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();
}
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;
}
#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();
}
three relevant input classes:
Fl_Input takes coordinates, dimensions and an optional label
value() returns the current text as const char*
demo: input field with print, clear and quit buttons
keyboard focus identifies the widget receiving typed input
clicking a button can move focus away from the input field
layout reserves space for the input's Type: label
typing followed by Enter should perform the natural primary action
Fl_Input can invoke the same print callback directly
position(): get or set the insertion cursor
mark(): get or set that other boundary
size() without arguments reports text length
replace(begin, end, text) edits a half-open range
additional operations are documented by the toolkit
Fl_Int_Input and Fl_Float_Input constrain numeric input syntax
Fl_Secret_Input masks displayed characters for password entry
Fl_Multiline_Input displays embedded newlines as separate lines
wrap controls display of long lines
for multiline input, place a label appropriately above the editing region
Fl_Text_Editor suits more substantial editing and supplies scrolling
create a buffer and attach it to the editor with buffer(buf)
print callback:
clear callback:
one buffer may be shared by several editor/display widgets
the chapter leaves the editor's larger feature set to toolkit documentation
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)
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
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 |
Fl_Widget supplies common presentation properties
box() chooses the frame/background style
color() selects a background color value
labelcolor() separately selects the label text color
label(text) retains the supplied text pointer
copy_label(text) copies the text into library-managed storage
constructor-supplied labels also retain their text pointer
@ introduces a built-in graphical symbol within a label
built-in symbols can be resized, reflected and rotated
symbol modifiers follow @ before the symbol name
keypad examples: 6 faces right, 8 up, 4 left, 2 down
@8>> and @00090>> point the double-arrow symbol upward
the labelpics example demonstrates combinations of these modifiers
symbol parsing expects symbols at label boundaries
align() combines FL_ALIGN_ flags to position the label
FL_ALIGN_INSIDE moves alignment to the widget's interior
FL_ALIGN_WRAP wraps labels within the allocated width
labelcolor and labelsize set label color and font size
labelfont selects a font family/style
Helvetica is sans serif; Times has serifs; Courier is monospaced
the author found Screen selection unpredictable in his environments
the fonts example displays available variants
labeltype selects label rendering effects and more complex label forms
some controls rely on their drawing style for correct repainting
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)
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
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;
}
labels can show results but their text is not normally selectable
Fl_Output provides a non-editable single-line text field
selectable output belongs in value(text), not the widget's label
output text follows input-like left alignment
make read-only results look read-only
retain a filled box style
Fl_Text_Display suits larger scrollable text views
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)
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
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();
}
resizable windows require an explicit policy for their contained widgets
the source presents FLTK's geometry-based scheme
Fl_Group manages child resizing
resizable(widget) identifies a reference rectangle for the group's changes
resizable(0) disables automatic resizing of the group's children
choosing a contained resizable widget distributes changes by overlap
diagram's central R changes in both dimensions
nested groups and invisible widgets can express more complex policies
useful patterns:
such patterns require deliberate construction of the group hierarchy
a window is also a group
current group determines the parent of newly created widgets
add can attach an existing widget directly
window shrinking can stop at an automatically selected minimum
Fl_Window::size_range configures limits explicitly
without size_range, the example version derives minimums from resizable
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)
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
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
}
#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
graphical programs can still accept command-line options
win->show(argc, argv) offers the simple library-only route
applications with their own options can combine the two parsers
Fl::args takes argc, argv, an index reference and optional handler
the application handler gets first chance at the current option
parsing stops at end of arguments or a positional argument
options after the first positional argument are not processed by this pass
this argument-handler interface has no user-data pointer
in the book's Fl::args path, still call show(argc, argv)
demo: a variable number of buttons with trailing arguments as labels
name layout constants and begin with buttons_count = 3
count parser:
application option handler:
main:
Fl::arg processes one current option under the application's own loop
coordinate this manual route with show's parsing behavior
cmdline2.cpp demonstrates that manually driven variant
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)
#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();
}
#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();
}
#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();
}
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");
}
the following is an orientation to facilities omitted from full examples
event handling can intercept keyboard, mouse and other activity
menu and selection widgets:
Fl_Scroll provides a scrollable area containing widgets
Fl_Progress displays progress through a longer operation
Fl_Valuator's subclasses offer numeric-value controls
Fl_Table supports tabular arrangements
Fl_Tile arranges touching child regions with draggable boundaries
Fl_Tabs provides user-selectable pages
Fl_Wizard provides pages selected by the application
Fl_Tooltip controls tooltip behavior
predefined modal dialogs provide simple messages and choices
other dialogs request text, passwords, files, directories or colors
Fl_Image and its subclasses represent image data
the toolkit contains much more than this introduction
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)
#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;
}
#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;
}
#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();
}
#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();
}
#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();
}
#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
#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
#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();
}
#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();
}
#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
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(); }
};
#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();
}
inspect the toolkit as an example of architectural paradigms
the author considers parts of FLTK only partly object-oriented
he also contrasts callback functions with object/message interaction
ordinary callback registration combines function address and void* context
an object-oriented alternative passes an object with a virtual method
for widgets, derive a class and override an event-reaction method
an adapter layer can provide that interface over FLTK callbacks
rewrite the earlier speaking-buttons demo with unchanged visible behavior
OOFLButton derives from Fl_Button
a no-op default is meaningful here
a normal non-static member cannot match the plain callback pointer type
private static CallbackFunction matches FLTK's callback signature
the adapter explicitly declares a virtual destructor
the reusable adapter contains no application-specific action
application subclasses divide the two button roles
ButtonCommon centralizes shared position, dimensions and label font
SayButton stores its message pointer and implements OnPress with output
ExitButton's override performs its exit action
main now constructs the window and three already-configured buttons
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)
#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();
}
#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();
}
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;
}
GUI toolkits commonly offer their own main event loop
other event sources may need equal attention
one route is to register other events with FLTK
the source then explores an external loop instead
idea: open the X connection under application control
the book's recipe:
a complete integration must also account for already queued events, timers,
pending redraws and library work that does not create fresh socket readiness
the author warns that this low-level recipe may change across versions
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)
#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();
}
#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;
}
#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;
}
#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;
}
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.
the chapter deliberately covers a limited historical subset
professional work may require the standard library and newer C++
if preparing for a specific role, learn its required missing facilities
the author's alternative learning sequence is to build one or two useful
programs with the studied mechanisms before moving to other facilities
the author suggests Jeff Alger's C++ for Real Programmers as further reading
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)
#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