C++ Resources

Updated on Nov 1  2020



C++SyntaxQuickReference

Deborah R. Fowler



Syntax Quick Reference

Posted 2013
Update April 22  2014

Sample files exist in the dropbox. This table is not a substitute for your textbook or you own notes but simply a quick reference for those of you who are less familiar with the syntax or are switching back and worth between languages to look up the syntax quickly.

C++ is compiled. See the compiling summary table or use an IDE such as Visual Studio 2010 or Eclipse.

Variables
  • are strongly typed in C++  ie.) int, float, double, char, bool
  • Newly declared variables have undefined value - INITIALIZE before use
  • should be named meaningfully (coding standards) ie. hps is not good, hitsPerSecond is good -
  • name can't be a keyword or start with a number
  • strings - you can use the new string library  (ie. no need to define an array of char)
    #include <string>
    string myStringVariableName;
  • Global variable are NOT good programming style in general
Constants
  •  make good clearer and avoid "magic" numbers
  • const datetype NAME - by convention, constants are in all caps, for example:
  • const int MAX_HIT_POINTS = 100;


Random Numbers

#include <cstdlib>
#include <ctime>

srand( time(0) );
int randomNumber = rand();

Notation

Popular Shorthand
Common Symbols
    x = x + 1;   
    x += 1;    
    x++;       
    ++x;  
 

// All of these increment x by one
  • ++ prefix increments and then uses
  • ++ postfix uses and then increments

endl is equivalent to "\n" and represent a new line


!=

==
<=
>=
<
>
%
Blocks
  • defined with curly braces
  • make it visually easy to see these (on their own line - coding standard)
         {
        
}
If/then/else

if ( condition )
{
    statements;
}
else
{
    statements;
}
Looping
  • while
  • for
  • do while
while( condition )
{
        // do something
}
for ( int i = 0; i < something; ++i )
{
        // do something
}
do
{
        // do something
} while ( condition);
Functions

int myFunction()
{
        statements;
        return 0;  // return some value
}


Coding Style:
declartion and definition to identify the function at the top and define below main (later to be in their own files, ultimately wrapped in classes)


int myFunction();  // declaration
int myFunction()
{
        // some code to do something
        return 0; // return value must match
}
Procedures (functions that act on data but don't explicitly return a value) - now mostly lumped under the word functions

void myFunction()
{
        statements;
}
Parameters/Arguments

When you have information to pass back and forth, these go in the (), for example

int myFunction( int x, float y )
{
        int resultVariable;
        // x and y are parameters and are local to the function
        // they take on the value of the argument
        return resultVariable;
}

To call a function (or procedure) you call its name, for example to run this piece of code

int resultFromCalling = myfunction( 10, 12.6 )

Pass by Value is default
Pass by Reference and Pass by Pointer will be heavily used
and are discussed below

Arrays
int myArray[3];
int myArray[5] = { 10, 15, 2, 35, 41 };

remember C++ starts at 0

myArray[0] = 5;

Vectors (new improved "lists")
#include <vector>
using namespace std;

vector<int> myVector;  // declare
myVector.push_back(0); // make a space

myVector.size();
myVector.begin();
myVector.end();
Also available:
#include <algorithm>
// to allow use of find, sort etc.
Interators (hinting at pointers)
vector<int>::iterator myIterator;
for ( myIterator = grades.begin(); myIterator != grades.end(); ++myIterator )
{
        cout << *myIterator << endl; // note the dereference
}

This has the same functionality as:
for ( int i = 0;  i < grades.size(); ++i )
{
        cout << grades[i] << endl;
}

myIterator = find( grades.begin(), grades.end(), searchValue );
sort ( grades.begin(), grades.end() );
Pointers
  • variables that store a memory address to another variable
  • declared with * prefix
  • for example int *pNum;
  • naming convention to use small p prefix

For example:
int myVariable;
int *pNum = &myVariable;

* to access the variable pointed to or declare a pointer
& to get the addres of a variable (this symbol is also use for "reference")

References provide another name for a variable (like a nickname) - not to be confused with pointers.
int myScore = 1000;
int &ranotherNameForScore = myScore;
 // results in two name referencing the same thing - useful for passing to functions, but better to use pointers

Classes
  • functions and data of all kinds all in one wrapper or "object" hence the name 00P
  • by convention first letter capitalized
  • class definition end in a semi-colon
  • Terminology: class ia a definition,
    object is an instance

class NameOfClass
{
public:
        int x;
        int y;
};

referred to data members and member functions with the dot operator
NameOfClass ThisOne;
ThisOne.x = 3;

Default invisible constructors. If you want to explicitly define:
NameOfClass::NameOfClass

Destructors use the symbol ~
Notation for Classes

// usually in a .h file
class SomeClass
{
public:
     int x;
     int myFunction();
}

// usually in a .cpp file
int SomeClass:: myFunction()
{
        // usual function stuff here, including return
}

SomeClass MyObject;
SomeClass *pMyObject = &MyObject;
cout <<  (*pMyObject).x;
cout << MyObject.x;

Since pointers to objects are used so often, two conveniences are:

SomeClass *pMyObject = new SomeClass();
cout << pMyObject->x;
delete pMyObject;
Inheritance and Polymorphism (more in class)
Use the : after the class name to inherit
polymorphism is using the pointer to figure out the right thing to do

Buzz words in a nutshell
Modularity - repeating code effectively, testing as you go (Functions help with all these)
Encapsulation - scoping/hiding to protect data/errors
Abstraction - don't sweat the details/(plan using algorithms, outline-refine)



Note: Structure vs OOP
A structured program is organized by functions, main calls other functions - it is a series of functions and relationships between them.
OOP (Object-oriented programming) - code is organized by objects - an object contains both variable and functions, but now the program is a series of object (with a little bit of code in main() typing them together to say how they are used.

Which to use? Ask does your program do something (with minimal user intervention) or does it react to something (like user input). Most do both, but which dominates?

Note about shorthand initialization of variables in constructors ie. NameOfClass::NameOfClass( int x ) : memberData(x) found here.