0% found this document useful (0 votes)
125 views61 pages

Reference Manual

This document is a reference manual for the C++ programming language. It describes the new features added to C to create C++, including classes, inline functions, operator overloading, and more. The manual is organized similarly to the Unix System V C reference manual, with sections covering syntax, declarations, statements, and differences from C. It provides an overview of the C++ language and its extensions beyond C.

Uploaded by

eric toure
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
125 views61 pages

Reference Manual

This document is a reference manual for the C++ programming language. It describes the new features added to C to create C++, including classes, inline functions, operator overloading, and more. The manual is organized similarly to the Unix System V C reference manual, with sections covering syntax, declarations, statements, and differences from C. It provides an overview of the C++ language and its extensions beyond C.

Uploaded by

eric toure
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

The C+ + Prograrnming Language - Reference Manual

Bjarne S1roumup
AT&T Bell Laboratories
Murray Hill, New Jersey 07974

ABSTRACT

C+ + is C extended with classes, inline functions, operator overloading,


funcûan name overloading, constant types, references, free store management,
function argument checking, and a new function definition syntax. This manual
was derived from the Unix System V C refen:nce manual, and the general organi-
zatian and sectiœ numbering have been preserved whereever possible. The differ-
enœs between C + + and C are summarlzed. Except for details like introduction
of ncw keywords, C+ + is a superset of C. An index and a table of contents are
also provided. For a more readable presentation of most of the new features see
Bjarne Stroustrup: "A C+ + TIIIDrlal". or
Bjarne Stroustrup: "The C+ + Programming LIJ.nguag, - Referenc, Manlllll".
Both in this volume.
CON'IENTS

1. INTRODUCTION 1
2. LEXICAL CONVENTIONS • 1
2.1 Comments • 1
2.2 Identifiers (Names) 1
2.3 Keywords 1
2.4 Constants 1
2.5 Strings 2
2.6 Hardware charactcrlstic:s 3
3. SYNTAX NOTATION 3
4. WHAT'S IN A NA.ME? 3
4.1 Scopes 3
4.2 Storage classes 4
4.3 Fundamental types 4
4.4 Derived types • 4
S. OBJECTS AND LVALUES s
6. CONVERSIONS s
6.1 Charaeters and integers 5
6.2 Float and double • 5
6.3 Floating and integral 5
6.4 Pointers and integers 5
6.5 Unsigned 5
6.6 Arithmetic conversions • 6
6.7 Void 6
7. EXPRESSIONS 6
7.1 Primary expressions • 7
7.2 Unary operators 8
7.3 Multiplicative operaton 10
7.4 Additive operators 10
7.5 Shift operators 11
7.6 Relational operators 11
7.7 Equality operators 11
7.8 Bitwisc AND operator 11
7.9 Bitwise exclusive OR operator 12
7.10 Bitwisc inclusive OR operator 12
7.11 Logical A.."ID operator 12
7.12 Logical OR operator 12
7.13 Conditional operator 12
7.14 Assignment operators 12
7.15 Comma operator • 13
7.16 Overloaded operators 13
8. DECLARATIONS 14
8.1 Scope and storage class specifiers 14
8.2 Type specifiers 15
8.3 Declarators 16
8.4 Meaning of declarators • 17
8.5 Class declarations 19
8.6 Initialization 28
8.7 Type names 30

.. i -
8.8 Typedcf 31
8.9 Overloaded function names 32
8.10 Enumeration declarations 33
(~_ 8.11 Asm declaration 33
9. STATEMENTS 33
9.1 Expression statemcnt 33
9.2 Compound statement, or block 34
9.3 Conditional statement 34
9.4 While statement 34
9.S Do statement • . 34
(~ 9.6 For statement • 34
\___ 9.7 Switch statement • 35
9.8 Break statement 35
9.9 Continue statemcnt 35
9.10 Retum statement 35
9.11 Ooto statcment 36
9. l2 Labelcd statement 36
9.13 Null statement 36
9.14 Delete statement • 36
9.15 Declaration statement 36
10. EXTERNAL DEFINmONS 37
10:1 Fun.ction definitions • 37
10.2 Extcmal data definitions 38
11. SCOPE RULES • 38
12. CO:MPlLER CONTROL UNES 38
12.1 Token replacement 38
12.2 File inclusion • 38
12.3 Conditional compilation 39
12.4 Line control 39
13. IMPIJcrr DECLARATIONS 39
14. TYPES REVISITED 39
14.1 Classes • 39
14.2 Functions 40
14.3 Arrays, pointers, and subscripting 40
14.4 Explicit pointer conversions 40
15. CONSTANT EXPRESSIONS 41
16. PORTABILttY CONSIDERATIONS • 41
17. FREE STORE 42
18. SYITTAX SUMMAY 42
18.1 Experessions 43
18.2 Dcclarations 44
18.3 Statemenis • 47
18.4 Extemal de.finitions • 47
18.5 Preprocessor 48
19. DIFFERENCES FROM C 48
19.l Extensions • 48
19.2 Summary of incompatibilities • 48
19.3 Anachronisms 49

- ii -
The C+ + Programming Language - Reference Manual
Bjarne Stroustru.p
AT&T Bell Laboratorles
Mw:ray Hill, New Jersey 07974

1. INTRODUCTION
This manual descrlbes the C+ + programming language. C+ + is C as desc:ribed in the C bookt
extended with classes, inline funetions, operator overloading, function name overloading, constant
types, references, free store management, function argument cbecking, and a new function
definition syntax. The differcnces betwecn C++ and C are summarized in §19. This manual
describes the language as of October 1984.

2. LEXICAL CONVENTIONS
There are six classes of tokens: ident:ifiers, keywords, constants, strings, opera.tors, and other
separators. Blanks, tabs, new-lines, and comments (collectivcly, "white spacctt) as desc:ribcd
below are ignored exœpt as they serve to separate tokens. Some white spaœ is required to
separate otherwise adjacent identifiers, keywords, and constants.
If the input stream has bcen parsed into tokens up to a given charactcr, the next token is taken to
include the longest string of characten wbich could possibly constitute a token.
2.1 Comments
The cbaracters / * introduce a comment, wbich temùnates with the characters •/. Comments do
not nest.
2.2 Identifiers (Names)
An identifier is an arbitrarily long sequenœ of letters and digits; the first character must be a
letter; the underscore _ counts as a letter. Upper- and lower-case letters are different.
2.3 Kcywords
The following identifiers are reserved for use as keywords, and may not be used otherwise:
asm auto break caae char claas conat
default delete do double elae enmn extern
float for friend. goto if inline int
long new operato:r overload. public registe:r return
short aizeof atatic atruct awitch this typed.ef
union unsigned virtual void while
(_ 2.4 Constants
Toere are several kinds of constants, as listed below. Hardware characterlstics that affect sizes are
summarized in §2.6.
2.4.1 Integer constants
An integer constant consisting of a sequence of digits is taken to be octal if it begins with o (digit
zero), decimal otherwise. The digits 8 and gare not octal digits. A sequence of digits preœded by
Dx or ox (digit zero) is taken to be a hexadecimal integer. The hexadecimal digits include a or A
(_ through f or F with values 10 through 15. A decimal constant wbose value exœeds the largest

+ This manual is or~ed like the rcfermce manual in The C Programming Longuoge by Brian W.
Kemighan and Dennis M. Ritchie, Prentice Hall, 1918.
C++ Reference Manual 2

signed integer is taken to be long; an octal or hex constant which exceeds the largest unsigned
integer is llk:ewise taken to be long; othcrwise integer constants are taken to be int.
2.4.2 Explici.t long constants
A declmal, octal, or hexadecimal integer constant immedi.ately followed by l (letter ell) or L is a
long constant.
2.4.3 Character constants
A character constant is a character enclosed in single quotes, as in 'x' . The value of a character
constant is the numerlcal value of the character in the machine's character set. Cbaractcr constants
are taken to be int.
Certain non-araphic characters, the single quote ', and the backslash \, may be represented
according to the following table of escape sequences:
new-line NL (LF) \n
horizontal tab HI' \t
vertical tab VT \v
backspace m \b
caniage retum CR ~
form feed FF 'f'
backslash
single quote
\
, ,,
\\

bit pattern ddd \ddd


The escape \ddd consists of the backslash followed by 1, 2, or 3 octal digits which are ta.ken to
specify the value of the desired character. A special case of tbis construction is \0 (not followed
by a digit), which indicates the character NUL. If the character following a backslash is not one of
those specified, the backslash is ignored.
2.4.4 Floating constants
A floating constant consists of an integer pan, a decimal point, a fraction pan, an e or E, and an
opûonally signcd intcger exponent. The integcr and fraction parts bath consist of a sequence of
digits. Either the integer part or the fraction part (not both) may be missing; either the decimal
point or the e (E) and the exponent (not bath) may be missing. A floating constant which cannot
be represcnted exactly as a single-precision float is taken to be double-precision; see §2.6.
2.4.5 Enumeration constants
Names decl.ared as cnumerators (see §8.5) are çonstants of type int.
2.4.6 Declared constants
An abject (§5) of any type can be specified to have a constant value throughout the scope (§4.1) of
its name. For pointers the •const declarator (§8.3) is used to achieve this; for non-pointer
objects the speclfier const (§8.2) is used.
2.5 Strings
A string is a sequenœ of characters surrounded by double quotes, as in " ••• ". A string has type
c_ "array of characters" and storage class static (see §4 below), and is initialized with the given
characters. All strings, even when wrltten identically, are distinct. The compiler places a null byte
'\O at the end of each string so that programs whicb scan the string can find its end. In a string,
the double quote charactcr " must be preceded by a'\; in addition, the same escapes as described
for character constants may be used. Finally, a new-line may occur only immediately following a
\.; then both the \ and the new-line are ignored.
C+ + Refertnce Manual 3

2. 6 Hardware characterlstics
The following table summarizes certain hardware properties that vary from machine to machine.
(_ DEC VAX Motorola 68000 IBM370 AT&T3B
ASCII ASCII EBCDJC ASCn
char 8 bits 8 bits 8 bits 8 bits
int 32 16 32 32
short 16 16 16 16
long 32 32 32 32
float 32 32 32 32
double 64 64 64 64
pointer 32 32 24 32
float range :t 10:38 ±10=38 :t:10=76 ±10=38
double range ±10=38 ±10=38 :tlO:t:76 :tlO:t: 308
field type signed unsigned unsigned unsigned
field order right-to-left left•t?-ril!tt left-to-right left-to-right
char simed unsitmed unsimed

3. SYNTAX NOTATION
In the syntax notation uscd in this manual, syntactic categories are indicated by italic type, and
literal words and characters in constant width type. Alternatives are listed on scparate Unes.
An optional terminal or non-terminal symbol is indicated by the subscript "opt," so that
{ expressionopt }
indicates an optional expression enclosed in braces. The syntax is summa:rized in §19.

4. \VHAT'S IN A NAME?
A name denotes an object, a function, a type, or a value. A name can only be used within a
region of program text called its scopc. A name has a type which determines its use. An abject is
a region of storage. An object bas a storage class which deter:m.incs its lifetime. 'Ibe meaning of
the values found in an object is determined by the type of the name used to acœss it.
4.1 Scopes
Thcre are four kinds of se.ope: local, file, program, and class.
Local: A name declared in a block is local to that block and can only be used in it after the
point of declaration and in blocks enclosed by it. Exceptions are labels (§9.12) which can be
used anywhere in the functian in which they are declared, and function names which be.long
to the file or program scopc. Names of formal parameters for a function arc treated as if
they wcrc declared in the outermost block of that function.
File: A name declared outside any block (§9.2) or class (§8.S) can be used in the file in
which it is declared after the point of declaration. It is not accessible from other files in a
multi-file program unlcss it is explicitly declared extern.
Program: A name declared extern is common to every file in a multi-file program, so that a
dcclaration of that name in another file refm to the same object (§5), fonction (§10.1), type
(§8.7), or value (18.10).
Class: The name of a class mcmber is local to its class and can only be used either in a
member function of that class, for an object of its class using the • operator (§7.1), or for a
pointer to an object of its class using the •> operator (§7.1). Static class members (§8.S.1)
and function members can also be rcferred to where the name of their class is in scope by
using the : : operator (§7 .1).
C++ Reference Manual 4

A name may be hidden by an explicit decl.aration of that same name in a block or cl.ass. A name in
a block or class c:an only be hidden by a name declared in an enclosed block or class. A hidden
non-local name can still be used when its scope is speclfied using the : : opcrator; sec §7.1.
4.2 Storage classes
There are twa declarable storagc classes: automatic and static.
Automatic abjects are local to each invocation of a block and are discarded u.pon exit from it.
Static abjects exist and retain their values throughout the execution of the entire program.
Some abjects are not associated with names and their lifetimes are explicitly controlled using the
new and delete operators; sec §7.2, §9.14, and §17.
4.3 Fundamental types
Objects declared as characten (char) are large enough to store any member of the
implementation's character set, and if a gcnuine character from tbat character set is stored in a
character variable, its value is equivalent to the integer code for that character. Other. quanti.tics
may be stored into character variables, but the implementation is machine-dependent.
Up to three sizes of integcr, declared ahort int, int, and long- int, are available. Longer
integers provide no less storage t1um shorter ones, but the implcmentation may make either shon
integers, or long integers, or both, equivalent to plain integers. "Plain" integers bave the natural
size suggested by the host machine architecture; the other sizes are provided to meet special needs.
Each enumeration (§8.9) is a set of named CODStants. The properties of an enwn are identical to
those of an int.
Unsigned integers, declarcd unsigned., obey the laws of arithmetic modulo 2n where n is the
number of bits in the representation.
Single-precision floatina point (float) and double-precision tloatin& point (double) may be
synonymous in some implementations.
Because objects of the foregoing types can usefully be interpreted as numbers, they will be referred
to as arithmenc typeS. Types char, int of all sizes, and enwn will collectively be callcd tnzegral
types. float and double will collectively be calledfloating types.
The void type speclfies an empty set of values; sec §6.7.
4.4 Derived types
Besides the fundamental arithmetic types there is a conceptually infinite number of derived types
(_ constructed from the fundamental types in the following ways:
arrays of objects of a given type;
Junctions which take argwnents of given types and return objects of a given type;
pointers to objects of a given type;
references to objects of a given type;
constants which are values of a givcn type;
classes containing a sequence of abjects of various types, a set of functions for manipulating
these objects, and a set of restrictions on the access to these objects and functions;
structures which are classes without access restrictions;
unions which are structures capable of containing objects of different types at different times.
In gencral these methods of constructing objects can be applied rec:unively.
C++ Reference Manual 5

5. OBJECTS AND LVALUES


An object is a region of storage; an /value is an expression referring to an object. An obvious
(~_ example of an lvalue expression is the name of an object. There are operators which yield !values:
for example, if E is an expression of pointer type, then *E is an !value expression rcferting to the
object to which E points. The name "!value" comes from the assignment expression E 1 • E2 in
which the left operand E1 must be an lvalue expression. The discussion of each operator below
indicates whether it expects lvalue operands and whether it yields an !value.

6. CONVERSIONS
A number of operators may, depending on their operands, cause conversion of the value of an
operand from one type to another. This section explains the result to be expected from such
conversions. §6.6 summarizes the conversions demanded by most ordinary operators; -it will be
supplemented as required by the discussion of each operator. §8.S.6 describes user-defined
conversions.
6.1 Characters and intcgers
A character or a shon integer may be used wherever an integer may be used. In all cases the
value is convened to an integer. Conversion of a shoner integer to a longer always involves sign
extension; integers are signed quantities. Whethcr or not sign-extension occurs for characters is
machine dependent; sec §2.6. The more expliclt type unsigned char forces the values to range
from O to a machine dependent maximum.
On machines that treat characters as signed, the characters of the ASCII set are all positive.
However, a character constant specified with an octal escape suffers sign extension and may appear
negative; for example, '\377' bas the value -1.
\Vhen a longer integcr is converted to a shorter or to a char, it is truncated on the left; excess bits
are simply discarded.
6.2 Float and double
Floating arithmetic is carried out as if in double·precision. Conversions between single-precision
and double-precision floating-point numbers are as mathematically correct as the hardware allows.
6.3 Floating and intcgral
Conversions of floating values to integral type tend to be machine-dependent; in particular the
direction of truncation of negative numbers varies from machine to machine. The result is
undefined if the value will not fit in the space provided.
(_ Conversions of integral values to floating type arc well bchavcd. Some loss of precision occurs if
the destination lacks sufficient bits.
6.4 Pointers and integers
An expression of integral type may be added to or subtracted from a pointer; in such a case the
first is converted as specified in the discussion of the addition operator.
Two pointers to objects of the same type may be subtracted; in this case the result is convened to
an int or a long- dependent on the machine; sec §7.4.
(__ 6.5 Unsigned
\Vhenever an unsigned integer and a plain integer are combined, the plain integer is converted to
unsigned and the result is unsiped. The value is the least unsigned integer congruent to the
signed integer (modulo 2wordsize). In a 2's complement repre.sentation, tbis conversion is
conccptual and there is no actual change in the bit pattern.
C+ + Reference Manual 6

\Vhen an unsigned integer is converted to long, the value of the result is the same numerically as
that of the unsigned integer. Thus the conversion amounts to padding with zeros on the left.
(_ 6.6 Arithmetic conversions
A great many operators cause conversions and yicld result types in a similar way. This pattern
will be called the "usual arithmetic conversions."
First, any operands of type char, unsigned char, or short are converted to int, and
any of type float is convertcd to doul)le.
Then, if either operand is doul>le, the other is converted to double and that is the type of
the result.
Otherwise, if either operand is unsigned long the other is converted to unsigned long
and that is the type of the result.
Otherwise, if either operand is long, the othcr is converted to long and that is the type of
the rcsult.
Otherwise, if either operand is unsigned, the other is converted to unsigned and that is
the type of the rcsult.
Otherwisc, bath operands must be int, and that is the type of the result.
6.7 Void
The (nonexistent) value of a voie! objcct may not be used in any way, and ncitber explicit nor
implicit conversions may be applicd. Because a void expression denotes a nonexistent value, such
an expression may be used only as an expression statement (§9.1) or as the left operand of a
comma expression (§7.15).
An expression may be convcrted to type void by use of a cast. For example, this makcs explicit
the discarding of the value of a function call uscd as an expression statement.
A abject of type void• (pointer to void) can be used to point to abjects of unknown type.

7. EXPRESSIONS
The preccdence of expression operators is the same as the order of the major subscctions of this
section, highest preccdencc first. Thus, for examplc, the expressions rcfcrrcd to as the operands of
+ (§7.4) are those expressions defined in §§7.1-7.4. Within each subsection, the operators have
the same precedence. Left- or right-associativity is specified in each subsection for the operators
discusscd therein. The precedence and associativity of all the expression operators is summarized
in the grammar of §18.
Otherwise the order of evaluation of expressions is undefined. In particular the compiler considers
itself free to compute subexpressions in the order it believes most efficient, even if the
subcxpressions involve side effects. The order in which side effects take place is unspecified.
Expressions involving a commutative and associative operator (*, +, &., 1, A) may be rearranged
arbitrarily, evcn in the presence of parenthcses; to force a particular order of evaluation an explicit
temporary must be used.
Toe bandling of ovcrflow and divide check in expression evaluation is macbine-dependent. Most
C_ existing implementations of C++ ignore integer overflows; treatmcnt of division by 0, and ail
floating-point exceptions, varies between machines, and is usually adjustable by a library function.
In addition to the standard meanings described in §7.2-7.15 operators may be overloaded, that is
given meanings when applied to user-dcfined types; see §7 .16.
C+ + Reference Manual 7

7.1 Primary expressions


Primary expressions involving • , ->, : : , subscrlpting, and function calls group left-to-right.
id:
identifier
operaior-fanction-name
typedef-name : : identifier
typedef-name : : operator-function-name
primary-upression:
id
: : identifier
constant
string
this
( expression )
primory-apression [ expression J
prima.ry-expression ( expression-List 1 )
primary-expression • Id op
primary.upreuion -> id
apression-llst:
expression
expression-lin , expression
An identifier is a primary expression, provided it bas been suitably declared as discussed below.
Its type is specified by its decl.aration. If the type of the identifier is "array of •.• ", however, then
the value of the identifier-expression is a pointer to the first object in the array, and the type of the
expression is "pointer to ... ". Moreover, an array identifier is not an !value expression.
Likewise, an identifier wbich is declared "function retumin& •.. ", when used cxcept in the
function-name position of a call, is converted to "pointer to function retuming ... ". An operator-
jllnaion-name is an identifier with a special meaning; see §7.16 and §8.5.10.
The operator : : followed by an identifier is a prlmary expression, provided the identifier bas been
suitably declared in the file or program scope (§4.1). Its type is specmed by the declatation of the
identifier. It allows an object to be referred to by name even if its identifier has been redefined in
a looal scope.
A typedef-name (§8.8) followed by : : folowed by an identifier is a primary expression. The
rypedeJ-name must denote a class (§8.S) and the identifier must denote a member of that class. Its
type is specified by the declaration of the identifier.
A constant is a prlmary expression. Its type may be int, long, or double depending on its
form.
A string is a primary expression. Its type is originally "array of char"; but following the same
rule given above for identifiers, this is modified to "pointer to char" and the result is a pointer to
the first character in the string. (There is an exception in certain initializers; see §8.6.).
The keyword this is a prlmary expression in the body of a me:mbcr function (see §8.5). 'Ibere it
refers to the abject for which the membcr function was invok.ed.
A parenthesized expression is a primary expression whose type and value are identical to those of
the unadorned expression. The presence of parmtheses does not affect whether the expression is
an lvalue.
A prlmary expression followed by an expression in square brackets is a prlmary expression. The
intuitive meaning is tbat of a subscript. Usually, the prlmary expression has type "pointer to ... ",
the subscript expression is int, and the type of the result is " ... ". The expression !1 [E2] is
C+ + Reference Manual 8

identical (by definition) to * C{E 1 ) + <E2 ) ) • All the clues needed to understand this notation are
contained in this section together with the discussions in§§ 7.1, 7.2, and 7.4 on identificrs, *, and
+ respectively; §14.3 below summarlzes the implications.
C A function call is a primary expression followed by parenthescs containing a possibly empty,
comma-separated list ·of expressions which constitutc the actual arguments to the function. The
primary expression must be of type "function returning ... ", and the result of the function call is
of type " ... ". A hitherto unseen identifier followed immcdiatcly by a left parenthesis is
contextually declared to represent a function returning an integer. Its argument type will be
declared to that of the argument list of the call.
The actual arguments are compared with the formai arguments and conversions are performed as if
(_ the forma! argument were initializcd with its actual argument (see §8.6).
ln preparing for a call to a function, a copy is made of each actual parametcr. A function may
change the values of its forma! parametcrs, but thesc changes cannot affect the values of the actual
parameters. On the other band, it is poss10le to passa pointer or a referenœ on the understanding
that the function may change the value of the object to whicb the pointer or referenœ points. An
array name is a pointer expression.
A function may be declared to accept fewer arguments or more arguments than are specified in the
function declaration; sec §8.4. Any actUal argument of type :float for which there is no forma!
argument are converted to double before the call; any of type char or short are converted to
int; and as usual, array names are convertcd to pointers. The order of evaluation of arguments is
undefined by the language; take note that the various compilers differ.
&cursive ca1ls to any function are permitted.
A primary expression followed by a dot followed by an identifier (or an identifier qualified by a
typedcf-name using the : : operator) is an expression. The first expression must be a class object,
and the identifier must name a member of that class. The value is the named member of the
object, and it is an !value if the first expression is an !value. Note that "class objects" can be
structures (§8.5.11) and unions (§8.5.12).
A primary expression followed by an arrow ( • >) followed by an identifier (or an identifier
qualified by a typedef-name using the : : operator) is an expression. The first expression must be
a pointer to a class object and the identifier must name a member of that class. The result is an
!value referring to the named member of the class to which the pointer expression points. Thus
the expression E1•>MOS is the same as ( •E1) .MOS. Casses are discussed in §8.5.
If a primary expression yields a value of type "referenœ to ... " (sce §8.4 and §8.6.3) that value is
immediately dereferenccd so that the value of the expression is · the objcct denoted by the
(_ reference. H this object is also a referenœ, it too will be dereferenced, and so on. A referenœ
can be thought of as a name of an object; sce §8.6.3.
7.2 Unary operators
Expressions with unary operators group riaht·to·left.
C++ Reference Manual 9

unary-expression:
unary-operator expression
expression + +
expression - -
C ryp,-name ) expression
simple-rype--name ( expression-list )
si zeof expression
sizeof C typt·name
new typtM1ame
new ( type-nome
unary-operator: one of
* L - 1 • ++
The unary * operator means indirection: the expression must be a pointer, and the result is an
lvalue rderring to the object to which the expression points. If the type of the expression is
"pointer to ... ", the type of the result is " ... ".
The result of the unary & operator is a pointer to the object referred to by the operand. The
operand must be an lvalue. If the type of the expression is " ... ,, , the type of the result is
"pointer to ... ".
The result of the unary - operator is the negative of its operand. The operand must be of integral
type. The usual arlthmetic conversions are pcrformcd. The negative of an unsigned quantity is
computed by subtractina its value from 2n, where n is the number of bits in an int. 'Ihere is no
unary + operator.
The result of the logical negation operator J is 1 if the value of its operand is 0, 0 if the value of
its operand is non-zero. The type of the result is int. It is applicable to any arlthmetic type or to
pointers.
The • operator yields the one's complement of its operand.. The usual arithmetic conversions are
performed. The type of the operand must be integral.
The operand of prefix ++ is incremented. The operand must be an !value. The value is the new
value of the operand, but is not an !value. The expression ++xis equivalent to x+•1. See the
discussions of addition (§7.4) and assignment operators (§7 .14) for information on conversions.
The operand of pretix - - is decremented analogously to the prefix + + operator.
The value obtained by applying a postfix + + is the value of the ope.rand. The operand must be an
lvaluc. After the result is noted, the objcct is incrcmentcd in the same manner as for the prefix ++
operator. The type of the result is the same as the type of the operand.
The value obtained by applying a postfix -- is the value of the operand. The operand must be an
!value. After the result is noted, the object is decremented in the manner as for the prctix --
operator. The type of the result is the same as the type of the operand.
A simple-typt-name (§8.2) followed by a parenthesized expression causes the value of the
expression to be c.onverted to the named type. To express conversion to a type that does not have
a simple name the rype-name (§8.7) must be parenthesized; ùt this case the expression need not be
parenthesized. This construction is called a cast. The mcthod for defining conversions for user-
defincd types (classes) is desc:rlbcd in §8.S.S and §8.5.6. For user-defined types an expression list,
rather than: a simple expression, can be used; sce §8.S.S.
The s izeof operator yields the size, in bytes, of its operand. (A byte is undefined by the
language except in tcrms of the value of sizeof. However, in all existing implemcntations a byte
is the space required to hold a char.) When applied to an array, the result is the total number of
bytes in the array. The size is detcrmined from the declarations of the objects in the expression.
This expression is semantically an uns:lgned constant and may be used anywhere a constant is
C+ + Re/erence Manu.al 10

required. Its major use is in communication with routines likc storage ailocators and 1/0 systems.
The sizeof operator may also be applied to a parenthesized type name. In that case it yields the
size, in bytes, of an abject of the indicated type.
The new operator creates an object of the type-name (sec §8.7) to wbich it is applied. The lifetime
of an object crcated by new is not restricted to the scope in which it is created. The new operator
returns a pointer to the object it created. When applied to an object of type T it therefore gcnerally
returns a value of type T•. However, the type yielded for an array type T [ ] is T• • For example,
both new int and new int [ 10] return an int•. See §17 for details of how the free store is
managed.
7. 3 Multiplicative operators
The multiplicative operators •, /, and " group left-to-rlght. The usual arithmetic conversions are
performed.
multiplicative-expression:
expression * expression
expression / expression
expression " expression
The binary * opcrator indicates multiplication. The * operator is associative and expressions with
several multiplications at the same lcvel may be rearranged by the compiler.
The binary / operator indicates division. When positive integers are divided truncation is toward
0, but the form of truncation is machine-dependent if either operand is negative. On ail machines
covered by this manual, the remainder bas the same sign as the dividend. It is always truc that
( a/b) •b + aXb is equal to a (if bis not 0).

The binary" operator yields the remaindcr from the division of the first expression by the second.
Toc usual arithmetic conversions arc performed. The operands must not be floating.
7.4 Additive opcrators
The additive operators + and - group left-to-rlght. The usual arithmetic conversions are
performed. There arc somc additional type possibilities for each operator.
additive-expression:
expression + expression
expression - expression
The result of the + operator is the sum of the operands. A pointer to an abject in an array and a
value of any integral type may be added. The latter is in ail cases converted to an address offset
by multiplying it by the lcngth of the abject to wbich the pointer points. The result is a pointer of
the same type as the original pointer, and which points to another object in the same array,
appropriately offset from the original object. Tous if P is a pointer to an abject in an array, the
expression P + 1 is a pointer to the next object in the array.
No further type combinations are allowed for pointers.
The + operator is associative and expressions with several additions at the samc lcvel may be
rearranged by the compiler.
(_ The result of the - operator is the differencc of the operands. The usual arithmetic conversions
are performed. Additionally, a value of any integral type may be subtracted from a pointer, and
then the same conversions as for addition apply.
If two pointers to abjects of the same type are subtracted, the result is converted (by division by
the length of the object) to an integer representing the number of abjects separating the pointed·to
objccts. Depending on the machine the resulting intcger may be of type int or type long; sec
§2.6. This conversion will in gencral give unexpccted results unless the pointers point to objccts in
C+ + Reference Manual 11

the same array, since pointers, evcn to objects of the same type, do not necessarily differ by a
multiple of the object-lenam.
7 .S Shift operators
The shift operators < < and > > group lefMo-rlght. Both perform the usual aritbmetic conversions
on their operands, each of which must be integral. Then the right operand is converted to int;
the type of the result is that of the left operand. The result is undefined if the right operand is
negative, or greater than or equal to the lcnath of the object in bits.
shift-expression:
expression < < expression
expression > > expression
The value of E1 « E2 is E1 (interpreted as a bit pattern) left-shifted E2 bits; vacated bits are 0-
filled. The value of E 1 » E2 is E 1 right-shifted E2 bit positions. The rlght shift is ,uaranteed
to be logical (0-fill) if E1 is unsigned; otherwise it may be arithmetic (fill by a copy of the sign
bit).
7.6 Relational operators
The relational operators group left-to-right, but tbis fact is not very use.ful; a<b<c does not mean
what it seems to.
relational-expression:
expressitJn < uprusion
apressitJn > ex.pression
expression < • expression
expression > • expression
The operators < (less than), > (greater than), o (less than or equal to) and >• (sreater than or
equal to) all yield O if the spedfied relation is false and l if it is truc. The type of the result is
int. The usual arithmetic conversions are performed. Two pointers may be compared; the result
depends on the relative locations in the address spaœ of the pointed-to abjects. Pointer
comparison is portable only wben the pointers point to abjects in the same array.
7. 7 Equality operaton
equality-expr,ssion:
expression •• expression
expressitJn. l • expression
The •• (equal to} and the ! • (not equal to) operators are exactly analogous to the relational
operators except for their lower precedence. (Thus a<b •• cccl is 1 wbenever a<b and c<cl
have the same truth-value.)
A pointer may be compared to an integer only if the integer is the constant O. A pointer to which
0 bas bcen assigned is guaranteed not to point to any object, and will appear to be equal to O; in
conventional usage, such a pointer is considered to be null.
7 .8 Bitwisc AND operator
and-expression:
expressitJn &. uprusitJn
The&. operator is associative and expressions involving & may be rearranged. The usual arithmetic
conversions ·are performed; the result is the bitwise AND function of the operands. The operator
applies only to integral operands.
C+ + Reference Manual 12

7.9 Bitwise exclusive OR operator


exclusive-or-expression:
(_ expression " expression
The ,. opcrator is associative and expressions involving,. may be rearranged. The usual arithmetic
conversions are performed; the result is the bitwise exclusive OR function of the operands. The
opcrator applies only to integral operands.
7.10 Bitwise inclusive OR operator
inclusive-or-expression:
expression I expression
(_ The I opcrator is associative and expressions involving f may be rcarranged. The usual arithmetic
conversions are performed; the result is the bitwise inclusive OR function of its operands. The
operator applies only to integral operands.
7.11 Logical AND operator
logical-and-expression:
expression il expression
The &.&. operator groups lefMo-right. lt returns 1 if bath its operands are non-zero, 0 otherwise.
Unlike &., &.& guarantees left-to-right evaluation; moreover the second operand is net evaluated if
the first operand is O.
The operands need net have the same type, but each must have one of the fundamental types or be
a pointer. The result is always int.
7.12 Logical OR operator
logical-or-expression:
expression f I u:pression
The 11 operator groups left-to-right. It returns 1 if either of its operands is non-zero, and 0
otherwise. Unlike 1, J I guarantees left-to-right evaluation; moreover, the second operand is net
evaluated if the value of the first operand is non-zero.
The operands need not have the same type, but each must have one of the fundamcntal types or be
a pointer. The result is always int.
7.13 Conditional operator
conditioruzl-upression:
(_ expression ? expression : expression
Conditional expressions group right-to-left. The fint expression is evaluated and if it is non-zero,
the result is the value of the second expression, otherwise that of third expression. If possi"ble, the
usual arithmetic conversions are performed to bring the second and third expressions to a common
type; otherwise, if both are pointers of the same type, the result has the common type; otherwise,
one must be a pointer and the other the constant 0, and the result has the type of the pointer.
Only one of the second and third expressions is evaluated.
7.14 Assignment operators
Toere are a number of assignment operators, all of which group rigbt-to-left. All require an lvalue
as their left operand, and the type of an assignment expression is that of its left opcrand. The
value is the value stored in the left operand after the assignment bas taken place.
C+ + Reference ManutJ.l 13

assignmem-expression:
expression assignment-operaror expression

assign:mem-operaror: one of
• +• -· •• /• %• >>• <<• &• A. 1.
In the simple assignment with •, the value of the expression replaces that of the object referred to
by the left hand operand. If both operands have arithmetic type, the rlght operand is converted to
the type of the left preparatory to the assignment. Both opcnmds may be class objects of the same
type or pointer abjects of the same type. Objects of some derived classes cannot be assigned; sec
§8.5.3. A pointer to a class may be assigned to a pointer to a public base class of that class; sec
§8.5.3. Any pointer may be assigned to a pointer of type void•. The constant Omay be assigned
to a pointer, and it is guaranteed that this value will produœ a null pointer distinguishable from a
pointer to any abject.
Since a reference is implicltly dereferenccd, assignment to a abject of type "reference to ... "
assigns to the object denoted by the reference.
The behavior of an expression of the form E 1 op • E2 may be infcrred by ta.king it as equivalent
to E 1 • E 1 op CE2); however, E 1 is evaluated only once. ln +a and -•, the left operand may
be a pointer, in which case the (integral) rlght operand is converted as explained in §7.4; all right
operands and all non-pointer left operands must have arithmetic type.
7.15 Comma opcrator
comnu:z-upression:
expression , expression
A pair of expressions separated by a comma is evaluated left-to-rlght and the value of the left
expression is discarded. The type and value of the result are the type and value of the rlght
operand. This opcrator groups left-to-right. In contexts where comma is given a speclal meaning,
for example in lists of actUal arguments to functions (§7 .1) and lists of initializers (§8.6), the
comma operator as descrlbed in this section can only appear in parentheses; for example,
f(a, (t•3, t+2), c)
bas threc arguments, the second of which bas the value S.
7.16 Overloaded operators
Most operators can be declared to accept class abjects as operands (see §8.5.10). lt is not possfüle
to change the precedence of operators. It is not possible to change the xnanjng of operators when
applied to non-class objects. The pre-defined meaning of the operators • and (unary) &. when
applied to class objects can be changed.
The meanings of somc operators arc defincd to be equivalcnt to some combination of other
opcrators on the same arguments. For example, ++a means a +a 1. Such relations do not hold for
defined operators unless the user defines them that way. Some operators, for cxample assigmnent,
require an opcrand to be an lvalue; this is not rcquired for defined operators.
7.16.1 Unary opcrators
A unary operator, whether prefix or postfix, can be defined by either by a member function (see
§8.5.4) taking no arguments or a fdend function (see §8.S.9) ta.king one argument. Thus, for
any unary operator I', both d and h can be interpreted as either x.operatoz:11() or
operatortt{ x) • If both operatorlt functions arc defined the former interpretation is usai.
Wh.en the operators + + and -- are overloaded, it is not possiôle to disûnguish prefix application
from postfix application.
C+ + Reference Manual 14

7.16.2 Binary operators


A binary operator can be defined either by a membcr function taking one argument or by a
friend. function taking two arguments. Thus, for any binary operator li, x(l)y can be interpreted
as either x.operatorl)(y) or operatorO(x,y). If bath operatorl) functions are defined the
former interpretation is uscd.
7.16.3 Special operators
Function call
prima:ry-upression ( expression-listopt
and subscripting
prima,ry-upression C expression J
are considered binary operators. The names of the defining functions are operator{) and
operator[ ], respectivcly. Thus, a call x(arg) is interpreted as x.operator() (arg) for a
class object x. The type of the argument list is defined by the operator ( ) function. A
subscripting x:Cy] is interpreted as x.operatorC J (y). The type of the argument is defined by
the operator [ J function.

8. DECLARATIONS
Declarations are used to specify the interpretation given to each identifier; they do not neœssarily
reserve storagc associated with the identifier. Dcclarations have the form
declaration:
decl-specift,rswt declarator-listopt ;
na:m,-declaratton
a.sm-declaration
The declarators in the declarator•list contain the identifien being declared. Only in c:xtemal
function definitions (§10.1) or external function declarations may the decl-specijiers be omitted.
Only wben declaring a class (§8.S) or enumcration (18.10), that is when the decl-speciftes is a
class-specifler or enum-specijier, may the declarator-list be empty. Name-declarations are described
in §8.8; asm declarations are described in §8.11.
decl-specifiers:
decl-specifter decl-specifiersopt

decl-specifier:
ss-specijier
type-specifier
fct-specift,r
friend.
typed.ef
The list must be self-consistent in a way·descnëed below.
8.1 Scope and storage class specifiers
(_ The ss-specifiers are:
ss-specijier:
auto
static
extern
regiater
C++ Reference ManlUJl 15

Declarations using the auto, static, and register specifiers also serve as definitions in that
they cause an appropriate amount of storage to be rcserved. If an extern declaration is not a
definition (that is, neither a data declaration with an initializer nor a function declaration with a
body) there must be an external definition (§10) for the given identifiers somewhere else.
A register declaration is best thought of as an auto declaration, together with a hint to the
compiler that the variables cleclared will be heavily used. The hint may be ignorcd. The address-of
operator &. cannot be applied to them.
The auto or register specifiers can only be used for names declared in a black and for formal
parameters. There can be no static funct.ions within a block, nor any static forma!
arguments. The scope of name declarcd with the static specifier outside a function or a class is
file (§4.1). The scope of the name of an object or function declared extern is program (§4.1).
At most one ss-specifler may be given in a declaration. If the ss-specifter is missing from a
declaration, the storage class is taken to be automatic inside a function and static outside.
Exception: functions are never automatic. If the ss-specifier is missing from a decl.aration, the
scope of the name is taken to be local in a block, class in a class declaration, and file elsewhere.
Exception: The scope of the name of a funct.ion that is declarcd but not defincd (§10) is taken to
be program unless it is explicitly declarcd static.
Some specifiers can only be used in function declarations and definitions:
fct-specifiers:
overload.
inline
virtual
The overload speclfier enables a sin.ale name to be used to denote several functions; see §8.9.
The inline specifier is only a hint to the compiler, does not affect the meaning of a program,
and can be ignored. lt is used to indicate that when the function is called inline substitution of the
funetion body is to be preferred to the usual fonction call implementation. lt can only be uscd in
function definitions (§10.1). A function (§8.5.2 and §8.5.9) defined within the declaration of its
class is inline by default.
The virtua.l specifier can only be used in declarations of class members; see §8.5.4.
The fr i end specifier is used to override the name hi.ding rules for class members and can only be
used within a class declaration; see §8.5.9.
The typedef specifier is used to introduœ a name for a type; see §8.8.
8.2 Type specifiers
The type-specifiers are
type-specifler:
simpl,-ryp,-Mm4
class-specljil!I'
en,nn-specifier
const
C++ Reference Manual 16

simple-rype-name:
typedef-na.me
char
( __ short
int
long
unsigned
float
double
void
The words long, short, and unsigned may be thought of as adjectives. They can be applied to
int; unsigned can also be applied to char, short, and long. The word const may be added
to any legal type-specifier. Otherwise, at most one type-specifier may be given in a declaration.
An abject of const type is not an lvalue. If the typc-specifier is missing from a declaration, it is
taken to be int.
Qass and enumeration specitiers are discussed in §8.5 and §8.10, respectively.
8.3 Declarators
The declarator-list appearing in a declaration is a comma-separated sequence of declarators, each
of which may have an initializer.
declarator-list:
init-declarator
inii-declarator , declarator-llst
init-declarator:
âeclarator initializeropt
Initializers are discussed in §8.6. The spedfiers in the dcclaration indicate the type and storage
class of the objects to which the dcclarators refer. Declarators have the syntaX:
declarator:
dname
( declarator )
* constopt declarator
&. const0 r declarator
declarator ~ argument-declaration-list
tkclarator [ constant-expressionopt J

dname:
simple-dname
typedef-name • simple-dnamt

simple-dn.amt:
identifier
typedef-name
• typedef-name
operator-function-namt
conversion-junction-namt

The grouping is the same as in expressions.


C++ Reference Manual 17

8.4 Meaning of declarators


Each declarator is taken to be an assertion that when a construction of the same form as the
declarator appears in an expression, it yields an object of the indicated type and storage class.
Each declarator contains exactly one dname; it spccifics the identifier that is declared. Exœpt for
the declarations of some special functions (see §8.S.2) a dftQ.1ne will be a simple idemifler.
Jf an unadorned identifier appears as a declarator, then it bas the type indicated by the specifier
heading the declaration.
A declarator in parentheses is identical to the unadomed decl.arator, but the binding of complex
declarators may be altered by parentheses; see the examples below.
(_ Now imagine a declaration
T 01
where Tisa type·specifier (like int, etc.) and D1 is a declarator. Suppose this declaration makes
the identifier have type" ... T," where the " ..• " is empty if D1 is just a plain identifier (so that
the type of x in "int x" is just int). Then if D1 bas the form
*O
the type of the contained identifier is " . . . pointer to T."
If o 1 has the form
* const D
the type of the contained identifier is '' ... constant pointer to T'' that is, the same type as *D, but
the contained identifier is not an lvalue.
If o1 bas the form
&.D
or
&. const D
the type of the contained identifier is '' •.. rcferenœ to T.'' Sinœ a rcference by definition cannot
be an lvalue, use of const is redundant. It is not poss10le to have a rcference to void ( a
void&.).
If o 1 has the fonn
o Cargument.dtclaration-lin)
then the contained identifier bas the type " . . • function taking arguments of type argument·
declaration-list and returning T."
argunumt..declaration-list:
arg.declaration-llstopt ••• opt

arg-declaration-list:
arg.declaration-list , argu:mem-declarad.on
arg,,,,,,.m.declaration

argument.declaration:
decl-sp,clflus declarat0r
decl-specifiers declarattJr • constant-expression
If the argumem.declaration-llst terminates with an ellipsis the number of arguments is only known
to be equal to or greater than the number of argument types specified; if it is empty the function
takes no arguments. All declarations for a function must agree exaetly both in the type of the
C+ + Referenct Manual 18

value retumed and in the number and type of arguments. The keyword void may be used to
indicat.e that a function takes no arguments, thus (void) is equivalent to C).

C The argumeni-declaration-lisr is used to check and convert actUal arguments in calls and to check
point.er-to-function assignments. If a constant expression is speclfied as initializer for an argument
this value is used as a default argument value. A default value for an argument cannot be
redefined by a latc:r declaration. Howevc:r, a declaration may add default values for arguments not
given such values in previous declarations. Default argument values will be used in calls where
trailing arguments are mi.ssing. In an argumeni-declaration the identifier in the declarator may be
lcft out (as in an absrraci-declarator (§8.7)). If present, the identifier can in fact never be used
since it goes out of scope at the end of the funetion declaration.
If D 1 bas the form
D [ connani-u.pression]
or
DC]
then the contained identifier bas type " . . . array of T." In the fim case the constant expression is
an expression whose value is detcrminable at compile time, and whose type is int. (Constant
expressions arc defincd in §15.) Wben several "array of" speclfications are adjacent, a multi-
dimensional array is creat.ed; the constant expressions which speclfy the bounds of the arrays may
be mi.ssing only for the :fim member of the sequenœ. This elision is useful when the array is
extc:rnal and the actual definition, which allocates storagc, is given elsewhere. The first constant-
expression may also be omined when the declarator is followed by initialization. In this case the
size is calculated from the number of initial elements supplied.
An array may be consttucted from one of the basic types, from a pointer, from a structure or
union, or from anothcr array (to gcneratc a multi·dimcnsional array).
Not all the possibilities allowed by the syntax above are permitted. The restrictions are as follows:
functions may not retum arrays or functions, although they may return pointers to such things;
there are no arrays of functions, although there may be arrays of pointers to functions.
AB an example, the declaration
int i, dp, f(), •fip(), (•pfi) ();
declares an integer i, a pointer ip to an integer, a funetion f retuming an integer, a function fip
retumin& a pointer to an integer, and a pointer pf i to a function which retums an integer. It is
espccially useful to compare the last two. The binding of •fip( ). is • <:Up()), so that the
C declaration suggests, and the same construction in an expression requiNs, the calling of a fonction
fip, and then using indirection through the (pointer) result to yield an integer. In the declarator
( •pf i) ( ) , the extra parentheses are necessary, as they are in an expression, to indicat.e that
indirection through a pointer to a funetion yiclds a function, which is then called. The functions f
and fip are declared to take no arguments, and pfi to point to· a funetion which takes no
argument.
The declaration
const a• 10, •pc • &.a, •const cpc • pc;
int b, •const cp • &.b;
declares a: a constant integer, pc: a pointer to a constant integer, cpc: a constant pointer to a
constant integer, b: an integer, and cp: a constant pointer to integer. The value of a, cpc, and cp
cannot be changcd aftc:r initialization. The value of pc can be ehanged, and so can the object
point.cd to by cp. E.xamplex of illegal operations are:
C++ Reference ManUIJI 19

a• 1; a++; *PC• 2; cp • La; cpc++;


Examples of legal operations are:
( b • a; *CP• a; pc++; pc • cpc;
The declaration
fseek(PILB*, long, int);
declares a function ta.king three arguments of the specified types •. Since no retum value type is
specified it is tak:en to be int (§8.2). The declaration
point(int • o, int • O);
dcclares a function which can be called with zero, one or two arguments of type int. For
example:
point(1,2);
point( 1); I• meaning point(1,0); •I
point(); /• meaning point(O,O); •I
The declaration
printf(char* ... ) ;
declares a function whicb can be called with varying nu.mber and typeS of arguments. For
example:
printf("hello world");
printf("a•Xd b•Xd", a, b);
printf ( "string • Xs" , st) ;
However, it must always have a char• as its first argument.
As another example,
float fa[17J, •afp[17];
declares an array of :f'loat numbers and an array of pointers to float numbers. Fmally,
static int x3d[3][5][7J;
declares a static three-dimensional array of inteaers, with rank 3x5x7. In complete detail, x3d. is
an array of three items; eac:h item is an array of five arrays; each of the latter arrays is an array of
seven integers. Any of the expressions x3d, x34 [ i J, x3d [ i J[ j l, x3d [ i ]C j ][ k l may
reasonably appear in an expression. The fim three have type ''array,'' the last bas type int.
8.5 Oass declarations
A class specifi.es a type. Its name becomes a 'typldef-name (see §8.8) which can be used even
witbin the class specifier itself. Objects of a class CODsist of a sequence of members.
class-spedfin-:
class-head { member-list , }
class-head { member-lisi:, public : memblr-listopt }
(_ class-head:
aggr identifier t
aggr identifier:, publicopt typedef-name
aggr.·
class
struct
union
C++ Refertnce Manual 20

A structure is a class with ail members public; see §8.S.8. A union is a structure wbich holds only
one member at a time; see §8.5.12. A member-li.st may declare data, function, class, typedef,
enum, and field mcmbers. Fields are discussed in §8.5.13. A m.ember-list may also contain
declarations adjustina the visibility of member names; see §8.5.8.
m.ember-list:
m.ember-declaration memb,r-li.stop,

m.emb,r-declaration:
decl-specifiers t m.ember-declarator initializer
function-definlll'Jn ; t opt
op

m.ember-declarmor:
declarator
identifieropt : constant-apresslon
Members that arc class abjects must be abjects of previously declared classes. ln particular, a class
cl may not contain an object of class cl, but it may contain a pointer to an object of class cl.
'l'be membcr names in different classes do not conflic:t witb cach other or with ordinary variables.
Only dcclarations of static members (§8.S.1) may contain initializers.
A simple cxample of a struct declaration is
struct tnode { .
char tword[20];
int count;
tnode •left;
tnode •right;
} ;
wbich contains an array of 20 charactets, an integer, and two pointers to similar structures. Once
tbis declaration bas been given, the declaration
tnode a, •sp;
declares a to be a tnode and ap to be a pointer to a tnod.e. With tbese declarations
ap•>count
refers to the count field of the structure to wbich sp points;
a.left
refers to the lcft subtrec pointer of the structure s; and
a.right•>tword[O]
refers to the first character of the tword. member of the right subtree of s.
8.5 .1 Static members
A data member of a class may be atatic; funetion members may not. Members may not be
auto, regiater, or extern. There is only one copy of a static member shared by a1l abjects of
the class in a program. A static me:m.ber mem of class cl can be referred to as cl : : mem, that is
without referring to an object. It exists even if no abjects of class c 1 have been crcated.
8.5.2 Member functions
A function declared as a member (witbout the friend specifier (§8.S.9) is called a member
function, and is called using the class member syntax (§7.1). For example:
C+ + Reference ManUJJ.I 21

struct tnod.e {
char tword. C2 0 J ;
int count;
C tnod.e *1eft;
tnod.e *ri9ht;
voièl set(char*, tnode• 1. tnode* r);
} ;

tnode n 1 , n2 ;
n1.aet("asd.f",&n2,O);
n2.set("ghjk",O,O);
The definition of a membcr function is considered to be w.ithin the scope of its class. This means
that it can use names of its class directly. If the definition of a membcr function is lexically
outsidc the class declaration the membcr function name must be qualified by the class name using
the rypedt/-na»N.simple-dna.me notation; see §8.3.3. Function definitions are discussed in §10.1.
For example:
void. tnode.aet{ch&r* w, tnode• l, tnod.e• r) {
count • •trlen(w);
if (abeof(tword)ocount) error("tnode string too long");
strcpy(tword,w);
left • l;
right • r;
}

Th~ function name tnode .. set spccifies that the function set is a membcr of class tnoèle. This
enables the member namcs word., count, left, and right to be used. In a mcmber function a
member name refcrs to the object for whièh the function was called. Thus, in the call
n 1 • set C ••• ) , tworcl refers to n 1 • tworèl, and in the call n2 • aet ( ••• ) it refers to
n2 •tword. ln this exam.ple, the functions strlen, error, and strcpy are assumed to be
declared clsewhere; see §10.1.
In a member function, the keyword thia points to the object for which the function is called. The
type of thia in a function whièh is the mcmber of a class cl is cl•. If mem is a man.ber of class
cl, mem and thia->mem are synonymous in a class cl member function (unless mem has been
used as the name of a local variable in an intermediate scope).
A member function may be dcfined (§10.1) in the class declaration. Placing a membcr function
definition in the class declaration is just a shorthand for declarlng it in the class declaration and
then detining it inline (§8.1} just after the class declaration. For example:
int b;
atruct x {
int f() { return b; }
int b;
} ;
means
C. int b;
struct x {
int f();
int b;
} ;
inline x.f () { return b; }
C++ Reference Manual 22

The specifier overload (§8.2) need not be used for member funetions: if a name is declared to
dcnote several funetions in a class it is overloaded (see §8.9).

( It is legal to apply the address-of operator to a member function. However, the type of the
resulting pointer to function is undefined, so that any use of it is implementation dependent.
8.5 .3 Derived classes
In the construct
aggr identifier : public0p, typedef-name
the typedef-name must dcnote a previously declared class, which is called a base class for the class
being declared. The latter is said to be derived from. the fonner. For the meaning of public see
§8.5.8. The membcrs of the base class can be referred to as if thcy were members of the derived
class itself, cxcept when a base member name bas been re-defined in the dcrived class; in this case
the typedef-name::iden:ljier notation (§7.1) can be used to refer to the hidden name. For example:
atruot base {
int a, b;
};

struct derived.: public base {


int b, c;
} :
derived d;

d.a • 1;
d. base : : b • 2;
d.b • 3;
d..c • 4;
assigns to the four members of d..
A derived class can itself be used as a base class. lt is not possible to derive from. a union
(§8.5.12). Assignment is not implicitly defined (see §7.14 and §14.1) for a objccts of a class
derived from. a class for which operator• ( ) bas becn defined (§8.S.10).
8.5.4 Virtual functions
If a base class base contains a virtual (§8.1) function vf, and a derived class d.erived. also
contains a function vf then a call of vf for an abject of class de:r:ived invokes de:r:ived: : vf.
For example:
struct base {
virtual void. vf();
void f();
} ;

struct derived.: public base {


void vf C);
void f();
} ;
C++ Reference Manual 23

derived d.;
base• bp • &.d;

bp->vf ();
bp->f ();
The calls invoke derived: :vf and base: :f, respectively for the class derived object named
d. That is, the interp.retation of the call of a virtua1 function depencis on the type of the object for
whicb it is called, whereas the interpretation of a call of a non-virtual member function depends
only on the type of the pointer denoting that object. This implies that the type of objects of classes
with virtual functions and abjects of classes derived from such classes can be determined at run
time.
C If a derived class bas a member of the same name as a virtual function in a base class the its type
must be the same in both classes. A virtual function cannot be a friend (§8.5.9). A function f
in a c:lass derived from a class which has a virtual fonction fis itself considered virtual. A virtua1
function in a base class must be defined. A virtual function which bas been ddined in a base class
nced not be defined in a derived class. ln that case, the function defined for the base class is used
in all œlls.
8.S .S Constructors
A me:mber function with the same name as its class is called a constructor. A consttuctOr has no
retum value type; it is used to construct values of its class type. A constructor can be used to
create new objects of its type, using the syntax
typedef-lllJ:IM ( argument-linopt )

complex zz • complex(1, 2.3);

cprint( complex(7.8, 1.2) );


Objeets created in tbis way are unnamed (unless the constructor was used as an initializer as for
zz above), with their lifetime limited to the scope in which they are created. They can often be
considered constants of their type. If a class has a consttuetor it is called for each object of that
class be.fore any use is mJide of the object; sce §8.6. A constructor may be over load, but not
virtual oi friend.
If a class has a base class with a constructor, the constrUCtor for the base class is called before the
constructor for the derived class. The consttuctors for member objects, if any, are cxecuted after
the constructor for the base class and before the canstructor for the object containing them. See
§10.1 for an explanation of how arguments can be speclfied for a base class constructor, and sec
§17 for an explanation of bow constructors can be used for frce storage management.
An object of a class with a constructor cannot be a membcr of a union.
8.5.6 Conversions
A constructor taking a single argument specifies a conversion from its argument type to the type of
its class. Sucb conversions are used implicitly in addition to the usual arlthmetic conversions. An
assignment to an object of class x is therefore legal if either the assigncd value is an x, or if a
conversion has been declared from the type of the assigned value to x. Constructors are used
similarly for conversion of function arguments (§7.1) and initializers (§8.6). For examplc:
C+ + Reference Ma.nuai 24

claas X { •.. X(int); };


f(X arg) {
X a• 1; /* a • X{ 1) */
(_ a• 2; I• a• X(2) •I
f ( 3); /* f(X(3)) • /
}

When no constructor for class xis found which accepts the assigned type, no attempt is made to
find other constructors to convert the assigned value into a type which would be acceptable to a
constructor for class x. For example:
class X { X( int); } ;
class Y { Y{X); } ;
Y a• 1; I• illegal: Y(X(1)) not tried •I

A member function of a class x with a name of the form


conversion-fa,nction-tllllM:
operatorrype
spedfies a conversion from ryp, to x. It will be used implicitly like the constructors above, or it
can be called explicitly using the œst notation. For example:
claaa X {

operator int();
} ;

X a;
int i • int(a);
i • (int)a;
i • a;
ln all tbree cases the value assigned will be found by a ca1l of the function X: : operator int C) .
A user defined type conversion is implic:itly applied only if it is unique; see §8.9. Note that if a
class x bas a conversion to an integral or pointer type declared, an x can be used whereever an
expression of such a type is required. For example
X a, l:>;
(_ inti• (a)? 1+a: O;
int j • {a&&.l:>)? a+l:>: i;
8.S. 7 Destructors
A membcr fonction of class cl namcd ·cl is called a destructor. A destructor has no retutn
value and takes no arguments; it is used to destroy values of type cl immediatcly before the objeet
containing them is desuoyed. A destructor cannot be ov-erload or friend.
The destructor for a base class is exccutcd after the destructor for its derlvcd class. Destructors
for member abjects are executcd before the desttuctor for the objeet they are members of. See §17
for an explanation of how destructors can be used for free storqe management.
An abject of a class with a destructor cannot be the member of a union.
8.S .8 Visibility of member names
The members of a class declarcd with the keyword claaa are prlvate, that is, their names can
only be used by membcr fonctions (§8.5.2) and friends (see §8.5.10), unless they appear aftcr the
C++ Re/erence Manual 25

"public: n label; in that case they are public. A public member can be uscd in any function. A
struct is a class with an members public; see §8.5.11.
H the keyword public precedes the base class name in the declatation of a derived class the
public members of the base class are public for the derived class; if not, tbey arc private. A public
membcr mem of a private base class base can be declared to be public for the derived class by a
declaration of the form
typede/-1111.1n4 • identifier ;
whcre the typedef-name denotes the base class and the identifier is the name of a member of the
base class. Such a declaration must occ:ur in the public part of the dcrived class.
Consider
claas base {
int a;
public:
int b. c;
int bf();

clasa derived base {


int d;
public:
base.c;
int e;
int df ();
} ;

int ef(derived.L};
The extema1 function ef canuse only the names c, e, and df. Bcing a me:mbcr of derived, the
function df canuse the names b, c, bf, d, e, and df, but nota. Being a me:mber of base, the
function bf canuse the mcmbers a, b, c, and bf.
8.S.9 Friends
A frlend of a class is a non-member function which may use the ptivate member names from the
class. A frlend is not in the scope of a class and is not called using the member selection syntu
(unless it itself is the membcr of some class). The following example illustrates the differences
between membcrs and frlends:
(_ class private {
int a;
friend void friend._set(private•, int);
public:
void mesnl>er_aet(int);
} ;
void friencLaet(pr:l.vate• p, inti) { p->a • i;}
(_ void private.member_aet(int i) {a• i; }
pri vate obj;

friend_set(Lobj,10);

obj.member_set(10);
C++ Reference Manual 26

When a friend declaration refers to an ovcrloaded name or opcrator only the function specified
by the argument types becomes a friend. A member of. a class c 11 can be the frlend of a class
cl2. For example
(_ claaa cl2 {
friend. char• cl1::foo(int);
};

Ail the functions of a class cl 1 can be made friends of a class c 12 by a single declaration
class cl2 {
friend. cl1

};
Placing the definition of a fri end function in a class declaration is a shorthand for declaring it
and tben defining it inline just as for mem.ber functions; see §8.5.2.
8.5 .10 Operator functions
Most operators can be overloaded to take class object operands.
operator-{unction-name:
operator operlUOr

optrator: one of
new delete
A
+
* /
"+• -·
L

"'•
<•

L•
>•
<
,.
L&.
>
<<
Il
>>
++
>>•
••
<<•
()
/•
••
[l

I•

The last two operators are function call and subscrlpting. An operator function (exœpt operator
new() and operator delete( ); see 117) must eitber be a member function or take at least one
argument of class type. See also §7.16.
8.5 .11 Structures
A structure is a class witb all members public. That is
struct • { ••• };
is equivalent to
claas s { public: ••• };
A structure may have member functions (including constructors and desttuctors).
8.5.12 Unions
A union may be tbought of as a structure all of whose mem.ber abjects begin at offset O and whose
size is sufficient to contain any of its member objects. At most one of the member objects can be
stored in a union at any time. A union may have membcr functions (ineluding constructors and
destructors). It is not possible to de.rive a class from a union. An abject of a class with a
constructor or a destructor cannot be a member of a union.
A union of. the form
union { member-list } ;
is called an anonymous union; it defincs an unnamed object. The names of the members of an
C+ + Reference Ma.nuai 27

anon.ymous union must be distinct from other names in the scope where the union is declared; they
can be used directly in that scope without using the usual membcr access syntax (§8.S). For
example
union { int a; char• p; };
a• 1;

p • "asd.f";
Here a and p are used like ordinary (non-member) variables, but since they are union members
they have the same address.
8.5.13 Bit fields
( __ A member-declararor of the form
identifierop, : constant•upression
specifies a field; its length is set off from the field name by a colon. Fields are packed into
machine integers; they do not straddle words. A field which does not fit into the space remaining
in an integer is put into the next word. No field may be wider than a word. Fields are assigned
risht-to-left on some machines, left-to-rlght on other machines; see §2.6.
An unnamed field is useful for padding to conform to extemally-impoed layouts. As a special
case, an mmamed field with a width of Ospecifies alignment of the nm field at a word boundary.
Implementations are not required to support any but integer fields. Moreover, even int fields
may be considered to be unsigned. For these reasons, it is recomme.ndcd that fields be declared as
unsigned. The address-of operator & may not be applicd to thcm, so that there are no pointers
to fields.
Fields may not be union membcrs.
8.5 .14 Nested classes
A class may be declared within another class. ln this case, the scope of the name of the inner class
and its public na.mes is restricted to the enclosing class. Except for this restriction the inner class
could have been declared outside its enclosing class. Declaring a class within another does not
affect the rules for acœss to private members, nor does it place the member functions of the inner
class in the scope of the enclosing class. For example:
int x;

class encloae {
int x;
class inner {
int y;
f () { X • 1; }

} ;
g( inner*);

} ;

int inner;

enclose.g{inner* p) { ••• }
ln this example, the x in f refers to the x declared before class enclose. Sincey is a private
member of inner, c; can not use it. Si.nec c; is a member of enclose, names used in c; are
C++ Reference ManUD,/ 28

resolved in the scope of class enclose. Thereforc inne:r in the argument declaration for 9' refers
to the enclosed type inner, and Dot to the int.
(_ 8.6 lnitializati.on
A declarator may spccify an initial value for the identifier being declared. The initializer is
preœded by •, and consists of an expression or a list of values nested in braces.
initia/izer:
• expression
• { initializer-li.n }
• { initializer-lisi , }
( upr,ssion-li.n >
initializer-list:
expression
initializer-li.n • initiali:er-li.n
{ initializer-lisi }
All the expressions in an initializer for a static or enemal variable must be constant expressions,
which are described in §15, or expressions which reduce to the address of a previously declared
variable, possibly offset by a constant expression. Autom.atic or register variables may be
initialized by arbittary expressions involving constantst previously declared variables and functions.
Static and cxternal variables which are not initialized are guanmtced to start off as .O; automatic
and register variables which are not initialized are guaranteed to stan off as prbage.
\Vhen an initializer applies to a scalar (a pointer or an object of arithmetic type), it consists of a
single expression, perhaps in braces. The initial value of the object is taken from the expression;
the same conversions as for assignment are performed.
Note that sinœ < ) is not an initializer, ' 'X a C) ; ' ' is not the dcclatation of an object of class x,
but the declaration of a function taking no argument and returning an x.
8.6 .1 Initializer lists
\Vhen the declared variable is an aggregate (a class or an array) then the initializcr may consist of
a brace-enclosed, comma-separated list of initializers for the members of the aggregate, writtcm in
incrcasing subscript or member ordcr. If the array contains subaggregates, this rule applies
recursively to the members of the aggregate. If there are fewer initializers in the list than tbere
are members of the aggregate, then the aggregate is padded with O's.
Braces may be elided as follows. If the initializer begins with a lcft bracc, then the s1Jœetding
(_ comma-separated list of initializers initi.alizes the membcrs of the aggrcgate; it is erroneous for
there to be more initializers than members. If, however, the initializer does Dot. begin with a left
braœ, tben only eDough clements from the list are taken to account for the members of the
aggregate; any remaining members arc left to initialize the ncxt member of the agregate of which
the current aggregate is a part.
For example,
int xCl • { 1 1 3, 5 };
declares and initializes x as a 1-dimensional array which bas three members, since no size was
spec:ified and there are thrce initializers.
C++ Reference Manual 29

..
float y[4]C3] • {
{ 1' 3, s }
(
-- { 2, 4, 6 }
\__ . { 3, s. 7 } ,
} ;
is a completely-bracketed initialization: 1, 3, and S initialize the first row of the array y[ o],
namely y t OH oJ, y t OJt 1 J, and y t Olt 2 l. Likewise the next two Unes initialize y t 1 J and
y[ 2 J. The initializer ends early and therefore y[ 3 J is initialized with O. Precisdy the same
effect could have bcen achieved by
float yt4][3J • {
1, 3, s, 2, 4, 6, 3, 5, 7
} ;
The initializer for y begins with a left brace, but that for y [ o ] does not, therefore three dements
from the list are used. Likewise the next three are taken successively for y t 1 J and y[ 2 J• Also,
float y[4l[3J • {
{ 1 }, { 2 }, { 3 }, { 4}
};

initializes the first column of y (regarded as a two-dimensional array) and leaves the rest O.
8.6.2 Cass objects
An object with private mcmbers cannot be initialized by simple assignment to its members as
descrlbed above; neither can a union object. An abject of a class with a constructor must be
initialized. If a class bas a construetor which does not take arguments tbat constructor is used for
abjects which are not explicitly initialized.
The arsuments for a constructor can also be presented as a paremhesized list; this style must be
used when creatina objects on the frce store. For example:
struct complex {
float re, im;
complex(float r, float i) { re•r; im•i; }
complex(float r) { re•r; im•O; }
} ;

complex zz(1, 2.3);


complex* zp • new complex(1, 2.3);
(_ lnitialization can also be performed by explicit assignment; conversions are performed. For
example,
complex zz1 • complex(1, 2.3);
complex zz2 • complex(123);
complex zz3 • 123;
complex zz4 • zz3;
If a construetor taking a reference to an object of its own class exists, it will be invoked when an
object is initialized with another object of that class, but Dot when an object is initialized with a
constructor.
An object can be a member of an agregate only if the object's class does not have a c:onstructor or
if one of its .constructors talc.es no arguments. In the latter case that consttuctor is called when the
aggregate is cre.ated. If a member of an aggregate is of a class witb a destructtJr tben that
destructor is called when the aggregate is destroycd.
C+ + Reference Manual 30

8.6.3 References
\Vhen a variable is declared to be a TL, that is "reference to type 'l'", it can be initialized either by
C a pointer to type T, or by an object of type 'l'. ln the latter case the address-of operator L will be
implicltly applied. For example:
inti;
intL r1 • i;
intL r2 • Li;
Both r 1 and r 2 will referenœ i.
lnitialization of a referenœ is ueated very differently from assignment toit. As descrlbed in §7.1 a
reference is implicitly dereferenced when used. For example
r1 • r2;
means copy the integer referenced by r2 into the integer referenœd by r 1.
A rc:ference must be initialized. Bccause of the implicit dereferencing the value of a referenœ
cannot be changed after initialization. A reference can therefore be thought of as a name of an
object.
The expression Lr 1 yields the addtess of the object refcnnœd by r 1. Thus to get a pointer pp to
denote the same abject as r1 one can wrlte pp•LJ:1.
If the initializer for a reference to type T is not an lvalue an object of type T will be created and
initiaJiz,-_,d wiih the initializer using the usual initialization rules. The addrcss of that object then
beeomes the value of the referenœ. 'Ibe lifetime of an abject created in this way is the scope in
which it is created. For eumple:
doubleL rr • 1 ;
is legal and tt will point to a double containing the value 1 • 0.
Refercnces are particularly useful as formal argument types.
8.6.4 Character arr~ys
A final abbrcviation allows a char array to be initialized by a string. In this case suc:œssive
characters of. the string initialize me members of the array. For esample,
char msg[] • nsyntax error on line Ka,n•;
shows a c:baracter array whœe members are initializcd with a string.
8.7 Type namcs
Sometimes (to specify type conversions explicitly, and as an argument of s:Lzeof or new) it is
desired to supply the name of a data type. This is acc:omplished usina a "type name," which in
essence is a declaration for an object of that type which omi.ts the name of the object.
type-name:
ryp,-sp,cifier abnract-declararor
aburact-declarator:
empty
* abmact-declarator
abnract-declarator ( argument-declaration-list )
aburact-declarator C consram-expnssionopt J
C abstract-decla:rator )

It is possible to identify uniquely the location in the abstract-declarator where the identifier would
appear if the construction were a declarator in a declaration. The named type is then the same as
the type of the hypothetical identifier. For example,
\
C+ + Reference Manual 31

int
int *
int •[3J
(~ int •()
int ( •) ()
name respectively the types "integer," "pointer to integer," "pointer to an array of three
integers," "function returning pointer to integer," and "pointer to function returning an integer."
8.8 Typedef
Declarations containing the decl-specijier typedef define identifiers which can be used later as if
they were type keywords naming fundamental or derived types.
(_
typedef-'fl/J'IM:
ideruifler
Within the scope of a declaration involving typedef, eacb identifier appearing as part of any
declarator therein becomes syntactically equivalent to the type keyword naming the type associated
with the identifier in the way dcscribed in §8.4. The name of a class or an enum is also a rypedef-
'fl/J'IM • For example, after
typedef int MILES, •ICLICICSP;
struct complex { double re. im; };
the constructions
MILES distance;
extern KLICKSP metricp;
complex z, •zp;
are all legal declarations; the type of distance is int, that of metricp is "pointer to int".
typed.ef does not inttoduce brand new types, only synonyms for types which could be specified in
another way. Thus in the example above distance is considered to have exactly the same type
as any other int abject.
A class declaration, however, does introduœ a new type. For eumple:
struct X { int a; };
atruct Y { int a;};
X a1;
y a.2;
int a3;
declares three variables of three diffcrent types.
A declaration of the form
name-declaration:
a,gr ùkntifer ;
enum identifier ;
specifies that an identifier is the name of some (possibly not yet defined) class or enumeration.
C Such declarations allows declaration of classes which refer to eacb other. For example:
C++ Reference Manual 32

class vector;

class matrix {
(_
friend matrix operator•(matrixL, vector&);
} ;

elass vector {

friend matrix operator•Cmatrix&, vector&);


} ;
(_ 8.9 Overloaded function names
When several (different} function dcclarations are specified for a single na.me, that name is said to
be overloaded. When that name is uscd, the correct function is selected by comparing the types of
the actual arguments with the argument types in the function declarations.
Of the usual arithmetic conversions defined in §6.6 only the conversions char->short->int, int-
>double, int->long, and jloat->double are performed for a call of an overloaded function. To
overload the name of a non-member funetion an overload declaration must precede any
declaration of the function; see §8.2. For example,
overload aba;
int abs ( i.nt ) ;
double abs(double);
When an overloaded name is called, the list of functions is scanned in order to find one which can
be invokcd. For example abs C12) will invoke abs Cint) and abs ( 12 .. O) will invoke
abs ( double ) . Had the order of declarations been reversed, both calls would have invoked
abs (double) .
If, for a call of an overloadcd name, no function is found by the method above, the set of user-
defined conversions (§8.S.6) is examined. If tbere is a unique set of user-defined conversions
which maltes the call legal, it is implicitly applied. For example:
claaa X { X(int); };
claaa Y { Y( int) ; } ;
class z { Z(char*)i };

overload int f(X), f(Y);


overload int g(X), g(Z);

f ( 1) ; I• illegal: ambiguous f(X(1)) or f(Y(1)) •/


g( 1) ; I• g(X(1)) •/
g( "asdf"); /• g(Z{"asdf")) •I

All operator function names are automatically overloaded.


The address-of operator & may only be applied to an overloaded name in an assignment or an
initialization where the type expected determines which function to take the address of. For
example:
int operator•Cmatrix&, matrix&.);
int operator•(vector&, vector&);
int (•pfm)(matrix&., matrix&) • &operator•;
int C•pfv)(veetor&, veetor&) • &operator•;
int (•pfx)( ••• ) • &operator•; I• error •I
C+ + Rejerence Manual 33

8.10 Enumeration decl.arations


Enumerations are int types with named constants.
enum-sptcifier:
enum id,mijieropt { enum-list }

enum-li.st:
enumerator
,mum-lin , enumerator

enumerator:
identifier
identifier • connani-upression
The identîfiers in an enum-list are declared as constants, and may appear wherever constants are
required. If no enumerators with • appear, then the values of the corresponding constants begin at
0 and increase by 1 as the declaration is read from left-to-right. An enumerator with • gives the
associated identifier the value indiœted; subsequent identifiers continue the progression from the
assigned value.
The names of enumerators must be distinct from those of ordinary variables. The· names of
enumcrators with different CODStants must also be distinct. The values ot the enumerators need
not be distinct.
The role of the identifier in the enum-specifier is entircly analogous to that of the class name; it
names a particular enumeration. For example,
enum color { chartreuse, burgundy, claret•20, wine4ark }:

color *CP, col;

col• claret;
cp • &.col;

if (•cp •• burgun4y) •••


makes color the name of a type descrlbing various colors, and then declares cp as a pointer to an
object of that type, and col as an object of that type. The possible values are drawn from the set
{O, 1, 20, 21}.
8.11 Asm declaration
An asm declaration bas the form
asm ( string ) ;

The meaning of an asm decl.aration is not defined. Typically it is used to pass information tbrough
the compiler to an assembler.
9. STATEMENTS
(_ Except as in~cated, statements are exccuted in sequenœ.
9.1 Expression statement
Most statements are expression statements, which have the form
expression ;
Usually expression statements are assig:nments or function calls.
C+ + Reference Manual 34

9.2 Compound statement, or black


So that several statements can be used where one is expected, the compound statement (also, and
equivalently, called "block") is provided:
compount:1-statement:
{ mnement-llnopt }

statement-lin:
statement
statement statement-list
Note that a declaration is an example of a statement (§9.15).
9.3 Conditional statemcnt
The two forms of the conditional statement are
if ( expression ) IUltement
if { expression ) natement elae na,ement
The expression must be of in'tegral or pointer type or of a class type for which a conversion to
integral or pointer type is defined (sec §8.5.6). The expression is evaluated and if it is non-zero,
the fint substatement is cxecuted. If else is used the second substatement is exccuted if the
expression is O. As usual the 0 else0 ambiguity is resolved by connecting an elee with the last
encountered else-less if.
9.4 While statemcnt
The while statement bas the form
while ( apression ) statement
The substatement is executed repeatedly so long as the value of the expression remains non-zero.
The test takes place before each e:xecution of the statement. The expression is handled as in a
conditional statement (§9.3).
9.5 Do statemcnt
The d.o statement bas the form
d.o staiement while C expression ) ;
The substatement is executed repeatedly until the value of the expression becomes zero. The test
takes place after each execution of the statement. The expression is handled as in a conditional
statement (§9 .3).
9.6 For stàtement
The for statement bas the form
for ( natement-1 apression-1 opt expression-2opt ) sttJlement-2
This statement is equivalent to
statement-1
wbil e ( expression-1 ) {
statement-2
expression-2 ;
}

Thus the first statement specifies initialization for the loop; the first expression speclfies a test,
made before each iteration, such that the loop is exited when the expression becomes O; the second
expression often specifies an incrementing that is performcd after each iteration.
C++ Reference Manual 35

Either or both of the expressions may be dropped. A missing expression-} makes the implied
while clause equivalent to while ( 1). Note that if statement-1 is a declaration, the scope of the
name dcclared extends to the end of the block enclosing the for-statement.
C 9. 7 Switch statement
Toc swi tch statement causes control to be transferred to one of several statements depending on
the value of an expression. It bas the form
swi tch ( expression ) statement
The type of the expression must be of integral or pointer type. Any statement within the statement
may be labeled with one or more case prefixes as follows:
( case constant-expression :
'---
where the constant expression must be of the samc type as the switch expression; the usual
arithmetic conversions are performed. No two of the case constants in the same switch may have
the same value. Constant expressions are defined in §15.
There may also be at most one statement prefix of the form
default:
When the switeh statement is executed, its expression is evaluated and compared with eacb case
constant. If one of the case constants is equal to the value of the expression, control is passed to
the statement following the matched case prefix. If no case constant matclles the expression, and if
there is a default prefix, control passes to the prefixed statement. If no case matches and if
there is no def aul t then none of the statements in the switch is executed.
case and def aul t prefixcs in thcmselves do not alter the flow of control, whicll continues
unimpeded across such prefixes. To exit from. a switch, sec break, §9.8.
Usually the statement that is the subject of a switch is compound. Declarations may appear at the
head of this statement, but initializations of automatic or register variables are ineffective.
9.8 Break statement
The statement
break;
causes termination of the smallest enclosing while, do, for, or switch statement; control passes
to the statemcnt following the terminated statement.
9.9 Continue statement
The statement
continue;
causes control to pass to the loop-continuation portion of the smallest enclosing while, do, or for
statement; that is to the end of the loop. More preclsely, in each of the statements
while ( •.• ) { do { for( ••• ) {

eontin: ; contin: .' contin: ;


} } while ( ... ) ; }

a continue is·equivalent to goto eontin. (Following the contin: is a null statement, 19.13.)
9.10 Return statement
A function retums toits caller by mcans of the return statement, which bas one of the forms
C+ + Reference Manual 36

return;
return a.pression
The fi.nt form can be uscd only in functions which does not retum a value, that is, a function with
the retum value type void. The second form can be used only in fonctions retuming a value; the
value of the expression is retumed to the caller of the function. If required, the expression is
converted, as in an initialization, to the type of the function in wlûch it appears. Flowing off the
end of a function is equivalent to a retum with no retumed value.
9.11 Goto statement
Control may be transferred unconditionally by means of the statement
goto identifier ;
The identifier must be a label (§9.12) located in the current fonction. lt is not possible to transfer
cœtrol past a declaration with an (implicit or explict) initializer.
9.12 Labeled statement
Any statement may be preceded by label prefixes of the form
identifier :
which serve to declare the identifier as a label. The only use of a label is as a target of a goto.
The scope of a label is the current function, excluding any sub-blocks in which the same identifier
bas been redeclared. See §4.l.
9.13 Null statement
The null statemcnt bas the form

A null statement is useful to carry a label just before the } of a compound statement or to supply a
null body to a looping statement such as while.
9.14 Deletc statement
The delete statement bas the form
del ete expression
The result of the expression must be a pointer. The object pointed to is deleted. That is, after the
delete statement the object cannot be assured to have a well de:fined value; see §17. The effect of
applying delete to a pointer not obtained from the new operator (§7.1) is unddined. However,
(_ deletin& a pointer with the value zero is harmless.
9.15 Declaration statement
A declaration statement is used to introduce a new identifier into a black; it has the form
declaration-staremtnt:
declaration
If an identifier introduœd by a declaration wcre previously declared, the outer declaration is
pushed down for the duration of the black, after which it resumes its force.
Any initializations of auto or register variables are performed cach time their t:kclaration-
statement is executed. lt is possible to transfêr into a block, but not in a way that causes
initializations not to be performed; see §9 .11. lnitializations of variables with storage class natic
(§4.2) are performed only once when the program begins execution.
C++ Reference Manual 37

10. EXTERNAL DEFINITIONS


A program consists of a scquence of extcmal de:finitions. The scopc of encrnal definitions persists
to the end of the file in which thcy are declared. The syntax of extemal definitions is the same as
(~_ that of declarations, except that only at this level and within elass declarations may the code for
functions be given.
10.1 Function definitions
Function definitions have the form
function-definition:
decl-specifiersopt function-declarator base-class-initiali:er0,,function-body
The decl-specifiers re;ister, auto, typedef may not be used, and friend, and virtual may
only be used within a class dcclaration (§8.5). A function declarator is similar to a declarator for a
"function retuming ... " except that it includes the names of the formai patameters of the function
being defined. Function declarators have the form
function-declarator:
declarator < argurMnt-d,claration-llst )
The form of an argUtMnt-declaration-list is spedfied in §8.4. If an argument is spedfied
register, the corresponc:ting actual parameter wil1 be copied, if possfüle, into a register at the
outset of the function. If a constant expression is spec1fied as initializer for an argument this value
is used as a default argument value.
The function-body bas the form
junction-body:
compound-stateTMnt
A simple example of a complete function definition is
int max(int a, int b, int c)
{
int m • ( a > b)? a: b;
return (m > c)? m: c;
}

Here int is the type-speclfier; max ( int a , int b, int c ) is the function-declarator; { • • • }
is the block giving the code for the statement.
Since in expression context an array name (in particular as an actual parameter) is taken to mean a
(_ pointer to the first element of the array, declarations of formal parameters declared "array of ••• "
are adjusted to read "pointer to ... ".
A base class initializer bas the form
bas,-class-inhializer:
: ( argument-li#Opt
lt is used to spccify arguments for a base class constructor in a consuuctor for a derived class. For
example:
struct base { baae(int); ••• };
struet d.erived: baae { d.eriTed.(int); };

derived.derived(int a) : (a+1) { ••• }

der i ved d ( 10 ) ;
The base class's constructor is callcd for the object d. witb the argument 11.
C++ Refertnce Manual 38

10.2 Extemal data definitions


An cxternal data definition bas the form
data-dt.finition.:
declaratlon
The storage class of such data is static.
If there is more than one extemal data definition of the samc nam.e, the dcfinitions must agree
exactly in type and storage class and all initializers (if any) must have the same value.

11. SCOPE RULES


See §4.1.

12. COMPil..ER CONIROL LINES


The compiler contains a preprocessor capable of macro substitution, conditional compilation, and
inclusion of named files. Lines beginning with # communicate with tbis preprocessor. Tbese lines
have syntaX independent of the rest of the. languagc; they may appear anywhere and have effect
which lasts (independent of scope} until the end of the source program file.
Note that const and inline definitions provide alternatives to most uses of #def ine.
12.1 Token replacement
A compiler-control line of the form
#def ine identifier ro/œn-srring
causes the preprocessor to replace subsequent instances of the identifier with the given stting of
tokens. Semi.colons in, or at the end of, the taken-stting are part of that string. Aline of the
form
#define Identifier( idtntijier , • • • , idtntlfter ) to/œn-string
where there is no space betwecn the first identifier and the ( , is a macro definition with
arguments. Subsequent instances of the first identifier followed by a C, a sequenœ of tokens
delimited by commas, and a ) are replaccd by the token string in the definition. Each occurrence
of an identifier mentioned in the formal parametcr list of the definition is replaced by the
corresponding token string from the call. The actual arguments in the call are token strings
separated by commas; however commas in quoted strings or protected by parentheses do not
separatc arguments. The number of forma! and actua1 parameten must be the same. Strings and
character constants in the tolcen-string are scanned for formal parameters, but strings and character
constants in the rest of the program are not scanncd for defined identifiers.
ln both forms the replacement string is rescanned for more defined identifiers. In both forms a
long definition may be continued on another line by 'Wri.ting \ at the end of the line to be
continued. A control line of the form
#undef idemifter
causes the identifier's prcprocessor definition to be forgotten.
12.2 File inclusion
A compiler conttol line of the form
#inclu.d.e "flltnamt"
causes the replacement of that line by the entire contents of the file flltname. The namcd file is
searched for first in the directory of the original source file, and then in a sequence of specified or
standard places. Alternatively, a conttol line of the form
C++ Reference Manual 39

#includ.e <Jilename >


searches only the speclfied or standard places, and not the directory of the source file. (How the
places are specified is not part of the language.)
#include's may be nested.
12.3 Conditional compilation
A compiler conttol line of the form
#if expression
checks wbether the expression evaluates to non•zero. The expression must be a constant
expression as diseussed in §15; the following additional restriction applies bere: the constant
expression-may not contain aizeof or an enumeration constant.) In addition to the usual C++
opcrations a unary operator defined can be used. Wh.en applied to an identifier, its value is non·
zero if that identifier bas becn defined using #def ine and not later undefined usmg lund.ef;
otherwise its value is 0. A control line of the form
#ifd.ef idtmifter
checks whether the identifier is currently defined in the preprocessor; that is, whether it bas been
the subject of a #d.efine conttol line. A conttol line of the form
#ifnd.ef identifier
checks wbether the identifier is currently undefined in the prcprocessor.
All three foms are followed by an arbitrary number of lines, possibly containing a control line
#else
and then by a control line
#end.if
If the cbecked condition is true thcn any lines between #elae and #end.if are ignored. If the
cbccked condition is false then any lines between the test and an lelse or, lacldng an #elae, the
#end.if, are ignored.
'Ihese constructions may be nested.
12.4 Une control
For the benefit of other preprocessors wbicb gcnerate C++ programs, a line of the form
#line constant "ftlenam,"
causes the compiler to believc, far purposes of error diagnostics, that the line number of the next
source line is given by the constant and the current input file is named by the identifier. If the
identifier is absent the remembered file name does not change.

13. IMPLICIT DECl.ARATIONS


See 18.1.

14. TYPES REVISITED


This section summarizes the operations wbicb can be performed on objects of certain types.
14.1 Casses
Qass objects may be assigned, passed as arguments to functions, and retumed by functions (cxcept
objects of somc derlved classes; sec §8.S.3). Other plausible operators, sucb as equality
comparison, can be defined by the user: sec §8.5.10.
C+ + Reference Manual 40

14.2 Functions
There are only two things that can be done witb a function: call it, or take its add:ress. If the name
of a fun.ction appears in an expression not in the function-name position of a call, a pointer to the
function is generated. Thus, to pass one function to another, one might say
type4ef int (•PP)();
extern g(PP);
extern f();

g(f);
Then the defmition of g might read
g(PF funcp)
{

(* f uncp ) ( ) ;
}

Notice tbat f must be declared explicitly in the calling routine since its appearance in g cf) was
not followed by C•
14.3 Arrays, pointers, and subscripting
Every time an identifier of array type appears in an expression, it is convcned into a pointer to the
first member of the array. Because of this conversion, arrays are not !values. By definition, the
subscript operator [ J is interpreted in such a way tbat E 1 [ !2 J is identical to • C C11 >+ C12 ) ) .
Beœuse of the conversion rules which apply to +, if E 1 is an array and E2 an integer, thcn
E 1 rE2 l refen to the E2-th member of E 1. 'Iherefore, despite its asymmetric appcarance,
subscripting is a commutative operation.
A consistent rule is followed in the case of multi-dimensianal arrays. If E is an n-dimensional
array of rank i x j x · · · x k, then E appearing in an expression is converted to a pointer to an
(n -1 )-dimcnsional array with rank Jx · · · x k. If the * operator, either explicitly or ùnplicitly as
a result of subscripting, is applied to this pointer, the result is the pointed-to (n-1)-dimensional
array, which itself is immediately converted into a pointer.
For exam.ple, consider
int x[3][5J;
Here x is a 3 x 5 array of integers. When x appean in an expression, it is convened to a pointer
to (the fint of three) 5-membered arrays of integen. In the expression xt i J, which is equivalent
to * Cx+ i ) , x is first converted to a pointer as described; then 1 is eonvened to the type of x,
which involves multiplying i by the length the object to wbich the pointer points, namely 5 integer
objects. The results are added and indirection applied to yield an array (of 5 integen) which in
turn is converted to a pointer to the fim of the integen. If there is another subscrlpt the sam.e
argument applies again; this time the result is an integer.
It follows from all this that arrays in C++ are stored row-wise (last subscript varies fastest) and
that the first subscript in the dcclaration helps determine the amount of storage consumed by an
array but plays no other part in subscrlpt calculations.
14.4 Explicit pointer conversions
Certain conversions involving pointers are permitted but bave ùnplementation-dependent aspects.
They are all specified by means of an explicit type-conversion operator, §§7 .2 and 8.7.
C+ + Reference Manu.al 41

A pointer may be converted to any of the integral types large enough to hold it. 'Wbether an int
or long is required is machine depcndent. The mapping function is also machine dependent, but
is intended to be unsurprising to those who know the addressing structure of the machine. Details
C_ for some particular machines were given in §2.6.
An object of integral type may be explicitly converted to a pointer. The mapping always carries an
integer converted from a pointer back to the same pointer, but is otherwise machine dependent.
A pointer to one type may be converted to a pointer to another type. The resulting pointer may
cause addressing exceptions upon use if the subject pointer does not refer to an object suitably
aligned in storage. It is guaranteed that a pointer to an object of a given size may be converted to
a pointer to an object of a smaller size and back again without change. Different machines may
differ in the number of bits in pointers and in alignment requirements for objects. Aggregates are
aligned on the strictest boundary required by any of their constituents.

15. CONSTANT EXPRESSIONS


In several places C++ requires expressions whicb evaluate to a constant: as array bounds (§8.3),
as case expressions (§9.7), as default function arguments (§8.3), and in initializers (§8.6). In the
first case, the expression can involve only integer constants, cbaracter constants, enumeration
constants, names declared conat, and sizeof expressions, possfbly connected by the binary
operators
+ - * I " & A << >> •• J• < > <• >• && If
or by the unary operators
- -
or by the temary operator
?:
Parentheses can be used for grouping, but not for function calls.
More latitude is permitted for the other three uses; besides constant expressions as discussed
above, float constants are pennitted, and one can also apply the unary & operator to extemal or
static object:s, or to external or stati.c arrays subscdptecl with a constant expression. The unary &.
can also be applied implicitly by appearance of unsubscripœd mays and functions. The basic rule
is that initializers must evaluate either to a constant or to the address of a previously dcclared
extemal or static object plus or minus a constant.
Lcss latitude is allowed for constant expressions after #if; names declared const, aizeof
expressions, and enumeration constants are not pennitted.

16. PORTABll..!IY CONSIDERATIONS


Certain parts of C+ + are inherently machine dependent. The following list of potential trouble
spots is not ma.nt to be all-inclusive, but to point out the main ones.
Purely hardware issues like word size and the properties of floating point arltbmetic and integer
division have proven in practice to be not much of a problem. Other facets of the hardware are
( reflected in differing implementations. Some of tbese, particularly sign extension (converting a
\...._ negative character into a negative integer) and the order in whicb bytes are plaœd in a word, are a
nuisance that must be carefully watched. Most of the others are only minor problems.
The number of :regiater variables that can actually be placed in registers varies from machine to
machine, as does the set of valid types. Nonetheless, the compilers ail do things properly for their
own machine; excess or invalid registe:r declarations are ignored.
C+ + Re/erence Manu.al 42

Some difficultics arise only when dubious coding practices are used. It is exceedingly unwise to
writc programs that dcpcnd on any of thesc propcrties.

C The ordcr of evaluation of function arguments is not specificd by the languagc. It is right-to-lcft
on somc machines lcft-to-right on othcrs. The ordcr in which sidc effects tak.e place is also
unspecificd.
Since charactcr constants arc rcally abjects of type int, multi-character charactcr constants may be
permitted. Toc specific implementation is very machine dependent, howevcr, because the order in
which characters arc assigncd to a word varies from one machine to anothcr. On some machines
fields are assigned left-to-right in a word, in othcrs right-to-lcft.
Toese differences are invisible to isolated programs which do not indulge in type punning (for
example, by converting an int pointer to a char pointer and inspecting the pointed-to storage),
but must be accounted for when conforming to externally-imposed storage layouts.

17. FREE·STORE
The new operator (§7.2) will call the function
extern void* operator new(lon;);
to obtain storage. The argument specifies the numbcr of bytes requircd. The store will be
uninitializcd. H operator newC ) cannot find the amount of store required it will return zero.
The delete operator will call the function
extern void operator delete(void*)i
to free the store pointed to for re-use. The effcct of c.alling operator delete C ) for a pointer not
obtained from operator new() is undefincd, and so is the effect of calling operator
del ete C) twice for the same pointer. However, deleting a pointer with the value zero is
harmless.
Default versions of operator new() and operator delete() are provided, but a user may
supply othcrs more suitable for parti.cular applications.
\Vhen a class object is created using the new operatot the constructor will (implicitly) use
operator newC) to obtain the store needed. By assigning to the thi• pointer before any use of
a member a constructor can implement its own storage allocation. By assigning a zero value to
tbis, a destructor can avoid the standard dcallocation operation for objects of its class. For
example:
class cl {
int v[ 10];
cl() { this • my_own_alloeator( sizeof(cl) ); }
·cl{) { my_own_deallocator( thia ); this • O; }
}

On entry into a constructor tbis is non-zero if allocation has already tak.en place (as is the case
for auto objects) and zero othcrwise.
If a derived class assigns to this, the call to its base class's constructor (if any) w:ill take place
after the assignment so that the base class constructor will refcr to the object allocated by the
derived class's constructor. Ha base class's constructor assigns to thia, the new value will also be
uscd by the dcrived class's constructor (if any).

18. SYNTAXSUMMAY
This summary of C+ + syntax is intendcd to be an aid to comprehension. lt is not an exact
statement of the language.
C+ + Reference ManUlll 43

18.1 Experessions
expression:
term
C expression binary-operator expression
expression ? expression : expression
expression-list
term:
primary
• term
& rerm
- term
1 term
• term
++ term
-- term
term ++
term --
< ryp.-nam, ) expression
simple-rype-na:me ( u.pression-ltst )
aizeof expression
sizeof ( type-nome
11ew type-name
new C rype-nam, )
primary:
id
: : identifier
cannant
string
thia
C upression )
primary [ expression ]
primary ( expression-Jinopt )
primary • id
primary - > id
id:
identifier
operaror-function-name
typedef-nam, : : tdenrijier
typedef-111l1M : : operaror-function-~
expression-list:
expression
expression-lin , expression
operator:
unary-operator
binary-operaror
special-operaror
free-store-operœor
Binary operators have preœd=nce decreasing as indicated:
C+ + Referenct Manua.l 44

binary-operator: one of
*
+
/
"
<< >>
C >
•• f•
&
A

ll
If
• +•
-· *· /• "• •• ,. >>• <<•
una:ry-operator: one of
* & ++

speciaJ.operator: one of
() [l
jree-store-operator: one of
new delete
type-name:
tkcl-sp,cijiers absrract.tüclarator
abstract-declarator:
m,,pty
• abstract-dtclarator
abstract-declarator ( argumenr-declaration-li&t )
abstract-declarator [ connanr-,xpreuionopt J
simple-rype-name:
typedef-name
char
short
int
long
unaigned
f'loat
double
void
typedef-name:
idtntlfler
18.2 Declarations
declaration:
tkcl-specifiersqpt declarator-linOJJI ;
name-declaration
asm-declaration
C+ + Reference Manual 45

nam.e-declaration:
aggr identifier ;
enum identifier ;

aggr:
claaa
at:ruct
union
asm-declaration:
asm ( string ) ;
decl-specifiers:
decl-sp,cifier decl-specijiersopt
decl-specijier:
ss-sp,dfter
type-sp,cifter
fct-specijier
f:riend.
typed.ef
rype-sp,cif~r
simple-rype-name
class-specijier
enum-speciji,r
conat
ss-specijier:
auto
exte:rn
:rec;iate:r
static
fct-specifler:
il'lline
ove:rload.
vi:rtual
declarator-list:
init-declarator
init-declaraior , declarator-list
init-declarator:
declarator initializeropt
declarator:
dname
C declarator )
* conat , declarator
&. constop, declarator
0
declarator ~ argument-declaration-list
declarator [ con.nant-upresslonopt l
C+ + Reference Man'Ulll 46

dname:
simplt-dnam.6
typedef-1111m1 • simple-dname
c_ simple-dname:
identifter
typedef·Nlm.6
• typede/-1111.lM
operaror-function-name
conversion-funclion-name

operaror-function-name:
operator operaror

conversion-function-name:
operator type
argument-declararion-list:
11rg-declaralion-listopt ••• opt

11rg-declaralion-list:
arg-declaration-llst , argument-declara:don
argument-declararion

11rgument-declaralion:
dec/-speciflers declararor
decl-specifters declararor • constant-expression
class-specljier:
class-head { member-lisr t }
class-head { member-lisr°:,, public : member-lisr0 pt }
class-h,ad:
aggr identijier 1
aggr identijier: , : publieopt typedef-nam11
member-list:
membu-declaralion member-listop,

member-declararion:
decl-speciflersont member-declarator initializer t
• .JJ:•. r
fu nction-u., •
1 ".itton ; opt

member-declararor:
declararor
identifteropt consrant-expression
initializtr:
• expression
• { initializer-lisr }
• { initializer•lisr , }
( upression•list )
C+ + Reference Manual 47

initializer-li.rt:
expression
initializer-list , initializer-list
{ initializer-list }
enum-specifier:
enum identifieropt { enum-list }

enum-list:
enumerator
enum-list , enumerator

(_ enumerator:
identifier
identifier• constant-expression
18.3 Statements
compound-statement:
{ st11.tement-listopt }
statement-list:
St/1.tement
sttztement statement-list
sttztement:
declaration
expression :
if ( expression ) statement
if ( expression ) statement else statement
whi le ( expression ) statement
do statemenr while ( expression ) ;
for ( statement expression01Jt ; exprusiono. t ) statement
swi tch ( expression ) statement "
case constant-expnssion : statemem
default : statement
break:
continue;
return expression t
goto identifier ; op
identifier : statement
(_ del ete expression

18.4 External definitions


program:
external-definition
external-definhion program

exterMl-definition:
function-definition
declaration

)
C++ Reference Manual 48

juncrion-definition:
decl-specifiersopt function-declarator base-class-initializeroptfunction-body

function-declarator:
declarator < argument-declaration-list )

function-body:
compound-statement

base-class-initializtr:
: ( argument-listopt
18.5 Preprocessor
#define identr'fier token-string
#define identifier ( identr'jier , •.• , identifier ) tolœn•string
#else
#end.if
#if expression
#ifdef identifier
#ifndef identifier
#include " fiœna.me "
#inelude < filenam, •
#line constant" filename"
#undej identifier

19. DIFFERENCES FROM C


19.1 Extensions
The types of function arguments can be specified (§8.4) and will be checked (§7.1). Type
conversions will be performed (17.1).
Single-precision floating aritbmetic may be used for float expressions; §6.2.
Function names œn be ovcrloaded; §8.6.
Operators can be overloaded; §7 .16, §8.5.10.
Functions can be inline substituted; §8.1.
Data objccts can be const; §8.3.
Objects of reference type can be declared; §8.3, §8.6.3.
A free store is providcd by the new and delete operators; §17.
Casses can providc data hiding (§8.5.8), guaranteed initialization (§8.6.2), user-defined
conversions (§8.S.6), and dynamic typing tbrougb use of virtual functions (§8.S.4).
'Ibe name of a class is a type name; §8.S.
Any pointer can be assigned to a void• without use of a cast; §7.14.
A declaration within a block is a statement; §9.15.
Anonomous unions can be declared; 18.5.12.
19.2 Summary of incompatibilities
Most constructs in C are legal in C+ + witb their meaning unehanged. The exceptions are as
follows
C++ Reference Manual 49

Programs using one of the new keywords


class const d.elete frienél inline
new operator overload public this virtual
as identifiers are not legal.
The function declaration
f ();
means that f taltes no arguments, in C it means that f could take arguments of any type at all.
The default scope of a name declared outside any block or class is file; in C it was program. This
implies that to make a name visible to functions in other files a name must explicitly be declared
extern; thus
int a; f() O
in C++ is
atatic int a; atatie f() {}
in C, and
extern int a; int a; extern f() {}
in C++ is
int a; f() {}

in C. However, note that


int f();

means
extern int f();
in both C++ and C.
Si.nœ clus names in C++ are in the sa.me nam.e spaœ as other names, constructs like
struct • { int a;} a;
atruct atat atat();
c:annot be used.
19.3 Anachronisms
A class name can be prefixed with the one of the keywords claaa, atruct, or union in the
declaration of class objects, pointers, etc. For example
atruet • a, •p;
atruct a f();
Programs using the old function definition syntax
C+ + Reference Manual 50

old-:function-deftnition:
decl-speciftersopt old..junction-declararor declaration-list function-body

old..junction-declarator:
declarator ( parameier-list )

paramerer-list:
identifier
identifier , identifttr
for example
max(a.b) { return (a<b)? b: a; }
may be used. H a function defined like this has not bee.n previously declared its argument type will
be taken to be C••• ) , that is, uncheckcd. If it bas been declared its type must agree with tbat of
the declaration.

(
Index

+ addition opcratcr 10 may a.planation of subscriprina 40


& address opcratcr 9 array iniùalizati.on 28
backslash characcer 2 array, multi-dimcmional 40
&. bitwise AND operator 11 array, storap crder of 40
" bitwise exclusive OR operator 12 may name, canversiœ of 7
1 bitwise inclusive OR. opemor 12 array name argument 37
• clau member operator 7 array sin. clefault 18
-• dus pointe: operator 7 asm declantion 33
, : ccmditional expression 12 asia,nmcnt, C01Wmion by 13
-- dec:rcmem operator 9 asi,nmcnt eçressian 12
/ division operator 10 aSÎJnl'llalt opcnlCJrS 12, 26
•• equality opermor 11 asqnmcmtofdassobjects 22
escape c:baraeter 2 asignmmt to pointer to dass object 13
c>. function call operaur 8 Msipmcnt to refermœ 13
> lfllllr than opcrator 11 associativity of operatcrs 6
,.. greater than cr equal to operaur 11 av.to spec:ificr 14
++ increme:m opcrator 9 automa1ic functions 15
• indirectiœ opera.ter 9 IUtomatÎC Sl'Or'a,e dus 4
f • inequality opcratcr 11 automaûcs, mitialization of 28
cc left shift operarar 11 baœlash cbaracler, 2
c lcss ihan opcrator 11 buedass 22
c• lcss than or equal to opcrator 11 base dm membcn. visibility of 25
&& Joaical AND operatar 12 binary apcntor, interpretatiœ of 14
1 lc,sical negation opcrator 9 binary openmn, ovcrloaded 14
11 logical OR opcrator 12 bit fields 27
" modulus operator 10 bitwise apeman 11
• muhipliœtion opermor 10 bitwise AND operator, & 11
oœ's complemem operator 9 bitwise m:lmive OR open.tœ, .. 12
: : opcratcr 7 bitwise inclusive OR opcrator, 1 12
.,. right sbift operator 11 black 34
: : , scope apeiator 7 blocks, initializltîœ in 36
[ ] , subsc:ript operatcr 7 black structure 36
- sublraction opcrator 10 break statemem 35
- unary minus opcrator 9 byte 9
abstract declaratcr 30 C++ C 1,48
addition opcrator, + 10 c, c++ 1, 48
additive operators 10 C+ + C campaùbility 48
address-of field 27 C+ + C default scope 49
address-of membct functlon 22 C+ + C funcdœ declaration 49
addr&u of overloadccl name 32 C++ Cnamespeœ 49
address of register 15 C eampatibility, C+ + 48
address opcrator, & 9 C default scc,pe, C++ 49
agrcpœ 28 C+ + mansions 48
aligmnem of fields 27 C function dcclamion, C+ + 49
alignme:m restriction 41 C function definitiœ, anacbronism 49
allocation of storap 42 C+ + keywords 49
ambiguity, it•elH 34 Cname space, C++ 49
anachrœism C function definition 49 call ci, funcrion 8
anachrcmism class names 49 can ci ovcrloaded fimdiœ 32
anachrœism \fCWstnsc:ta 49 caaaprefix 35
anachraûsm \fCWunion\fP 49 eut opcmar B, 9, 30
anmymous union 26 chu type 4, 16
arpmcnt evaluation, order of 8 characœr c:œsrant 2
argument, func:tion 8 characier, siped 4
aritbmctic convenions 6 cbaractcr array initialization 30
arithmctic opcratcrs 10 cbaractcr•imepr canversion S
arithmctic, pointer 10 cbaracœr strlna 2
aritbmelic types 4 dus, base 22
array dedaration 18 dus declaration 19
. 2.

class, derived 22 conversion, un1iguad-imeger S


class, friend 26 conversion by assignment 13
class, f:riend of 26 conversion by retunl 36
class member function 20 conversion ftom use:r-defined type 34
class member name 20 conversion of array name 7
class, member of 20 conversion of function 7
class, name of 19 conversion ope:raur, aplic:it 8, 40
class scope 3 conversions, arithmetic 6
claH 1truct union 20 conversions for overloadcd functions 32
class dcclaration, aample et. 20 conversion to fundamcnœl types 24
class declaratiom, nesting of 27 conversion to imegral type 34
classes 4 conversion to pointer type 34
classes, ope.rations permitted on 39 data de6nitions 38
classes, ove:rlœding 26 dec1aration 44
class member semantics 8 declaration, array 18
class member, 1tatic 20 declaration, asm 33
class member sym.u 8 declaration, dus 19
class member operau:r, • 7 declaration, anwa 33
(_ class name new type 31
class names, anachromsm 49
dedaration, a:ample et. 18
declaration, exte:n 15
class object initialization 28, 29 declaration, fidd 27
class objects, assignment of 22 declaration, name 31
class pâmer ope:rator, •> 7 declaration, ra;iat•r 15
comma ope:rator 13 declaration, stcrap class 14
comment 1 dcclaration, type 17
commutative opc:rators 6 c!=laration, typeclef 31
comparison, pointer 11 declaration of constant pointer 17
compatibility, C + + C 48 declaration of œfault func:tion araumenu 18
compiler comrol lines 38 declaration of function 17
compound statcme.nt 34 declaration of flmaion, implic:it 8
cxmditicri 34 declaration of function ar,uments 17
cœditiœal amipilation 39 declaration of pointer 17
cxmditiœal e:qression, ? : 12 declaratian of refermœ 17
con1t, eumpl.e of 18 declarations 14
conat type 16 declaration statm.tmt 36
conmnt,character 2 declaraur 16
constant, double 2 declarau:r, absuact 30
constant expressim 41 decrement apcmor. -- 9
constant, floating 2 default array size 18
constant, hexadeàmal 1 default ini1:ializa1:iœ 28
constant, im.ege:r 1 default sœpc, C+ + C 49
constant, l0n9 2 default arpli1mt5, e.ample of 19
amstant, octal 1 default functian arguments, declaratîon of 18
constant type 16 default prefix 35
constant pointer, declaration of 17 #dafin• 38
cxmstant pointer, cumple of 18 deUned operator 39
c:omtants 1, 4 · definitiœ, eztrmaI 37
constants, enumeratiœ 33 definitiœ, fimcrion 37, 47
c:onsttUCt0l' typc-cxmvenion 23 definitiœ, mcmber function 21
comtnlCt01'S 23 definitim of virtual function 23
construetors, free store 42 definitiœs, atemal 47
construetOn, initializatiœ 29 d•l•t• operaur 42
consuuctOn, overloading and 32 dclerc sratemm.t 36
cmmrucu,n, muctures 26 œrderenc:ina 8
c:onstruCt01'S, thil 42 daived dass 22
constrUCt01'5, uniœ 26 daived types 4
ccmsttUCtOrS and initialization 29 daived class, a:amplc of 22
consttuCtOn for initialization, esample of 29 datrw:tars 24
continue stateme.nt 35 destruetars, ftee store 42
conversion, character-intege:r 5 destruetcrs, thi• 42
conversion, doubl•·float 5 division, integer 41
conversion, float-doubl• 5 division opcraur. / 10
conversion, flœting-integer 5 do statemcnt 34
conversion, funetion argument 8 doubla constant 2
conversion, integer-characte:r S double type 16
conversion, integer-floating 5 double-:Uoat cœve:rsiœ 5
conversion, integer-lon; S ellipsis 17
conversion, integcr-poimer 10, 41 #elH 39
conversion, integer-un• igned 5 empty Smement 36
conversion, long-integer 5 #endif 39
amversion, overloading and 32 anum declaration 33
conversion, pointer 10, 40 enumeralion 33
conversion, pânter-imepr 5, 10, 41 enumeration constants 33
enumeratiœ, eumple of 33 friend of clau 26
enumerat.ors, restrictions on 33 friend of member funetion 26
equality operarors 11 function argumem 8
equality operator, •• 11 funetion call of 8
equivalence, type 31 function, call d overlœded 32
escape charaet«, 2 function, class membcr 20
escape seque.nce 2 function, conversion of 7
evaluation, orde:r of 6, 42 function, dcclaration of 17
evaluation, orde:r of argument 8 function definition 37, 47
eumple of class declaration 20 function, implidt declaration of 8
eumple of con•t 18 function, inlinc member 21
cumple of constant pointer 18 funetion name, overloadcd 32
eumple of constructon for initialization 29 function, p(inter to 40
eumple of declaratiœ 18 function 81JIIIMftt convenion 8
eumple of default argume:nu 19 function argument type-emve:rsiœ 23
ezample of de:rived class 22 function arpmem type conversion 18
eumple of em.m:ieration 33 funetion arguments, declaration of 17
ex:ample of friend. functiœs 2.5 function ar,umem iypes, un1cnown 17
aamplc of functiœ declaration 19 function call operau,r 26
( e.umple of member funetion 20 function cal1 operamr ( > 8
eumple of member funetions 2.5 function call operamr, OYerlœded 14
e.umple of member name visibility 2.5 function call semamics 8
eumple of ncsted class declartions 27 function call synm 8
eumple of subscriptina 19 function declarlliorl. C+ + C 49
ezample of typedef 31 function declarat:ion. aample of 19
e.umple of use of ellipsis 19 function definiûon, anachronism C 49
eumple of virtual funcdon 22 fl.mc:rions 4
cxplanation of subscriptina, array 40 functiom, automatic 15
explicit conversion operator 8, 40 functiom, friend 25
expression 6, 43 functions, opetations permitted œ 40
expression, assignment 12 functiom, vtnuaI 22
expression, cœiStant 41 fl.mdame:mal types 4
expression, paremhesized 7 fundamemal iypes, conversion to 24
expression, primary 7 ,oto nate:mmt 36
apression, referencc 8 area• iban operau,r, • 11
expression, unary 8 greaœr tlum or equal to c,perator, •• 11
expressions, order of evaluation of 6 hardware 3
expression statement 33 baado:imal comœnt 1
enensions, C+ + 48 idemifier 1
ut.e:n dedaration 15 #if 39
utert'l, scope of 15 #if4ef 39
memal definîtion 37 !f·•l. . ambiguity 34
=emal definitions 47 U•elH Stltcmenl 34
extem.al data definitions 38 #ifndaf 39
'iCWstrucMP, anachronism 49 implicit declaation of funi:tion 8
'iCWunion\fP, anachronism 49 #inclue!• 38
field, address-of Z7 incremem opcrarar, ...... 9
field declaratiœ 27 iJidjrection openter, • 9
field union 27 inequalîty operator, 1• 11
fields, alipment ci 27 initialization 28
fields, orde:r ci 3 initialization, array 28
fields, restrictions on 27 initialization, c1mlcœr array 30
fields, type of 3 initialization, class abject 28, 29
fields, unnamed 27 initialization constnacron 29
fields, zero.sized Z7 initialization, constructars and 29
file scape 3 initialization, dâa:ult 28
file ind.usiœ 38 initialization, e:ample of co.nsttuct0n for 29
float type 16 initialization in blocks 36
float-doubl.a conversion 5 initialization of amomatics 28
floating constant 2 initialization of references 30
floating types 4 initialization of statics 28
floating-intep:r conversion S initializer 28
format param=r 37 initializer, permitted form of 41
for Statement 34 i:l:Ln• !riend~function 26
free stcrage 42 inline member function 21
free stcre constructors 42 i:l:Ln• specifier 15
free stcre destruct.ors 42 int type 16
friend class 26 integer cmmanr l
friend functions 25 intepr-chancter cœversiœ S
friand specifier 15 integer-flœtina cxmversion 5
friend, virtual and 23 ime&er-lcmg convenion 5
friend-function, inlin• 26 imeler·polntet conversion 10, 41
friend functicm•, exampla of 25 intepr-uui,nn conversion s
integral types 4 operator, func:rion c:all 26
integral type, conversion to 34 operator, naw 42
interpretation of binary opcratar 14 operator, subsaipting 26
interpretation of unary operatar 13 : : operator, use m 20
keyword, public 24 operarors, additive 10
keywords, C+ + 49 operarors, arithmeric 10
keywords, list of 1 cpcrarors, assilJlDle:nt 12, 26
C label 36
labeled stateme:nt 36
left shift oper&tor, CC 11
operarors, assoàativity of 6
operators, bitwise 11
operators, commutative 6
le:ngth d. names l operators, equality 11
less than operator, c 11 operators, list of 26
Jess than ar equal to operatar, c. 11 operaton, multiplicative 10
lexiœl conventions l operators, ovcrloactina of 26
#lino 39 operatDn, J:rcicedcnœ of 6
list of keywords 1 operators, rdational 11
list of operators 26 operarors, shift 11
local scope 3 operators, mmy 8
logical AND operator, && 12 arder of argument evaluation 8
logic:al negatiœ operator, ! 9 arckr of evaluation 6, 42
logic:al OR operator, 11 12 arckr of fields 3
lon9 constant 2 arder of evaluarion of e,qressions 6
long type 4, 16 overflow 6
long-integcr conversion 5 ova:load spedficr 15
lvalue S, 16 ovcrloaded binary OJ)et'ltors 14
machine dependeney 41 ovcrloaded funa:iœ, call of 32
maao 48 ovcrloadcd funcâan name 32
macro preprocéssar 38 ovcrloaded funa:iœ call operator 14
membcr function, class 20 ovcrloaded member functions 22
membcr function, inlinc 21 ovcrlce.ded subscriJXinl operator 14
membcr name, class 20 ovcrloaded u.nary operaton l3
membcr function, address-of 22 ovcrloaded functicm, ccmvcrsions for 32
membcr function definition 21 ovcrloaded name, address of 32
membcr function, examplc ci 20 ovcrloaded opcratars 13
member function, f ri end of 26 ovcrloading classes 26
membcr· func:tions, eumple of 25 ova:loadina, restriction on 26
member functions, overloaded 22 ovcrloading and cœstructors 32
member functions, sttuc:tures 26 ovcrloadina and cœversiœ 32
member functions, union 26 ovcrloading of opemars 26
membcr name visibility, example d. 25 paramete:r, formal 37
member names, visil:ility of 24 parenthesized expression 7
member of class 20 permitted form of initializer 41
members, private 24 permitted on classes, operaTiœs 39
members, public 24 permitu:d on functions, opc:rations 40
missing smrage class specificr 15 pointer arithmetic 10
modulus operator, " 10 pointer comparison 11
multi ·dimcnsiœal array 40 pointer conversion 10, 40
multiplication OJ)e:l'ator, • 10 pointer, decl.aration of 17
multiplicative operatars 10 pointer, IM.1, l3
name 1, 3 pointer, thi• 7, 21
name, class member 20 pointer-inœpr ccmvetsion 5, 10, 41
name declaration 31 poimm 4
namc, ovcrloaded functiœ 32 po_imm, size of 3
name cl class 19 pointer to function 40
(__ names, length of l
name space, C++ C 49
pointer to class object, assignmem to 13
pointer type, conversion to 34
nested class declartions, enmple of 27 pointer type, void• 13, 48
nating of class dcdaratiœs 27 panability 41
new operator 42 pos1:fix ++ and -- 9
new operator 8, 10 precedenœ of cpemors 6
new type, class name 31 J:re& ++ and -- 9
new type, typcdef 31 p r ~ 48
WU, pointer l3 J:reprocessar, macro 38
mail stateme:nt 36 pimary expression 7
numbers, size of 3 private mcmbcn 24
object 3, 5 iroaram 47
oeta1 constant 1 program scope 3
cne's compleme:nt operator, 9 p-ogram format l
opcrations pcrmitted on classes 39 JN,blic keywcrd 24
operaticm pcrmitted on functions 40 public memben 24
operator, : : 7 rccunion 8, 4
opcrator, dafined 39 refcrenœ, usig:mne:nt to 13
operator, d•l•te 42 refmnœ, dcdaration of 17
. s.

referenœ a.pression 8 aubacriptin;, array •xplanation of 40


refe:renœs 4 aubacriptin9, axample of 1t
refe:renc::es, initialization of 30 aubacripting opuator 26
registe:r, address of 15 aubacriptin; opuator, ovarloa4ad 14
ra9iatez· declaration 15 aubacl'ipt oparator (J 7
regimn, restrictions on 41 su.brrac:tion ope:ratcr. - 10
relational operau,rs 11 awitchstatement 35
reserved words 1 syntu 42
restriction on overloadina 26 syntu, dass manbcr 8
restrictions on enumeratan 33 symu notation 3
restrictions on fields 27 thia consuucron 42
restrictions on re,isters 41 thia desttUCUl'S 42
restrictions on atatic 15 thia pointer 7, 21
restrictions on typcS 18 token r:placement 38
raturn, type conversion 'by 36 type 3
retw:n statement 35 type, char 4, 16
right slûft opcntcr, > > 11 type, ccmat 16
ruJcs, type conversion 6 type, constant 16
scope 3 type, c:onversion. from user-dcfined 34
scope, C+ + C ddault 49 type dedaration 17
scope, class 3 type, double 16
sœpe, file 3 type cquivalence 31
sa,pe, local 3 type, float 16
scope, program 3 type, int 16
scope çeàfier 14 type. lcm9 4, 16
scope of axtarn 15 type, ahOrt 4, 16
scope of atatic 15 type sprdficr 15
scope ope:rator : : 7 type, unaigued 4, 16
semantics, c1ass member 8 type, void. 4, 6, 16
seqUlftd:na of swcmenu 33 type-conversion, Cl0l'lftrUCl0r 23
sbift opemors 11 type-conversion, function argument 23
ahOs-t type 4, 16 type conversion, func2ion argument 18
sideeffects 6 type conversion nales 6
IÎgmd characte:r 4 type c:onversion UQiqucness 32
sign e:xu:nsion 41 type-conversion uniquesness, user-defi:ned 24
size of numben 3 type-conversion user-ddined 23
size of poimcrs 3 type c:onversion by rat.urn 36
&iHOf opa'atOr 8 t)"Paclaf dedara1ion 31
spedfier, auto 14 t)'J*!ef, eumpe of 31
spedfier, fdend 15 typedef new type 31
spedfier, inlin• 15 type names 30
spedfier. missin& storap class 15 type of fields 3
spedfier, ovùload 15 type of mine 7
spedfier, scope 14 type of virtuaJ function 23
specifier, atatic 14 types, atithmetic 4
spedfier, storap class 14 typeS, derive.d 4
specifier, type 15 types, floatina 4
specifier, virtu.al 15 typeS, fundamemal 4
statanem 47 types, inttp'l1 4
statanents 33 typet, resirictions on. 18
statemems, sequencina of 33 umry expression 8
atat.::Lc c1ass member 20 unary operators 8
atatic, restrictions on 15 umry mimis operator, .. 9
atatic, scope of 15 unary operator, imapretaûon of 13
•tatic specifier 14 unary operators, ove:rloaded 13
static storap class 4 #undat 38
statios, initialization cl. 28 undersœrc characta 1
srorage, allocation of 42 union, anonymous 26
srorage, free 42 union, claH atruct 20
stora1e allocation operator 8 union conatructœ:a 2,
Sf01'8.leclass3 union, field 27
storaac class, autcmatic 4 union mamber functicma 26
storage dass dedaration 14 u.niona ,. 25
storage class spedfier 14 uniqu.en•••• t)"Pa converdon 32
storage dass spedfier, miuing 15 u.niqu••:1•••, u.aer•deUned. typa•convaraion
(__, srorage class, static 4
storage order of may 40
24
lZlcnown !unct.icm azv=,.ant typH 17
mina, type of 7 œmamed field• 27
mine constant 2 unaignad type 4, 16
ltl'1.l.2 union., cl••• 20 unaignad.-int.eger conversion .5
atructuraa 4, 26 use ci : : operator 20
atructur•• ccmatructœ:a 2& use d. dlipsis, cumplc of 19
atructurH membu functicma 25 user-defined type, conversion frein 34
user-ddined. iype-convmion 23
user-defined type-cœvmion uniquesœss 24
vinual funct:iœs 22
virtual specifi.er 15
vinual and friend 23
vinual fu:nctiœ, definiùœ d 23
vinual funct:iœ, aample of 22
vinual funct:iœ, type of 23
visibility, exemple of member name 25
Yisibility of base dass members 25
visibility of member names 24
YOid.& 17
YOièl• poimer type 13, 48
voici type 4, 6, 16
while Statemem 34
zero..sized fields 27
- 20-

20 Appendix B: Run Time Erron


When an crror is detected at run time, task_error C) is called. 'Ibis function will examine
error_f et , and ü this variable denotes a function, that function will be called with the error
number and this as arguments, otherwise the enor numbcr will be given as argument to
C_ print_error ( ) which will prlnt an error message on atderr and termina.te the program.
[E_OLINICJ Attempt to delete object wb.ich remembere a taak.
[I_ONEXT) Attempt to delete an object which ia atill on aome chain.
[ UUTP'ULL J Attempt to putto a full queue.
[IJUTOBJJ Atteçt to J)Ut an object already cm aome queue.
[!_M.ClCOBJJ Atteçt to J)Utback an object already on aome queue.
[I_BACOULLJ Attempt to putback to a full queue.
[E_Grt'EMPTrJ Attempt to g-et from an empty queue.
[!_SETCLOCKJ Clock wae non-zero when aetclock() wa1 called.
[E_USTERMJ Atteçt to reaume T!lt.MINATZl> taak.
[ !_:R!SlltrN J Atteçt to reaume RTJNNIHG ta1k.
[ E.J4EGTXM!) Neg-ative arg-ument to delay().
[E_ll:ESOBJJ Attempt to resmne tuk or timer already cm aODLe queue.
[EJ{ISTOJ Bad argumenta for hiatog-ru.new().
[E_TAS!OIOI>EJ Bad mode for tuk.new().
[ !_TASICI>!L J Attempt to delete ncm•TZRMINATED taak.
[ E_TASJCPll! j Attempt to preempt a ncm-aUNNING taak.
[ E_TIM!RI>EL J Attempt to delete a non-TEUINATED timer.
[!_SCHTIM!J Scheduler chain ccrrupted: bad time.
[E_SCHOBJ) Scheduler ch&in corrupted: b&d object..
[!_Qt>!LJ Atteçt to delete a non-empty queue.
[E_CLOCKXI>LIJ The ,clock..,,.taak waa non-II>L! when clock waa ad.vancad.
[E_STACKJ Taak run time atack overflow.
[E_STOUJ No more free atore - NZW f&iled.
[E..USULTJ A taak attempted to obt&in ita own result().
[E_WAITJ A taak attempted to wait() for itaelf to TEaMINATE.
- 21-

21 Appendix C: A Program usina Taskl


#include ctaak.h>

/• trivial test exemple:


make a aet of t&aka which pasa an object round between themaelvea
uae printf to indicate pr09re••
WARNIHG: thil program aeta up an infinite loop

claaa pc: public t&ak {


pc(char•, qtail•, qhead•);
} ;

void pc.pc(char• n, qt&il• t, qhe&d• h) :(n,O,O)


{
printf("new pc(Ka,K4,"4)\n•,n,t,h);

while (1) {
object• p • h->get();
printf("taak ka\n",n);
t•>put(p);
}
}

main()
{
qhead• hh • new qhead;
qtail• t . hh->t&il();
qbea«h h;

for (int 1•0; 1<20; 1++) {


char• n • new char[2j; /• make a one letter taak name •I
n[OJ • 'a'+i;
n[1J • 0;

h • new qhead;
new pc(n,t,h);
printf("main()'• loop\n");
t • h•>tail C ) ;
}

new pc("firat pc•,t,hh);


printf("main: bere we go\n"};
t->put(new object);
printfC"ma.in: ezit\n");
thiataak->reaultia(O};
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy