You are on page 1of 2

C++ Reference Card © 2002 Greg Book

Key C++ Program Structure Control Structures Functions


// my first program in C++ Decision (if-else) In C, functions must be prototyped before the main
#include <iostream.h> if (condition) { function, and defined after the main function. In
switch – keyword, reserved int main () statements; C++, functions may, but do not need to be,
“Hello!” – string { } prototyped. C++ functions must be defined before
// comment – commented code cout << “Hello World!”; else if (condition) { the location where they are called from.
close() – library function return 0; statements; // function declaration
} type name(arg1, arg2, ...) {
main – variable, identifier }
else { statement1;
variable – placeholder in syntax // single line comment statements; statement2;
if (exression) - syntax /* multi-line } ...
statement; comment */ if (x == 3) // curly braces not needed }
flag = 1; // when if statement is type – return type of the function
else // followed by only one name – name by which the function is called
flag = 0; // statement arg1, arg2 – parameters to the function
Identifiers Repetition (while) statement – statements inside the function
These are ANSI C++ reserved words and cannot be used as variable names. while (expression) { // loop until // example function declaration
statements; // expression is false // return type int
asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, } int add(int a, int b) { // parms
default, delete, do, double, dynamic_cast, else, enum, explicit, extern, false, float, Repetition (do-while) int r; // declaration
for, friend, goto, if, inline, int, long, mutable, namespace, new, operator, private, do { // perform the statements r = a + b; // add nums
protected, public, register, reinterpret_cast, return, short, signed, sizeof, static, statements; // as long as condition return r; // return value
static_cast, struct, switch, template, this, throw, true, try, typedef, typeid, } while (condition); // is true }
typename, union, unsigned, using, virtual, void, volatile, wchar_t Repetition (for) // function call
init - initial value for loop control variable num = add(1,2);
condition - stay in the loop as long as condition Passing Parameters
is true Pass by Value
Data Types Operators increment - change the loop control variable function(int var); // passed by value
Variable Declaration priority/operator/desc/ASSOCIATIVITY for(init; condition; increment) { Variable is passed into the function and can be
special class size sign type name; statements; changed, but changes are not passed back.
special: volatile 1 :: scope LEFT } Pass by Constant Value
class: register, static, extern, auto 2 () parenthesis LEFT Bifurcation (break, continue, goto, exit) function(const int var);
size: long, short, double [ ] brackets LEFT break; // ends a loop Variable is passed into the function but cannot be
sign: signed, unsigned -> pointer reference LEFT continue; // stops executing statements changed.
type: int, float, char (required) . structure member access LEFT // in current iteration of loop cont- Pass by Reference
name: the variable name (required) sizeof returns memory size LEFT // inues executing on next iteration function(int &var); // pass by reference
// example of variable declaration 3 ++ increment RIGHT label: Variable is passed into the function and can be
extern short unsigned char AFlag; — decrement RIGHT goto label; // execution continues at changed, changes are passed back.
TYPE SIZE RANGE ~ complement to one (bitwise) RIGHT // label Pass by Constant Reference
char 1 signed -128 to 127 ! unary NOT RIGHT exit(retcode); // exits program function(const int &var);
unsigned 0 to 255 & reference (pointers) RIGHT Selection (switch) Variable cannot be changed in the function.
short 2 signed -32,768 to 32,767 * dereference RIGHT switch (variable) { Passing an Array by Reference
unsigned 0 to 65,535 (type) type casting RIGHT case constant1: // chars, ints It’s a waste of memory to pass arrays and
long 4 signed -2,147,483,648 to + - unary less sign RIGHT statements; structures by value, instead pass by reference.
2,147,483,647 4 * multiply LEFT break; // needed to end flow int array[1]; // array declaration
unsigned 0 - 4,294,967,295 / divide LEFT case constant2: ret = aryfunc(&array); // function call
int varies depending on system % modulus LEFT statements; int aryfunc(int *array[1]) {
float 4 3.4E +/- 38 (7 digits) 5 + addition LEFT break; array[0] = 2; // function
double 8 1.7E +/- 308 (15 digits) - subtraction LEFT default: return 2; // declaration
long double 6 << bitwise shift left LEFT statements; // default statements }
10 1.2E +/- 4,932 (19 digits) >> bitwise shift right LEFT } Default Parameter Values
bool 1 true or false 7 < less than LEFT int add(int a, int b=2) {
wchar_t 2 wide characters <= less than or equal LEFT int r;

Console Input/Output
Pointers > greater than LEFT r=a+b; // b is always 2
type *variable; // pointer to variable >= greater than or equal LEFT return (r);
type *func(); // function returns pointer 8 == equal LEFT [See File I/O on reverse for more about streams] }
void * // generic pointer type != not equal LEFT C Style Console I/O
NULL; // null pointer 9 & bitwise AND LEFT stdin – standard input stream Overloading Functions
*ptr; // object pointed to by pointer ^ bitwise NOT LEFT stdout – standard output stream Functions can have the same name, and same
&obj // address of object | bitwise OR LEFT stderr – standard error stream number of parameters as long as the parameters of
Arrays 10 && logical AND LEFT // print to screen with formatting are different types
int arry[n]; // array of size n || logical OR LEFT printf(“format”, arg1,arg2,...); // takes and returns integers
int arry2d[n][m]; // 2d n x m array 11 ? : conditional RIGHT printf(“nums: %d, %f, %c”, 1,5.6,’C’); int divide (int a, int b)
int arry3d[i][j][k]; // 3d i x j x k array 12 = assignment // print to string s { return (a/b); }
Structures += add/assign sprintf(s,”format”, arg1, arg2,...); // takes and returns floats
struct name { -= subtract/assign sprintf(s,”This is string # %i”,2); float divide (float a, float b)
type1 element1; *= multiply/assign // read data from keyboard into { return (a/b); }
type2 element2; /= divide/assign // name1,name2,... divide(10,2); // returns 5
... %= modulus/assign scanf(“format”,&name1,&name2, ...); divide(10,3); // returns 3.33333333
} object_name ; // instance of name >>= bitwise shift right/assign scanf(“%d,%f”,var1,var2); // read nums Recursion
name variable; // variable of type name <<= bitwise shift left/assign // read from string s Functions can call themselves
variable.element1; // ref. of element &= bitwise AND/assign sscanf(“format”,&name1,&name2, ...); long factorial (long n) {
variable->element1; // reference of ^= bitwise NOT/assign sscanf(s,“%i,%c”,var1,var2); if (n > 1)
pointed to structure |= bitwise OR/assign C Style I/O Formatting return (n * factorial (n-1));
13 , comma %d, %i integer else
%c single character return (1);
%f double (float) }
Initialization of Variables %o octal Prototyping
type id; // declaration User Defined DataTypes %p pointer Functions can be prototyped so they can be used
type id,id,id; // multiple declaration typedef existingtype newtypename ;
%u unsigned after being declared in any order
type *id; // pointer declaration %s char string // prototyped functions can be used
typedef unsigned int WORD;
type id = value; // declare with assign %e, %E exponential // anywhere in the program
enum name{val1, val2, ...} obj_name;
type *id = value; // pointer with assign %x, %X hexadecimal #include <iostream.h>
enum days_t {MON,WED,FRI} days;
id = value; // assignment %n number of chars written void odd (int a);
union model_name {
Examples %g, %G same as f for e,E void even (int a);
type1 element1;
// single character in single quotes C++ console I/O int main () { ... }
type2 element2; ...
char c=‘A’; cout<< console out, printing to screen
} object_name ;
// string in double quotes, ptr to string cin>> console in, reading from keyboard
union mytypes_t {
char *str = “Hello”; cerr<< console error
char c;
clog<< console log
int i = 1022; int i;
cout<<“Please enter an integer: ”;
Namespaces
float f = 4.0E10; // 4^10 } mytypes;
cin>>i; Namespaces allow global identifiers under a name
int ary[2] = {1,2} // array of ints struct packed { // bit fields
cout<<“num1: ”<<i<<“\n”<<endl; // simple namespace
const int a = 45; // constant declaration unsigned int flagA:1; // flagA is 1 bit
Control Characters namespace identifier {
struct products { // declaration unsigned int flagB:3; // flagB is 3 bit
\b backspace \f form feed \r return namespace-body;
char name [30]; }
\’ apostrophe \n newline \t tab }
float price;
\nnn character #nnn (octal) \” quote // example namespace
} ;
\NN character #NN (hexadecimal) namespace first {int var = 5;}
products apple; // create instance
apple.name = “Macintosh”; // assignment Preprocessor Directives namespace second {double var = 3.1416;}
#define ID value // replaces ID with int main () {
apple.price = 0.45;
cout << first::var << endl;
products *pApple; // pointer to struct
pApple->name = “Granny Smith”;
//value for each occurrence in the code
#undef ID // reverse of #define
Character Strings cout << second::var << endl;
#ifdef ID //executes code if ID defined The string “Hello” is actually composed of 6 return 0;
pApple->price = 0.35; // assignment
#ifndef ID // opposite of #ifdef characters and is stored in memory as follows: }
#if expr // executes if expr is true Char H e l l o \0 using namespace allows for the current nesting
#else // else Index 0 1 2 3 4 5 level to use the appropriate namespace
Exceptions #elif // else if \0 (backslash zero) is the null terminator character using namespace identifier;
try { #endif // ends if block and determines the end of the string. A string is an // example using namespace
// code to be tried... if statements #line number “filename” array of characters. Arrays in C and C++ start at namespace first {int var = 5;}
statements; // fail, exception is set // #line controls what line number and zero. namespace second {double var = 3.1416;}
// filename appear when a compiler error str = “Hello”; int main () {
throw exception;
// occurs str[2] = ‘e’; // string is now ‘Heelo’ using namespace second;
}
catch (type exception) { #error msg //reports msg on cmpl. error common <string.h> functions: cout << var << endl;
// code in case of exception #include “file” // inserts file into code strcat(s1,s2) strchr(s1,c) strcmp(s1,s2) cout << (var*2) << endl;
statements; // during compilation strcpy(s2,s1) strlen(s1) strncpy(s2,s1,n) return 0;
} #pragma //passes parameters to compiler strstr(s1,s2) }
Class Reference File I/O ACSII Chart
#include <fstream.h> // read/write file Dec C har Dec Char Dec Char Dec Char
Class Syntax
class classname {
Inheritance #include <ofstream.h> // write file 0 N UL 64 @ 128 Ç 192 └
#include <ifstream.h> // read file 1 SO H 65 A 129 ü 193
Functions from a class can be inherited and reused ┴
public: File I/O is done from the fstream, ofstream, and
in other classes. Multiple inheritance is possible. 2 ST X 66 B 130 é 194 ┬
classname(parms); // constructor ifstream classes.
~classname(); // destructor class CPoly { //create base polygon class 3 ET X 67 C 131 â 195 ├
member1; protected:
File Handles 4 EO T 68 D 132 ä 196 ─
member2; int width, height;
A file must have a file handle (pointer to the file) to 5 ENQ 69 E 133 à 197 ┼
public: 6 ACK 70 F 134 å 198 ╞
protected: access the file.
void SetValues(int a, int b) 7 BEL 71 G 135 199
member3; ifstream infile; // create handle called ç ╟
{ width=a; height=b;}
... // infile to read from a file 8 BS 72 H 136 ê 200 ╚
};
private: ofstream outfile; // handle for writing 9 T AB 73 I 137 ë 201 ╔
member4; class COutput { // create base output
public: // class
fstream f; // handle for read/write 10 LF 74 J 138 è 202 ╩
} objectname; 11 VT B 75 K 139 ï 203
void Output(int i); ╦
// constructor (initializes variables) Opening Files 12 FF 76 L 140 î 204 ╠
};
classname::classname(parms) { After declaring a file handle, the following syntax 13 CR 77 M 141 ì 205
void COutput::Output (int i) { ═
} can be used to open the file
// destructor (deletes variables) cout << i << endl; 14 SO 78 N 142 Ä 206 ╬
void open(const char *fname, ios::mode);
} 15 SI 79 O 143 Å 207 ╧
classname::~classname() { fname should be a string, specifying an absolute
} // CRect inherits SetValues from Cpoly
or relative path, including filename. ios:: mode 16 D LE 80 P 144 É 208 ╨
public members are accessible from anywhere // and inherits Output from COutput
can be any number of the following and repeat: 17 D C1 81 Q 145 æ 209 ╤
where the class is visible class CRect: public CPoly, public COutput 18 D C2 82 R 146 Æ 210 ╥
in Open file for reading
protected members are only accessible from { 19 D C3 83 S 147 ô 211
out Open file for writing ╙
members of the same class or of a friend class public: T ö
ate Initial position: end of file 20 D C4 84 148 212 ╘
private members are accessible from members int area(void)
app Every output is appended at the end of file 21 N AK 85 U 149 ò 213 ╒
of the same class, members of the derived classes { return (width * height); }
trunc If the file already existed it is erased 22 SYN 86 V 150 û 214 ╓
and a friend class };
binary Binary mode 23 ET B 87 W 151 ù 215 ╫
constructors may be overloaded just like any // CTri inherits SetValues from CPoly
ifstream f; // open input file example 24 C AN 88 X 152 ÿ 216 ╪
other function. define two identical constructors class CTri: public CPoly {
f.open(“input.txt”, ios::in); 25 EM 89 Y 153 Ö 217
with difference parameter lists public: ┘
ofstream f; // open for writing in binary Z Ü
Class Example int area(void) 26 SUB 90 154 218 ┌
f.open(“out.txt”, ios::out | ios::binary
class CSquare { // class declaration { return (width * height / 2); } 27 ESC 91 [ 155 ¢ 219 █
| ios::app);
public: }; 28 FS 92 \ 156 £ 220 ▄
void Init(float h, float w); void main () {
Closing a File 29 GS 93 ] 157 ¥ 221 ▌
float GetArea(); // functions CRect rect; // declare objects
A file can be closed by calling the handle’s close 30 RS 94 ^ 158 ? 222 ?
private: // available only to CSquare CTri tri;
function 31 US 95 _ 159 ƒ 223 ?
float h,w; rect.SetValues (2,9);
f.close(); 32 96 ` 160 á 224 α
} // implementations of functions tri.SetValues (2,9); 33 ! 97 a 161 í 225 ß
void CSquare::Init(float hi, float wi){ rect.Output(rect.area());
Writing To a File (Text Mode) 34 “ 98 b 162 ó 226 Γ
cout<<tri.area()<<endl; 35 # 99 c 163 ú 227 π
h = hi; w = wi; The operator << can be used to write to a file. Like
} 36 $ 100 d 164 ñ 228 Σ
} cout, a stream can be opened to a device. For file
37 % 101 e 165 Ñ 229 σ
float CSquare::GetArea() { writing, the device is not the console, it is the file. & f ª µ
38 102 166 230
return (h*w); cout is replaced with the file handle. 39 ‘ 103 g 167 º 231 τ
} ofstream f; // create file handle 40 ( 104 h 168 ¿ 232 Φ
// example declaration and usage Templates f.open(“output.txt”) // open file 41 ) 105 i 169 ? 233 Θ
CSquare theSquare; Templates allow functions and classes to be f <<“Hello World\n”<<a<<b<<c<<endl; * j ¬ Ω
42 106 170 234
theSquare.Init(8,5); reused without overloading them 43 + 107 k 171 ½ 235 δ
area = theSquare.GetArea(); template <class id> function; Reading From a File (Text Mode) 44 , 108 l 172 ¼ 236 ∞
// or using a pointer to the class template <typename id> function; The operator >> can be used to read from a file. It 45 - 109 m 173 ¡ 237 φ
CSquare *theSquare; // ---------- function example --------- works similar to cin. Fields are seperated in the file 46 . 110 n 174 « 238 ε
theSquare->Init(8,5); template <class T> by spaces. 47 / 111 o 175 » 239 ∩
area = theSquare->GetArea(); ifstream f; // create file handle 0 p ?
T GetMax (T a, T b) { 48 112 176 240 ≡
return (a>b?a:b); // return the larger f.open(“input.txt”); // open file 49 1 113 q 177 241 ±

} while (!f.eof()) // end of file test 2 r
50 114 178 ▓ 242 ≥
Overloading Operators void main () {
int a=9, b=2, c;
f >>a>>b>>c; // read into a,b,c
51 3 115 s 179 │ 243 ≤
Like functions, operators can be overloaded. 52 4 116 t 180 ┤ 244 ?
float x=5.3, y=3.2, z; I/O State Flags
Imagine you have a class that defines a square Flags are set if errors or other conditions occur. 53 5 117 u 181 ╡ 245 ?
c=GetMax(a,b);
and you create two instances of the class. You can z=GetMax(x,y); The following functions are members of the file 54 6 118 v 182 ╢ 246 ÷
add the two objects together. } object 55 7 119 w 183 ╖ 247 ≈
class CSquare { // declare a class // ----------- class example ----------- handle.bad() returns true if a failure occurs in 56 8 120 x 184 ╕ 248 °
public: // functions template <class T> reading or writing 57 9 121 y 185 ╣ 249 ?
void Init(float h, float w); handle .fail() returns true for same cases as 58 : 122 z 186 250 ·
class CPair { ║
float GetArea(); bad() plus if formatting errors occur
T x,y; 59 ; 123 { 187 ╗ 251 √
CSquare operator + (CSquare); handle.eof() returns true if the end of the file
public: 60 < 124 | 188 ╝ 252 ⁿ
private: // overload the ‘+’ operator reached when reading
float h,w;
Pair(T a, T b){ 61 = 125 } 189 ╜ 253 ²
x=a; y=b; } handle.good() returns false if any of the above 62 > 126 ~ 190 254
} // function implementations ╛ ■
T GetMax(); were true
void CSquare::Init(float hi, float wi){ 63 ? 127 ? 191 ┐ 255
};
h = hi; w = wi; template <class T> Stream Pointers
} T Pair<T>::GetMax() handle.tellg() returns pointer to current location
float CSquare::GetArea() {
return (h*w);
{ // implementation of GetMax function when reading a file Dynamic Memory
T ret; // return a template handle.tellp() returns pointer to current location
}// implementation of overloaded operator Memory can be allocated and deallocated
ret = x>y?x:y; // return larger when writing a file
CSquare CSquare::operator+ (CSquare cs) { // allocate memory (C++ only)
return ret; // seek a position in reading a file
CSquare temp; // create CSquare object pointer = new type [];
} handle.seekg(position);
temp.h = h + cs.h; // add h and w to int *ptr; // declare a pointer
int main () { handle.seekg(offset, direction);
temp.w = w + cs.w; // temp object ptr = new int; // create a new instance
Pair <int> theMax (80, 45); // seek a position in writing a file
return (temp); ptr = new int [5]; // new array of ints
cout << theMax.GetMax(); handle.seekp(position);
} // deallocate memory (C++ only)
return 0; handle.seekp(offset, direction);
// object declaration and usage delete [] pointer;
} direction can be one of the following
CSquare sqr1, sqr2, sqr3; delete ptr; // delete a single int
ios::beg beginning of the stream
sqr1.Init(3,4); // initialize objects delete [] ptr // delete array
ios::cur current position of the stream pointer
sqr2.Init(2,3); // allocate memory (C or C++)
ios::end end of the stream
void * malloc (nbytes); // nbytes=size
sqr3 = sqr1 + sqr2; // object sqr3 is now
(5,7)
Friend Classes/Functions char *buffer; // declare a buffer
Binary Files
Friend Class Example // allocate 10 bytes to the buffer
buffer is a location to store the characters.
class CSquare; // define CSquare buffer = (char *)malloc(10);
numbytes is the number of bytes to written or read.
class CRectangle { // allocate memory (C or C++)
Advanced Class Syntax int width, height;
write(char *buffer, numbytes);
read(char *buffer, numbytes);
// nelements = number elements
public: // size = size of each element
Static Keyword void convert (CSquare a); void * malloc (nelements, size);
Output Formatting
static variables are the same throughout all }; int *nums; // declare a buffer
streamclass f; // declare file handle
instances of a class. class CSquare { // we want to use the // allocate 5 sets of ints
// set output flags
static int n; // declaration private: // convert function in nums = (char *)calloc(5,sizeof(int));
f.flags(ios_base::flag )
CDummy::n; // reference int side; // the CSquare class, so // reallocate memory (C or C++)
possible flag s
public: // use the friend keyword void * realloc (*ptr, size);
dec fixed hex oct
Virtual Members void set_side (int a) { side=a; } // delete memory (C or C++)
scientific internal left right
Classes may have virtual members. If the function friend class CRectangle; void free (*ptr);
uppercase boolalpha showbase showpoint
is redefined in an inherited class, the parent must };
showpos skipws unitbuf
have the word virtual in front of the function void CRectangle::convert (CSquare a) {
adjustfield left | right | internal
definition width = a.side;
basefield dec | oct | hex ANSI C++ Library Files
height = a.side;
floatfield scientific | fixed The following files are part of the ANSI C++
This keyword }
f.fill() get fill character standard and should work in most compilers.
The this keyword refers to the memory location of // declaration and usage
f.fill(c h) set fill character ch <algorithm.h> <bitset.h> <deque.h>
the current object. CSquare sqr;
f.precision( numdigits) sets the precision for <exception.h> <fstream.h> <functional.h>
int func(this); // passes pointer to CRectangle rect; // convert can be
floating point numbers to numdigits <iomanip.h> <ios.h> <iosfwd.h>
// current object sqr.set_side(4); // used by the
f.put( c ) put a single char into output stream <iostream.h> <istream.h> <iterator.h>
rect.convert(sqr); // rectangle class
f.setf(flag) sets a flag <limits.h> <list.h> <locale.h> <map.h>
Class TypeCasting Friend Functions
f.setf(flag, mask) sets a flag w/value <memory.h> <new.h> <numeric.h>
reinterpret_cast <newtype>(expression); A friend function has the keyword friend in front of
f.width() returns the current number of <ostream.h> <queue.h> <set.h> <sstream.h>
dynamic_cast <newtype>(expression); it. If it is declared inside a class, that function can
characters to be written <stack.h> <stdexcept.h> <streambuf.h>
static_cast <newtype>(expression); be called without reference from an object. An
f.width(num) sets the number of chars to be <string.h> <typeinfo.h> <utility.h>
const_cast <newtype>(expression); object may be passed to it.
written <valarray.h> <vector.h>
/* change can be used anywhere and can
Expression Type have a CRect object passed in */
The type of an expression can be found using // this example defined inside a class
© 2002 The Book Company Storrs, CT
typeid. typeid returns a type. friend CRect change(CRect); C++ Reference Card
typeid(expression); CRectangle recta, rectb; // declaration C/C++ Syntax, DataTypes, Functions
refcard@gbook.org
Information contained on this card carries no warranty. No liability is assumed by the maker
rectb = change(recta); // usage Classes, I/O Stream Library Functions of this card for accidents or damage resulting from its use.

You might also like