0% found this document useful (0 votes)
53 views

C++ Cheat Sheet

c++ cheatsheet

Uploaded by

dummymailcs8902
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)
53 views

C++ Cheat Sheet

c++ cheatsheet

Uploaded by

dummymailcs8902
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/ 2

C++ Cheat Sheet Looping Pointers

C++ Data Types while Loop Example A pointer variable (or just pointer) is a variable that stores a
Data Type Description while (expression) while (x < 100) memory address. Pointers allow the indirect manipulation of
bool boolean (true or false) statement; cout << x++ << endl; data stored in memory.
char character ('a', 'b', etc.)
while (expression) while (x < 100)
char[] character array (C-style string if null Pointers are declared using *. To set a pointer's value to the
{ {
terminated) statement; cout << x << endl; address of another variable, use the & operator.
string C++ string (from the STL) statement; x++;
int integer (1, 2, -1, 1000, etc.) } } Example
long int long integer char c = 'a';
float single precision floating point do-while Loop Example char* cPtr;
do do cPtr = &c;
double double precision floating point
statement; cout << x++ << endl;
These are the most commonly used types; this is not a while (expression); while (x < 100);
complete list. Use the indirection operator (*) to access or change the
do do value that the pointer references.
{ {
Operators statement; cout << x << endl; Example
statement; x++; // continued from example above
The most commonly used operators in order of precedence:
} } *cPtr = 'b';
1 ++ (post-increment), -- (post-decrement) while (expression); while (x < 100); cout << *cPtr << endl; // prints the char b
2 ! (not), ++ (pre-increment), -- (pre-decrement)
cout << c << endl; // prints the char b
3 *, /, % (modulus) for Loop
4 +, - for (initialization; test; update)
5 <, <=, >, >= statement;
Array names can be used as constant pointers, and pointers
6 == (equal-to), != (not-equal-to) can be used as array names.
for (initialization; test; update)
7 && (and) {
8 || (or) statement; Example
9 = (assignment), *=, /=, %=, +=, -= statement; int numbers[]={10, 20, 30, 40, 50};
} int* numPtr = numbers;
cout << numbers[0] << endl; // prints 10
Console Input/Output cout << *numPtr << endl; // prints 10
Example
cout << numbers[1] << endl; // prints 20
cout << console out, printing to screen for (count = 0; count < 10; count++)
cout << *(numPtr + 1) << endl; // prints 20
{
cout << numPtr[2] << endl; // prints 30
cout << "count equals: ";
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)
Variable is passed into the function but Definition Example
statement; cout << x;
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
class Student
type member2; float getArea(); // or this code might test and throw
{ // exceptions directly
protected: private:
type member3; float width; public: if (num3 < 0)
Student(string n, string id);
private: }; throw -1; // exception to be thrown can
void print();
type member4; // 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, cout << exceptionString;
protected members are accessible from the same class, string prev);
derived classes, or a friend (function or class). exit(-2);
void print(); }
protected: // add more catch blocks as needed
constructors may be overloaded just like any other string prevDegree;
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
etc.) work with classes that you write. For example, to use int a=9, b=2, c;
void Square::setWidth(float w) c = getMax(a, b);
{ the operator + with your class, you would write a function
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
{ Example
return width*width; template <class T>
}
If the object that receives the function call is not an instance
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();

You might also like