Professional Documents
Culture Documents
{ The original cfront translated C++ into C for { e.g., unlike Ada, complicated run-time libraries
portability have not traditionally been required for C++
However, this was dicult to debug and po- Note, that there is no language-specic sup-
tentially inecient port for concurrency, persistence, or distri-
bution in C++
{ Many native host machine compilers now exist
e.g., Borland, DEC, GNU, HP, IBM, Microsoft,
Sun, Symantec, etc. Compatibility with C libraries and UNIX
tools is emphasized, e.g.,
C++ is a mostly upwardly compatible ex- { Object code reuse
tension of C that provides: The storage layout of structures is compat-
1. Stronger typechecking ible with C
2. Support for data abstraction Support for X-windows, standard ANSI C li-
brary, UNIX system calls via extern block
3. Support for object-oriented programming
{ C++ works with the make recompilation utility
{ C++ supports the Object-Oriented paradigm
but does not require it
2 3
C++ Design Goals (cont'd) Major C++ Enhancements
1. C++ supports object-oriented program-
\As close to C as possible, but no closer" ming features
{ i.e., C++ is not a proper superset of C, so that e.g., single and multiple inheritance, abstract
backwards compatibility is not entirely main- base classes, and virtual functions
tained
Typically not a problem in practice:::
2. C++ facilitates data abstraction and en-
capsulation that hides representations be-
hind abstract interfaces
Note, certain C++ design goals con
ict e.g., the class mechanism and parameterized
with modern techniques for: types
1. Compiler optimization
{ e.g., pointers to arbitrary memory locations 3. C++ provides enhanced error handling ca-
complicate register allocation and garbage pabilities
collection
e.g., exception handling
2. Software engineering
{ e.g., separate compilation complicates inlin- 4. C++ provides a means for identifying an
ing due to diculty of interprocedural anal- object's type at runtime
ysis
e.g., Run-Time Type Identication (RTTI)
4 5
Other Enhancements
C++ enforces type checking via function
Other Enhancements (cont'd)
prototypes
References provide \call-by-reference" pa-
rameter passing
Allows several dierent commenting styles
Provides type-safe linkage Declare constants with the const type qual-
ier
Provides inline function expansion
New mutable type qualier
Built-in dynamic memory management via
new and delete operators New bool boolean type
Default values for function parameters New type-secure extensible I/O interface
called streams and iostreams
Operator and function overloading
6 7
Other Enhancements (cont'd)
A new set of \function call"-style cast no- Language Features Not Part of
tations
C++
Variable declarations may occur anywhere
statements may appear within a block 1. Concurrency
See \Concurrent C" by Nehrain Gehani
The name of a struct, class, enum, or
union is a type name 2. Persistence
Allows user-dened conversion operators See Exodus system and E programming lan-
guage
C++ Classes
C++ Classes (cont'd)
The class is the basic protection and data
abstraction unit in C++
For eciency and C compatibility reasons,
{ i.e., rather than \per-object" protection C++ has two type systems
1. One for built-in types, e.g., int,
oat, char,
double, etc.
The class mechanism facilitates the cre-
ation of user-dened Abstract Data Types 2. One for user-dened types, e.g., classes, structs,
(ADTs) unions, enums etc.
{ A class declarator denes a type comprised of
data members, as well as method operators
Data members may be both built-in and user- Note that constructors, overloading, in-
dened heritance, and dynamic binding only apply
to user-dened types
{ Classes are \cookie cutters" used to dene ob- { This minimizes surprises, but is rather cumber-
jects some to document and explain :::
a.k.a. instances
14 15
C++ Classes (cont'd) C++ Classes (cont'd)
A class is a \type constructor" General characteristics of C++ classes:
{ e.g., in contrast to an Ada package or a Mod- { Any number of class objects may be dened
ula 2 module i.e., objects, which have identity, state, and
Note, these are not types, they are \encap- behavior
sulation units"
{ Class objects may be dynamically allocated and
{ Until recently, C++ did not have a higher-level deallocated
modularization mechanism :: :
16 17
26 27
C++ Objects (cont'd)
C++ Objects (cont'd)
Life-time or \storage class:"
1. Static
{ i.e., it lives throughout life-time of process
High Stack Automatic
{ static can be used for local, global, or class- Addresses Variables
specic objects (note, their scope is dier-
ent) Heap
Dynamic
Variables
2. Automatic Uninitialized
Global Data Static
{ i.e., it lives only during function invocation, Initialized Variables
on the \run-time stack" Low
Global Data
Read-Only
Addresses Text Code and
3. Dynamic Data
{ Note, it is very dicult to implement garbage { Use the class-specic new and delete opera-
collection correctly in C++ due to pointers and tors to dene a memory management facility
unions using reference counts to reclaim unused mem-
ory
Therefore, programmers must explicitly deal- { Adapt Hans Boehm's conservative garbage col-
locate objects when they want them to go lector for C to C++ :::
away
{ C++ constructors and destructors are useful
for automating certain types of memory management ::: No solution is optimal, however, so stor-
age management is often performed \by
hand" (ugh ;-))
30 31
C++ Object-Oriented Features C++ Object-Oriented Features
C++ provides three characteristics gen-
erally associated with object-oriented pro- (cont'd)
gramming:
1. Data Abstraction C++'s object-oriented features encourage
designs that
{ Package a class abstraction so that only the 1. Explicitly distinguish general properties of re-
public interface is visible and the implemen- lated concepts from
tation details are hidden from clients
{ Allow parameterization based on type 2. Specic details of particular instantiations of
these concepts
2. Single and Multiple Inheritance
{ A derived class inherits operations and at-
tributes from one or more base classes, pos- e.g., an object-oriented graphical shapes
sibly providing additional operations and/or
attributes library design using inheritance and dy-
3. Dynamic Binding namic binding
{ The actual type of an object (and thereby
its associated operations) need not be fully
known until run-time This approach facilitates extensibility and
Compare with C++ template feature, which reusability
are instantiated at compile-time
32 33
class Y : public X f /* */ g;
::: private:
class Z : public X f /* */ g;
::: int lo bnd ;
class YZ : public Y, public Z f /* ::: */ g; g;
#endif /* ADA VECTOR H */
36 37
38 39
Dynamic Binding Preview Dynamic Binding Preview
(cont'd)
Dynamic binding is a mechanism used along
with inheritance to support a form of poly- e.g.,
morphism
struct X f /* Base class */
int f (void) f puts ("X::f"); g // Non-virtual
C++ uses virtual functions to implement virtual int vf (void) f puts ("X::vf"); g // Virtual
dynamic binding: g;
struct Y : public X f /* Derived class */
{ The actual method called at run-time depends int f (void) f puts ("Y::f"); g // Non-virtual
on the class of the object used when invoking virtual int vf (void) f puts ("Y::vf"); g // Virtual
the virtual method g;
void foo (X *x) f /* Note, can also use references */ :::
C++ allows the class dener the choice x->f (); /* direct call: f 1X (x); */
of whether to make a method virtual or x->vf (); /* indirect call: (*x->vptr[1]) (x) */
not g
{ This leads to time/space performance vs.
ex- int main (void) f
ibility tradeos X x;
Y y;
Virtual functions introduce a small amount foo (&x); // X::f, X::vf
of overhead for each virtual function call foo (&y); // X::f, Y::vf
g
40 41
Therefore, the linker may be used to de- On older C++ compilers, diagnostic mes-
sages from the linker are sometimes rather
tect mismatches between function proto- cryptic!
types, function denitions, and function { See the c++filt program
usage
:: :
46 47
Typesafe Linkage (cont'd)
Language interoperability issues
Typesafe Linkage (cont'd)
{ This problem arises as a side eect of using Language interoperability issues (cont'd)
type-safe linkage in C++
{ Other syntactic forms of extern blocks:
{ C functions used in C++ code (e.g., standard
UNIX library functions) must be explicitly de- extern "C" f
clared as requiring C linkage (i.e., names are char *mktemp (const char *);
not mangled) via the new extern "C" declara- char *getenv (const char *);
tion g
{ Encapsulating existing header les
e.g., #if dened ( cplusplus)
extern "C" f
extern "C" int abs (int i); #endif /* cplusplus */
double abs (double d); #include <string.h>
Complex abs (Complex &c); #ifdef cplusplus
g
int foo (int bar) f #endif /* cplusplus */
cout << abs (Complex (,10, 4.5)); { Note, extern blocks also support other languages :::
g
48 49
Inline Functions
Inline Functions (cont'd)
Many programming languages force devel-
opers to choose between:
Here's an example of a common C prob-
1. Modularity/abstraction (function call) lem with the preprocessor:
2. Performance (macro or inline-expansion by-hand) { Classic C macro, no sanity-checking at macro
expansion time
#dene SQUARE(X) ((X) * (X))
C++ allows inline function expansion, which int a = 10;
has several advantages:
int b = SQUARE (a++); // trouble!!! (a++) * (a++)
1. It combines the eciency of a macro with the
type-security and abstraction of a function call { C++ inline function template
2. It reduces both execution time and code size template<class T> inline
(potentially) T square (T x) f return x * x; g
3. It discourages the traditional reliance upon macro int c = square (a++); // OK
preprocessor statements
50 51
Inline Functions (cont'd) Inline Functions (cont'd)
Points to consider about inline functions: As an example of inlining in C++, we
1. Class methods that are dened in their decla- will discuss a simple run-time function call
ration are automatically expanded inline \trace" facility
2. It is dicult to debug code where functions { Provides a rudimentary debugging facility
have been inline expanded and/or optimized e.g., useful for long-running network servers
3. Compilers require more time and space to com-
pile when there are many inline functions
4. Inline functions do not have the pseudo-polymorphic The goals are to be able to:
properties of macros 1. Determine the dynamic function calling behav-
{ However, inline templates approximate this ior of the program, i.e., \tracing"
functionality
2. Allow for ne-grain control over whether trac-
5. Compilers often have limits on the size and ing is enabled, e.g.,
type of function that can be inlined.
{ e.g., if stack frame is very large: { At compile-time (remove all traces of Trace
and incur no run-time penalty)
int foo (void) f
int local array[1000000]; { At run-time (via signals and/or command-
// line options)
{ This can cause surprising results wrt code
:::
size, e.g.,
3. Make it easy to automate source code instru-
int bar (void) f foo (); foo (); g mentation
52 53
tion denitions and then insert code auto- enter void foo (void) in (file main.C, line 8)
54
Inline Functions (cont'd)
Inline Functions (cont'd)
// Trace.h
e.g., main.C
#if !dened ( TRACE H)
#dene TRACE H
#include "Trace.h" #if dened (NTRACE) // compile-time omission
#dene T(X)
void foo (int max depth) f #else
T ("void foo (void)"); #dene T(X) Trace (X, LINE , FILE )
#endif /* NTRACE */
/* Trace ("void foo (void)", 8, "main.c") */
if (max depth > 0) foo (max depth , 1); class Trace f
/* Destructor called automatically */ public:
g Trace (char *n, int line = 0, char *le = "");
~Trace (void);
int main (int argc, char *argv[]) f static void start tracing (void);
const int MAX DEPTH = static void stop tracing (void);
static int set nesting indent (int indent);
argc == 1 ? 10 : atoi (argv[1]); private:
if (argc > 2) static int nesting depth ;
Trace::set nesting indent (atoi (argv[2])); static int nesting indent ;
if (argc > 3) static int enable tracing ;
Trace::stop tracing (); char *name ;
g;
T ("int main (int argc, char *argv[])"); #if dened ( INLINE )
foo (MAX DEPTH); #dene INLINE inline
return 0; #include "Trace.i"
/* Destructor called automatically */ #else
g #dene INLINE
#endif /* INLINE */
#endif /* TRACE H */
55 56
delete b;
foo = "To C or not to C?" // OK
Built-in support for memory management foo[7] = 'C'; // error, read-only location
improves: // error, can't assign to const pointer bar
1. Type-security bar = "avoid cliches like the plague.";
// OK, but be careful of read-only memory!!!
2. Extensibility bar[1] = 'D';
private:
Ensuring \const correctness" is an impor- size t len;
tant aspect of designing C++ interfaces, g;
e.g.,
1. It ensures that const objects may be passed const String string constant ("hello");
as parameters string constant.size (); // Fine
{ A const method may not directly modify its
2. It ensures that data members are not acciden- this pointer
tally corrupted string constant.set (1, 'c'); // Error
61 62
Stream I/O
Stream I/O (cont'd)
C++ extends standard C library I/O with
stream and iostream classes The stream and iostream class categories
replace stdin, stdout, and stderr with cout,
Several goals cin, and cerr
1. Type-Security
These classes may be used by overloading
{ Reduce type errors for I/O on built-in and the << and >> operators
user-dened types
{ C++ does not get a segmentation fault since
2. Extensibility (both above and below) the "correct" function is called
#include <iostream.h>
{ Allow user-dened types to interoperate syn- char *name = "joe";
tactically with existing printing facilities int id = 1000;
cout << "name = " << name << ", id = " << id << '\n';
Contrast with printf/scanf-family // cout.operator<< ("name = ").operator<< ("joe") :::
{ Transparently add new underlying I/O de- { In contrast, old C-style I/O oers no protection
vices to the iostream model from mistakes, and gets a segmentation fault
on most systems!
i.e., share higher-level formatting opera- printf ("name = %s, id = %s\n", name, id);
tions
63 64
Boolean Type
Stream I/O (cont'd) C++ has added a new build-in type called
bool
{ The bool values are called true and false
Be careful using Stream I/O in construc-
tors and destructors for global or static { Converting numeric or pointer type to bool
objects, due to undened linking order and takes 0 to false and anything else to true
elaboration problems :::
{ bool promotes to int, taking false to 0 and
true to 1
In addition, the Stream I/O approach does { Statements such as if and while are now con-
not work particularly well in a multi-threaded verted to bool
environment :::
{ This is addressed in newer compilers that oer { All operators that conceptually return truth
thread-safe iostream implementations values return bool
e.g., the operands of &&, jj, and !, but not
&, j, and ~
65 66
References
References (cont'd)
C++ allows references, which may be:
1. Function parameters e.g., consider a swap abstraction:
2. Function return values void swap (int x, int y)
3. Other objects f
int t = x; x = y; y = t;
g
A reference variable creates an alternative int main (void) f
name (a.k.a. \alias") for an object int a = 10, b = 20;
printf ("a = %d, b = %d\n", a, b);
swap (a, b);
References may be used instead of point- printf ("a = %d, b = %d\n", a, b);
ers to facilitate: g
1. Increased code clarity
There are several problems with this code
2. Reduced parameter passing costs
1. It doesn't swap!
3. Better compiler optimizations
2. It requires a function call
References use call-by-value syntax, but 3. It only works for integers!
possess call-by-reference semantics
67 68
69 70
References (cont'd)
ir i Type Cast Syntax
10
C++ introduces a new type cast syntax
in addition to Classic C style casts. This
"function-call" syntax resembles the type
conversion syntax in Ada and Pascal, e.g.,
With references (as with classes), it is im- // function prototype from math.h library
portant to distinguish initialization from extern double log10 (double param);
assignment, e.g.,
int i = 10; if ((int) log10 ((double) 7734) != 0)
// initialization of ir ; /* C style type cast notation */
int &ir = i; // Equivalent to int *const ip = &i;
ir = ir + 10; // dereference is automatically done
// *ip = *ip + 10; if (int (log10 (double (7734))) != 7734)
; // C++ function-style cast notation
Once initialized, a reference cannot be changed
{ i.e., it may not be reassigned to reference a This \function call" is performed at com-
new location
pile time
{ Note, after initialization all operations aect
the referenced object
i.e., not the underlying const pointer :::
71 72
private:
double real, imaginary;
g; I recommend version 4 since it is the most
consistent and also works with built-in types :::
assign grade ("Bjarne Stroustrup", "C++"); However, it is not possible to omit argu-
// Bjarne needs to work harder on his tasks ments in the middle of a call, e.g.,
assign grade ("Jean Ichbiah"); extern int foo (int = 10, double = 2.03, char = 'c');
// Jean gets an "A" for Ada!
foo (100, , 'd'); /* ERROR!!! */
foo (1000); /* OK, calls foo (1000, 2.03, 'c');
Default arguments are useful in situations
when one must change a class without af-
fecting existing source code There are several arcane rules that per-
{ e.g., add new params at end of argument list mit successive redeclarations of a func-
(and give them default values) tion, each time adding new default argu-
ments
75 76
Miscellaneous Dierences
In C++, sizeof ('a') == sizeof (char); in
C, sizeof ('a') == sizeof (int)
Miscellaneous Dierences
{ This facilitates more precise overloading:::
(cont'd)
In C++, a struct or class is a scope; in
char str[5] = "hello" is valid C, but C++ C a struct, enum, or enum literal are
exported into the \global scope," e.g.,
gives error because initializer is too long
(because of hidden trailing '\0') struct Foo f enum Bar fBAZ, FOOBAR, BIZBUZZg; g;
/* Valid C, invalid C++ */
enum Bar bar = BAZ;
In C++, a function declaration int f(); // Valid C++, invalid C
means that f takes no arguments (same Foo::Bar bar = Foo::BAZ;
as int f(void);). In C it means that f can
take any number of arguments of any type The type of an enum literal is the type of
at all! its enumeration in C++; in C it is an int,
{ C++ would use int f ( );:::
e.g.,
/* True in C, not necessarily true in C++. */
In C++, a class may not have the same sizeof BAZ == sizeof (int);
/* True in C++, not necessarily true in C. */
name as a typedef declared to refer to a sizeof Foo::BAZ == sizeof (Foo::Bar);
dierent type in the same scope
85 86
Miscellaneous Dierences
(cont'd) Summary
In ANSI C, a global const has external C++ adds many, many, many new fea-
linkage by default; in C++ it has internal tures to the C programming language
linkage, e.g.,
/* In C++, \global1" is not visible to other modules. */
const int global1 = 10; It is not necessary to use all the features
/* Adding extern makes it visible to other modules. */ in order to write ecient, understandable,
extern const int global2 = 100; portable applications
In ANSI C, a void * may be used as the
right-hand operand of an assignment or C++ is a \moving target"
initialization to a variable of any pointer
type, whereas in C++ it may not (without { Therefore, the set of features continues to change
using a cast ):::
and evolve
void *malloc (size t); { However, there are a core set of features that
/* Valid C, invalid C++ */ are important to understand and are ubiquitous
int *i = malloc (10 * sizeof *i);
/* Valid C, valid C++ */
int *i = (int *) malloc (10 * sizeof *i);
87 88