You are on page 1of 2

C++ Reference Card Looping Pointers

while Loop Example A pointer variable (or just pointer) is a variable that stores a
C++ Data Types while (expression) while (x < 100) memory address. Pointers allow the indirect manipulation of
statement; cout << x++ << endl; data stored in memory.
Data Type Description
bool boolean (true or false) while (expression) while (x < 100)
Pointers are declared using *. To set a pointer's value to the
char character ('a', 'b', etc.) { {
address of another variable, use the & operator.
char[] character array (C-style string if null statement; cout << x << endl;
statement; x++;
terminated) Example
} }
string C++ string (from the STL) char c = 'a';
int integer (1, 2, -1, 1000, etc.) char* cPtr;
do-while Loop Example
long int long integer do do cPtr = &c;
float single precision floating point statement; cout << x++ << endl;
double double precision floating point while (expression); while (x < 100);
Use the indirection operator (*) to access or change the
These are the most commonly used types; this is not a do do value that the pointer references.
complete list. { {
statement; cout << x << endl; Example
statement; x++;
Operators } }
// continued from example above
*cPtr = 'b';
The most commonly used operators in order of precedence: while (expression); while (x < 100); cout << *cPtr << endl; // prints the char b
1 ++ (post-increment), -- (post-decrement) cout << c << endl; // prints the char b
2 ! (not), ++ (pre-increment), -- (pre-decrement) for Loop
for (initialization; test; update)
3 *, /, % (modulus) statement;
4 +, - Array names can be used as constant pointers, and pointers
can be used as array names.
5 <, <=, >, >= for (initialization; test; update)
6 == (equal-to), != (not-equal-to) {
statement; Example
7 && (and) int numbers[]={10, 20, 30, 40, 50};
statement;
8 || (or) } int* numPtr = numbers;
9 = (assignment), *=, /=, %=, +=, -= cout << numbers[0] << endl; // prints 10
Example cout << *numPtr << endl; // prints 10
for (count = 0; count < 10; count++) cout << numbers[1] << endl; // prints 20
Console Input/Output { cout << *(numPtr + 1) << endl; // prints 20
cout << "count equals: "; cout << numPtr[2] << endl; // prints 30
cout << console out, printing to screen
cout << count << endl;
cin >> console in, reading from keyboard
}
cerr << console error Dynamic Memory
Example: Allocate Memory Examples
cout << "Enter an integer: "; Functions ptr = new type; int* iPtr;
cin >> i; iPtr = new int;
cout << "Input: " << i << endl; Functions return at most one value. A function that does not
return a value has a return type of void. Values needed by ptr = new type[size]; int* intArray;
a function are called parameters. intArray = new int[5];
File Input/Output
Example (input): return_type function(type p1, type p2, ...)
Deallocate Memory Examples
ifstream inputFile; {
delete ptr; delete iPtr;
inputFile.open("data.txt"); statement;
delete [] ptr; delete [] intArray;
inputFile >> inputVariable; statement;
// you can also use get (char) or ...
} Once a pointer is used to allocate the memory for an array,
// getline (entire line) in addition to >>
array notation can be used to access the array locations.
...
inputFile.close(); Examples
int timesTwo(int v) Example
{ int* intArray;
Example (output):
int d; intArray = new int[5];
ofstream outFile;
d = v * 2; intArray[0] = 23;
outfile.open("output.txt");
return d; intArray[1] = 32;
outFile << outputVariable;
... }
outFile.close();
void printCourseNumber() Structures
{
Decision Statements cout << "CSE1284" << endl; Declaration Example
return; struct name struct Hamburger
if Example } { {
if (expression) if (x < y) type1 element1; int patties;
statement; cout << x; type2 element2; bool cheese;
Passing Parameters by Value }; };
if / else Example
return_type function(type p1)
if (expression) if (x < y)
statement; cout << x;
Variable is passed into the function but Definition Example
changes to p1 are not passed back. name varName; Hamburger h;
else else
statement; cout << y;
Passing Parameters by Reference name* ptrName; Hamburger* hPtr;
switch / case Example return_type function(type &p1) hPtr = &h;
switch(int expression) switch(choice) Variable is passed into the function and
{ { changes to p1 are passed back. Accessing Members Example
case int-constant: case 0: varName.element=val; h.patties = 2;
statement(s); cout << "Zero"; Default Parameter Values h.cheese = true;
break; break; return_type function(type p1=val)
case int-constant: case 1: val is used as the value of p1 if the ptrName->element=val; hPtr->patties = 1;
statement(s); cout << "One"; function is called without a parameter. hPtr->cheese = false;
break; break;
default: default:
Structures can be used just like the built-in data types in
statement; cout << "What?";
} } arrays.
Classes Inheritance Exceptions
Declaration Example Inheritance allows a new class to be based on an existing Example
class classname class Square class. The new class inherits all the member variables and try
{ { functions (except the constructors and destructor) of the {
public: public: class it is based on. // code here calls functions that might
classname(params); Square(); // throw exceptions
~classname(); Square(float w); quotient = divide(num1, num2);
type member1; void setWidth(float w); Example
type member2; float getArea(); class Student // or this code might test and throw
protected: private: { // exceptions directly
type member3; float width; public: if (num3 < 0)
private: }; Student(string n, string id); throw -1; // exception to be thrown can
type member4; void print(); // be a value or an object
}; protected: }
string name; catch (int)
string netID;
public members are accessible from anywhere the class is };
{
visible. cout << "num3 can not be negative!";
exit(-1);
class GradStudent : public Student
private members are only accessible from the same class {
}
or a friend (function or class). catch (char* exceptionString)
public: {
GradStudent(string n, string id,
protected members are accessible from the same class, string prev);
cout << exceptionString;
derived classes, or a friend (function or class). exit(-2);
void print(); }
protected:
constructors may be overloaded just like any other string prevDegree;
// add more catch blocks as needed
function. You can define two or more constructors as long };
as each constructor has a different parameter list.

Visibility of Members after Inheritance Function Templates


Definition of Member Functions Inheritance Access Specifier in Base Class Example
return_type classname::functionName(params) Specification private protected public template <class T>
{ private - private private T getMax(T a, T b)
{
statements; protected - protected protected
} if (a>b)
public - protected public return a;
else
Examples
return b;
Square::Square()
}
{
width = 0; Operator Overloading
}
C++ allows you to define how standard operators (+, -, *, // example calls to the function template
void Square::setWidth(float w)
etc.) work with classes that you write. For example, to use int a=9, b=2, c;
{ the operator + with your class, you would write a function c = getMax(a, b);
if (w >= 0) named operator+ for your class.
float f=5.3, g=9.7, h;
width = w;
h = getMax(f, g);
else Example
exit(-1); Prototype for a function that overloads + for the Square
} class:
Square operator+ (const Square &);
float Square::getArea() Class Templates
{
return width*width; Example
} If the object that receives the function call is not an instance template <class T>
of a class that you wrote, write the function as a friend of class Point
your class. This is standard practice for overloading << and {
>>. public:
Definition of Instances Example Point(T x, T y);
classname varName; Square s1(); void print();
Square s2(3.5); Example double distance(Point<T> p);
Prototype for a function that overloads << for the Square private:
classname* ptrName; Square* sPtr; class: T x;
sPtr=new Square(1.8); friend ostream & operator<< T y;
(ostream &, const Square &); };
Accessing Members Example
varName.member=val; s1.setWidth(1.5);
varName.member(); cout << s.getArea(); Make sure the return type of the overloaded function // examples using the class template
matches what C++ programmers expect. The return type of Point<int> p1(3, 2);
ptrName->member=val; cout<<sPtr->getArea(); Point<float> p2(3.5, 2.5);
ptrName->member();
relational operators (<, >, ==, etc.) should be bool, the
p1.print();
return type of << should be ostream &, etc. p2.print();

Suggested Websites
C++ Reference: http://www.cppreference.com/ http://www.informit.com/guides/guide.aspx?g=cplusplus
C++ Tutorial: http://www.cplusplus.com/doc/tutorial/ http://www.sparknotes.com/cs/
C++ Examples: http://www.fredosaurus.com/notes-cpp/
Gaddis Textbook:
Video Notes http://media.pearsoncmg.com/aw/aw_gaddis_sowcso_6/videos
Source Code ftp://ftp.aw.com/cseng/authors/gaddis/CCSO5 (5th edition)

Developed for Mississippi State University's CSE1284 and CSE1384 courses February 17, 2009
Download the latest version from http://cse.msstate.edu/~crumpton/reference

You might also like