Code Reference
T.'s Database
C++ Syntax

//C++ Comments:

  • //Compiler ignores comments - they don't affect execution.

  • //Single-Line Comments...
    1. //I'm a single-line comment!
  • //Multi-Line Comments...
    1. /*
    2. I'm a...
    3. ...multi-line comment!
    4. */
  • Read More...

//C++ Header Files:

  • //INCLUDING HEADER FILES:
  • //#include <headerFileName>

  • //Including External Files
    1. //If function definitions are in external files they must be included to be used
    2. //Place includes at the top of the main file or the top of an included header file
    3. #include <cstdlib>   //Includes some basic functions
    4. #include <iostream>   //Includes functions for stream input & output
    5. #include <iomanip>   //Includes functions for input & output manipulation
    6. #include <fstream>   //Includes functions for file input & output
    7. #include <ofstream>   //Includes functions for file output
    8. #include <ifstream>   //Includes functions for file input
    9. #include <cmath>   //Includes functions for mathematical operations
    10. #include <vector>   //Includes functions for vector math
    11. #include <algorithm>   //Includes functions ranges of elements
  • Read More...
  • //CREATING HEADER FILES:
  • //#ifndef FILENAME_H
  • //#define FILENAME_H
  • //headerFileCode; #endif

  • //Using ifndef...endif Structure
    1. //Save header files with the .h extension like “myHeader.h”

    2. //The ifndef...endif structure prevents multiple instances of linked header files
    3. //Place the ifndef and define lines at the top of the file
    4. #ifndef MYHEADER_H
    5. #define MYHEADER_H

    6. //code for function libraries or class declarations goes here

    7. //Place the endif line at the end of the file
    8. #endif


    9. //If the filename is myHeader.h, include it in the main file as follows:
    10. #include “myHeader.h”
  • Read More...

//C++ Data Types & Variables:

  • //DATA TYPES:
  • //Data Types usable in Variables & Function Declarations:
NameDescriptionValue Range
boolBoolean
(True/False)
true or false
charSingle Character
(Letters)
signed: -128 to 127   //ASCII Values
unsigned: 0 to 255   //ASCII Values
intInteger
(Whole Numbers)
signed: -2147483648 to 2147483647
unsigned: 0 to 4294967295
floatFloating Point Number
(Decimal #'s w/ 7 digits)
minimum: 1.175494351 E -38
maximum: 3.402823466 E +38
doubleDouble Precision Floating Pt
(Decimal #'s w/ 16 digits)
minimum: 2.2250738585072014 E -308
maximum: 1.7976931348623158 E +308
stringString of Characters
(Like a Sentance)
Lots of “Letters”
  • //DECLARING & INITIALIZING VARIABLES:
  • //dataType varName = value;

  • //Declaring & Initializing basic Variables...
    1. bool isTrue = true;   //false == 0, true == anything but zero
    2. char aLetter = ‘Y’;
    3. int intNum = 5;
    4. float floatNum = 5.125;
    5. double doubleNum = 2.2250738585072014;
    6. string sentance = “whatever”;

    7. //You can also Declare and Initialize multiple Variables in the same line...
    8. int intNum1 = 5, intNum2 = 10;
  • Read More...

//C++ Special Characters (used in Strings):

  • //Special Characters usable in strings:
SymbolNameDescription
“  \n  ”NewlineCreates a new line character or carriage return.
“  \t  ”Horizontal TabCreates a horizontal tab space.
“  \v  ”Vertical TabCreates a vertical tab space.
“  \b  ”BackspaceDeletes back one space like a backspace.
“  \\  ”BackslashCreates a backslash character.
“  \?  ”Question MarkCreates a question mark.
“  \'  ”Single QuoteCreates a single quotation mark.
“  \"  ”Double QuoteCreates a double quotation mark.
“  \0  ”NullCreates a NULL character.

//C++ Operators:

  • //ASSIGNMENT & CONCATENATION OPERATORS:
SymbolNameExample
=AssignmentvarName = 5;   //5 is saved in varName
+ConcatenationvarName = “My name is ” + “Terrance.”
//varName will now equal “My name is Terrance.”
  • //STREAM OPERATORS:
SymbolNameExample
<<Stream Insertioncout << 5;   //sends 5 to the output device
>>Stream Extractioncin >> varName;   //saves from input device
  • //ARITHMETIC OPERATORS:
SymbolNameExample
+AdditionaNum = 1 + 2;   //aNum = 3
-SubtractionaNum = 3 - 2;   //aNum = 1
*MultiplicationaNum = 2 * 3;   //aNum = 6
/DivisionaNum = 13 / 5;   //aNum = 2 (ignore remainder)
%ModuloaNum = 13 % 5;   //aNum = 3 (remainder)
  • //COMPOUND ASSIGNMENT OPERATORS:
SymbolNameExample
+=Plus EqualsaNum += 4;   //aNum = aNum + 4
+=Concatenation EqualsaString += “ more letters.”;
//aString = aString + “ more letters.”
-=Minus EqualsaNum -= 4;   //aNum = aNum - 4
*=Multiply EqualsaNum *= 4;   //aNum = aNum * 4
/=Divid EqualsaNum /= 4;   //aNum = aNum / 4
%=Modulo EqualsaNum %= 4;   //aNum = aNum % 4
--DecrementaNum--;   //aNum = aNum - 1
++IncrementaNum++;   //aNum = aNum + 1
++varPre-IncrementmyNum = ++urNum;
//myNum = urNum + 1, urNum = urNum + 1
var++Post-IncrementmyNum = urNum++;
//myNum = urNum, urNum = urNum + 1
--varPre-DecrementmyNum = --urNum;
//myNum = urNum - 1, urNum = urNum - 1
var--Post-DecrementmyNum = urNum--;
//myNum = urNum, urNum = urNum - 1
  • //RELATIONAL OPERATORS:
SymbolNameExample (Used in expressions)
==Equal to(a == b)   //returns true if a equals b
!=Not Equal to(a != b)   //returns true if a doesn't equal b
>Greater than(a > b)   //returns true if a is greater than b
<Less than(a < b)   //returns true if a is less than b
>=Greater than or equal to(a >= b)
//returns true if a is greater than or equal to b
<=Less than or equal to(a <= b)
//returns true if a is less than or equal to b
  • //LOGICAL OPERATORS:
SymbolNameExample (Used in expressions)
!Not(!true)   //returns false (the opposite)
&&And(a == b && b > c)   //returns true if both sides are true
||Or(a == b || b > c)   //returns true if either side is true
  • //BITWISE OPERATORS:
SymbolNameExample (Used with binary values)
&AndaNum = 11 & 5;   //aNum = 1 (“and”s each bit)
//11 = 1011 (binary) and 5 = 0101 so... 0001 (binary) = 1
|Inclusive OraNum = 12 | 9;   //aNum = 13 (“or”s each bit - 1 | 1 = 1)
//12 = 1100 (binary) and 9 = 1001 so... 1101 (binary) = 13
^Exclusive OraNum = 12 ^ 9;   //aNum = 5 (“or”s each bit - 1 ^ 1 = 0)
//12 = 1100 (binary) and 9 = 1001 so... 0101 (binary) = 5
<<Left-ShiftaNum = 16 << 4;   //aNum = 256 (shift bits 4 spaces)
//16 = 10000 (binary) so... 100000000 (binary) = 256
>>Right-ShiftaNum = 16 >> 2;   //aNum = 4 (shift bits 2 spaces)
//16 = 10000 (binary) so... 100 (binary) = 4
  • //OVERLOADING OPERATORS:
  • //className operatorName(const classNameReference);

  • //Overloaded Operators...
    1. //See “OVERLOADING OPERATORS” section under C++ Classes
  • Read More...

//C++ Arrays:

  • //SINGLE-DIMENSIONAL ARRAYS:
  • //dataType varName[elementNum] = {value, value, ...};

  • //Declaring & Initializing Single-Dimensional Arrays...
    1. dataType varName[integerValue] = {value, value, ...};

    2. //example...
    3. //A Single-Dimensional Array is like a list.
    4. //An integer Array
    5. int anArray[3] = {0};   //This will initialize ALL elements in the array to 0!
    6. int anArray2[3] = {1, 2};
      //Saves 1 and 2 to the 1st 2 elements and 0 in ALL others!

    7. int myArray[5] = {0, 1, 2, 3, 4};   //indexing for Arrays start at 0 so...
    8. cout << myArray[0];   //This statement will print 0 to the screen

    9. //Assignment works similar to Variables...
    10. myArray[3] = 25;   //The fourth element in myArray is now 25

    11. //One thing to remember about Arrays...
    12. //int myArray[5]; will create an Array with 5 elements
    13. //But the last element (the 5th one) will be referenced with myArray[4]
  • Read More...
  • //MULTI-DIMENSIONAL ARRAYS:
  • //dataType varName[elementNum][elementNum] ... = {value, value, ...};

  • //Declaring & Initializing Multi-Dimensional Arrays...
    1. dataType varName[integerValue][integerValue] ... = {value, value, ...};

    2. //example...
    3. //Two-Dimensional Arrays are like a grid.
    4. //Multi-Dimensional Arrays can eat up a LOT of memory so be careful!

    5. //A Two-Dimensional integer Array
    6. int myArray[3][5] = {0};   //This will initialize ALL elements in the array to 0!
    7. int myArray2[3][5] = {1, 2};
      //Saves 1 and 2 to the 1st 2 elements and 0 in ALL others!

    8. int anArray[3][5] = {    0,    1,   2,    3,    4,
    9.                                  5,    6,   7,    8,    9,
    10.                                10,  11,  12,  13,  14    };
    11. //Using nested for loops to print the values in a Multi-Dimensional Array
    12. for(int i = 0; i < 3; i++) {   //Loops for index i = 0 - 2 (3 times)
    13.      for(int f = 0; f < 5; f++) {   //Loops for index f = 0 - 4 (5 times)
    14.           cout << anArray[i][f] << “, ”;
    15.      }
    16.      //Start a new row after a value for every column is printed...
    17.      cout << endl;
    18. }

    19. //A Two-Dimensional boolean Array
    20. bool anotherArray[3][5];
    21. //Using nested for loops to initialize the Multi-Dimensional Array
    22. for(int i = 0; i < 3; i++) {   //Loops for index i = 0 - 2 (3 times)
    23.      for(int f = 0; f < 5; f++) {   //Loops for index f = 0 - 4 (5 times)
    24.           anotherArray[i][f] = false;
    25.      }
    26. }
  • Read More...

//C++ Decision Structures:

  • //IF/ELSE IF/ELSE STATEMENTS:
  • //decisionType(expression) { codeToExecute; }

  • //Using If/Else If/Else Statements...
    1. if(expressionIsTrue) {
    2. }
    3. else if(expressionIsTrue) {
    4. }
    5. else {
    6. }

    7. //example...
    8. int varName = 0;
    9. //only one of the following will execute...
    10. //if(expressionIsTrue) { codeToExecute; }
    11. if(varName == 1) {

    12. }
    13. //else if(expressionIsTrue) { codeToExecute; }
    14. else if(varName == 2) {   //if not equal to 1 is it 2

    15. }
    16. //else { codeToExecute; }
    17. else {   //any value except 1 or 2

    18. }
  • Read More...
  • //SWITCH STATEMENTS:
  • //switch(varName) { case value: codeToExecute; break; ... default: codeToExecute; }

  • //Using Switch Statements...
    1. switch(varName) {
    2.      case value:
    3.           break;
    4.      case value:
    5.           break;
    6.      default:
    7. }

    8. //example...
    9. //void srand(unsignedIntegerValue);
    10. srand(time(NULL));   //Initialize random number generator
    11. int i = rand() % 100;   //Limits random number to 0 - 99
    12. //switch(var) { case varValue: codeToExecute; break; default: }
    13. switch(i) {
    14.      //if using a char value you need single quotes - 'A'
    15.      case 0:
    16.           //code for when i = 0;
    17.           break;
    18.      case 1:
    19.           //code for when i = 1;
    20.           break;
    21.      default:
    22.           //code for default processing; - like else statement
    23. }
  • Read More...

//C++ Looping Structures:

  • //WHILE LOOPS:
  • //while(expressionIsTrue) { codeToExecute; }

  • //Using While Loops...
    1. while(expressionIsTrue) {
    2. }

    3. //example...
    4. //while(expressionIsTrue) { codeToExecute; }
    5. while(varName < 10) {
    6.      //code here will execute repeatedly as long as varName is less than 10
    7. }
  • Read More...
  • //DO...WHILE LOOPS:
  • //do { codeToExecute; }while(expressionIsTrue);

  • //Using Do...While Loops...
    1. do {
    2. }while(expressionIsTrue);

    3. //example...
    4. //do...while loops will ALWAYS execute at least once...
    5. //do { codeToExecute; }while(expressionIsTrue);
    6. do {
    7.      //code here will execute once & repeat while varName is less than 10
    8. }while(varName < 10);
  • Read More...
  • //FOR LOOPS:
  • //for(int indexVarName = startValue; indexVarName expressionWhileTrue; indexVarName loopIncrementation) { codeToExecute; }

  • //Using For Loops...
    1. for(int indexVarName = value; indexVarName expressionWhileTrue; indexVarName loopIncrementation) {
    2. }

    3. //example...
    4. //for(startingCondition; exitCondition; iteration) { codeToExecute; }
    5. for(int i = 0; i < 10; i++) {
    6.      //code here will execute exactly 10 times (where i = 0 to 9)
    7. }
  • Read More...

//C++ Pointers & Referencing:

  • //POINTERS:
  • //dataType *varName = memoryAddress;

  • //Declaring & Initializing Pointers...
    1. /*
    2. Pointers point to locations in memory
    3. It's faster to redirect pointers than to overwrite values
    4. Pointers are great for sorting arrays!
    5. */
    6. dataType *varName = memoryAddress;

    7. //example...
    8. //Assigning Memory Addresses to Pointers...
    9. int intVariable = 75;
    10. //There are two ways to assign a memory location to declared pointers...
    11. int *intPointer;
    12. *intPointer = intVariable;   //or...
    13. intPointer = &intVariable;
    14. //There's only one way to declare & initialize pointers in one line...
    15. int *intPointer = &intVariable;

    16. //Extracting data from Pointers...
    17. cout << intPointer << endl;   //returns Memory Address of pointer
    18. cout << &intPointer << endl;   //returns Memory Address of pointer
    19. cout << *intPointer << endl;   //returns Value stored at pointer

    20. //Using Values stored at Pointer locations...
    21. *intPointer = 85;   //Saves value 85 to location intPointer is pointing
    22. int aNumber = *intPointer;   //Saves the pointer's value to a variable

    23. //Pointers are similar to arrays - an index can access adjacent values...
    24. cout << intPointer[0] << endl;   //returns Value stored at pointer
    25. cout << intPointer[1] << endl;   //returns Value stored at next location
    26. cout << &intPointer[0] << endl;   //returns Memory Address of pointer
    27. cout << &intPointer[1] << endl;   //returns Address of next location

    28. //Dynamically Allocating Memory with Pointers...
    29. int *intPointer;   //Declare a Pointer to the Integer Data Type
    30. intPointer = new int;   //Dynamically Allocate a new place in memory
    31. intPointer = new int[10];   //Integer Pointers can also point to Integer Arrays

    32. //You can also Declare and Initialize a pointer in the same line...
    33. bool *boolPointer = new bool[10];   //A Boolean Pointer
    34. char *charPointer = new char[10];   //A Character Pointer
    35. int *intPointer = new int[10];   //An integer Pointer
    36. float *floatPointer = new float[10];   //A Floating Point Pointer
    37. double *doublePointer = new double[10];   //A Double Floating Point Pointer
    38. string *stringPointer = new string[10];   //A String Pointer

    39. //Practical Example...
    40. #include <cstdlib>
    41. #include <iostream>
    42. using namespace std;

    43. int main(int argc, char *argv[]) {
    44.      int size = 0;
    45.      char tempChar[100] = “\0”;

    46.      cout << “Please enter the number of names for the list: ”;
    47.      cin >> size;
    48.      cin.ignore();
    49.      cout << endl;

    50.      string *stringList = new string[size];

    51.      for(int i = 0; i < size; i++) {
    52.           cout << “Please enter a name: ”;
    53.           cin.getline(tempChar, 100);
    54.           stringList[i] = tempChar;
    55.      }

    56.      cout << “\nThe names are:\n”;
    57.      for(int i = 0; i < size; i++) {
    58.           cout << stringList[i] << endl;
    59.      }
    60.      cout << endl;

    61.      system(“PAUSE”);
    62.      return EXIT_SUCCESS;
    63. }
  • Read More...
  • //REFERENCING:
  • //dataType varName& = value;

  • //Using a Reference...
    1. dataType varName&;

    2. //A Reference is like a copy of an object so you cannot change the value of the original
    3. //They are used...
  • Read More...

//C++ Functions:

  • //FUNCTION PROTOTYPES:
  • //returnDataType functionName(dataTypesOfParameters);

  • //Syntax for Function Prototypes...
    1. returnDataType functionName(dataType, dataType, ...);

    2. //example...
    3. //prototype for a function to return an integer value
    4. int getHours(int, bool);
  • Read More...
  • //FUNCTION DEFINITIONS:
  • //returnDataType functionName(dataTypesOfParameters varNames) { }

  • //Syntax for Function Definitions...
    1. returnDataType functionName(dataType varName, dataType varName, ...) {
    2.      return value;
    3. }

    4. //example...
    5. //definition for a function to return an integer value
    6. int getHours(int aNumber, bool isTrue) {
    7.      //Code to complete the function algorithm goes here
    8.      return 5;   //MUST return integer because of returnType
    9. }
  • Read More...
  • //CALLING FUNCTIONS:
  • //varName = functionName( parameterValues );

  • //Syntax for Calling Functions...
    1. returnDataType = functionName(varName, varName, ...);

    2. //example...
    3. int totalHours = 0;
    4. //function call for a function to return an integer value
    5. totalHours = getHours(15, true);
  • Read More...
  • //FRIEND FUNCTIONS:
  • //friend returnDataType functionName(dataTypesOfParameters);

  • //Friend Functions...
    1. //See “FRIEND FUNCTIONS TO A CLASS” section under C++ Classes
  • //OVERLOADING FUNCTIONS:
  • //returnDataType functionName(dataTypesOfParameters);

  • //Overloading Functions...
    1. //An Overloaded function has multiple definitions w/ different parameters
    2. //The MUST be a different number of parameters or different dataTypes
    3. returnDataType overloadedFunctionName(dataTypeOfParameter)
    4. returnDataType overloadedFunctionName(dataTypeOfParameter, dataTypeOfParameter)

    5. //example...
    6. //Valid Overloaded Function Prototypes...
    7. //Notice that the returnDataType & the functionName stay the same
    8. //ONLY the parameters change!
    9. int overloadMe();
    10. int overloadMe(bool);
    11. int overloadMe(int);
    12. int overloadMe(int, int);

    13. //Valid Overloaded Function Definitions...
    14. int overloadMe() {
    15.      //Code to complete the function algorithm
    16.      return integerValue;
    17. }
    18. int overloadMe(bool varName) {
    19.      //Code to complete the function algorithm
    20.      return integerValue;
    21. }
    22. int overloadMe(int varName) {
    23.      //Code to complete the function algorithm
    24.      return integerValue;
    25. }
    26. int overloadMe(int varName, int varName) {
    27.      //Code to complete the function algorithm
    28.      return integerValue;
    29. }

    30. //Calling Valid Overloaded Functions...
    31. int num1 = 0, num2 = 0, num3 = 0, num4 = 0;
    32. bool isTrue = false;
    33. num1 = overloadMe();
    34. num1 = overloadMe(isTrue);
    35. num1 = overloadMe(num2);
    36. num1 = overloadMe(num3, num4);
  • Read More...

//C++ Classes:

  • //DECLARING A CLASS:
  • //class className { public: protected: private: };

  • //Declaring a Class with Member Function Prototypes...
    1. //Class Declarations should be saved in separate header files
    2. class className {
    3.      public:
    4.      protected:
    5.      private:
    6. };

    7. //example...
    8. class addClass {
    9.           //Anything above declared sections defaults to public

    10.      public:
    11.           //Code within public is available to all modules
    12.           //Generally speaking it's good to put your functions in public
    13.           addClass();   //Default Constructor
    14.           ~addClass();   //Destructor
    15.           int addNum(int, int);
    16.           int getNumOne();   //Accessor

    17.      protected:
    18.           //Code within protected is ONLY available to child classes
    19.           //Private data MUST be here to be accessed with inherited classes

    20.      private:
    21.           //Code within private is ONLY availabe to this class
    22.           //Generally speaking it's good to put your data in private
    23.           int num1;
    24.           int num2;
    25. };
  • Read More...
  • //CLASS MEMBER FUNCTION DEFINITIONS:
  • //returnType className::functionName( dataTypesOfParameters varNames) { }

  • //Inline Class Member Function Definitions...
    1. //Inline Class Member Function Definitions...
    2. inline returnDataType className::functionName(dataType varName, dataType varName, ...) {
    3.      return value;
    4. }

    5. //example...
    6. //Inline Definitions MUST be in the same file as the Class Declaration
    7. //NEVER dynamically allocate memory in a header file!
    8. //ONLY simple functions should be defined inline like Accessors...
    9. inline int addClass::getNumOne() {
    10.      //All member functions can access num1 because it's a member too
    11.      return num1;
    12. }

  • //Non-Inline Class Member Function Definitions...
    1. //Non-Inline Class Member Function Definitions...
    2. returnDataType className::functionName(dataType varName, dataType varName, ...) {
    3.      return value;
    4. }

    5. //example...
    6. //Non-Inline Definitions MUST be in a different file
    7. //Non-Inline Definitions MUST #include “headerFileName.h”
    8. int addClass::addNum(int num1, int num2) {
    9.      int total = num1 + num2;
    10.      return total;
    11. }
  • Read More...
  • //CALLING CLASS MEMBER FUNCTIONS:
  • //classInstanceName.functionName(varNames);

  • //Calling Class Member Functions...
    1. varName = classInstanceName.functionName();

    2. //example...
    3. //ONLY functions in the public category can be called from other modules
    4. //MUST #include “headerFileName.h” to declare a Class Instance...

    5. #include “addClass.h”
    6. int main() {
    7.      int num1 = 1, num2 = 2, total = 0;   //Initialize some integers
    8.      addClass myClass;   //Call the Default Constructor
    9.      total = myClass.addNum(num1, num2);   //Call the member function
    10.      return 0;   //Return a value to exit the main module
    11. }

    12. //Accessing Class Data is similar to calling Class Member Functions...
    13. cout << myClass.num1;   //This only works if num1 is declared in “public!”
  • Read More...
  • //CLASS INHERITANCE:
  • //class className : inheritanceType otherClassName { public: prototype: private: };

  • //Class Inheritance...
    1. class className : inheritanceType otherClassName {
    2.      public:
    3.      protected:
    4.      private:
    5. };

    6. //example...
    7. //The inheritanceType affects how data is imported into the child class

    8. //Parent class “soldier” in soldierClass.h file...
    9. class soldier {
    10.      public:
    11.           soldier();
    12.           soldier(soldier&);
    13.           soldier(int, int, int);
    14.           ~soldier();
    15.           int getHitPoints();
    16.           int getAccuracy();
    17.           int getJogSpeed();
    18.           void setHitPoints(int);
    19.           void setAccuracy(int);
    20.           void setJobSpeed(int);
    21.      protected:
    22.           //Ammo values are save in weapon objects (class DMRClass)
    23.           int hitPoints;
    24.           int accuracy;
    25.           int jogSpeed;
    26.           //CrouchSpeed, & SprintSpeed are = for all classes
    27.      private:
    28. };

    29. //Child class “sniper” in sniperClass.h file...
    30. //Imports public & protected from soldier and saves to private in sniper

    31. #include “soldierClass.h”
    32. class sniper : private soldier {
    33.      public:
    34.           sniper();
    35.           sniper(sniper&);
    36.           sniper(int, int, int);
    37.           ~sniper();
    38.           string getAbility();
    39.           int getZeroBloomTime();
    40.           void setAbliity(string);
    41.           void setZeroBloomTime(int);
    42.      protected:
    43.      private:
    44.           string ability;   //Like invisiblity
    45.           int zeroBloomTime;   //Like holding your breath before a shot
    46. };

    47. /*
    48. The sniper class now has access to all the functions and variables in both the public & protected sections of the soldier class
    49. */
  • Read More...
  • //FRIEND FUNCTIONS TO A CLASS:
  • //friend returnDataType functionName(dataTypesOfParameters);

  • //Friend Functions to a Class...
    1. /*
    2. Friend functions are NOT class member functions
    3. But they can access protected & private data of the class
    4. */
    5. class className {
    6.      public:
    7.           friend returnDataType functionName();
    8.      protected:
    9.      private:
    10. };

    11. //example...
    12. //Friend Function Prototype (in the class declaration)
    13. class myClass {
    14.      public:
    15.           friend myClass Calculations(int);
    16.           myClass();
    17.      protected:
    18.      private:
    19.           int aNumber;
    20. };

    21. //Friend Function Definition
    22. //Notice that Friend Functions do NOT need className::functionName
    23. myClass Calculations(int anotherNumber) {
    24.      myClass tempClass;
    25.      //Calculations can ONLY access “aNumber” because it's a friend
    26.      tempClass.aNumber *= anotherNumber;
    27.      return tempClass;
    28. }

    29. //Calling a Friend Function
    30. int calc = 6;
    31. myClass aClass;
    32. //Notice that Friend Functions do NOT need className.functionName
    33. aClass = Calculations(calc);
  • Read More...
  • //OVERLOADING OPERATORS:
  • //returnType operatorName(const dataTypeReference varName) { }

  • //Example shapeRec Class Declaration...
    1. #ifndef shapeRecClass_H
    2. #define shapeRecClass_H

    3. #include <cstdlib>
    4. #include <iostream>
    5. #include <iomanip>
    6. using namespace std;

    7. class shapeRec {
    8.           //Overloaded Stream Operators...
    9.           friend ostream& operator<<(ostream&, const shapeRec&);
    10.           friend istream& operator>>(istream&, shapeRec&);

    11.           //Overloaded Arithmetic Operators...
    12.           friend shapeRec operator+(const shapeRec&, const shapeRec&);
    13.           friend shapeRec operator-(const shapeRec&, const shapeRec&);
    14.           friend shapeRec operator*(const shapeRec&, const shapeRec&);
    15.           friend shapeRec operator/(const shapeRec&, const shapeRec&);

    16.           //Overloaded Assignment Operator...

    17.           //Overloaded Compound-Assignment Operators...

    18.           //Overloaded Increment & Decrement Operators...
    19.           friend shapeRec operator++(shapeRec&);
    20.           friend shapeRec operator++(shapeRec&, int);
    21.           friend shapeRec operator--(shapeRec&);
    22.           friend shapeRec operator--(shapeRec&, int);

    23.           //Overloaded Relational Operators...
    24.           friend bool operator==(const shapeRec&, const shapeRec&);
    25.           friend bool operator!=(const shapeRec&, const shapeRec&);
    26.           friend bool operator<=(const shapeRec&, const shapeRec&);
    27.           friend bool operator<(const shapeRec&, const shapeRec&);
    28.           friend bool operator>=(const shapeRec&, const shapeRec&);
    29.           friend bool operator>(const shapeRec&, const shapeRec&);

    30.      public:
    31.           //Constructors...
    32.           shapeRec();
    33.           shapeRec(double, double);
    34.           shapeRec(shapeRec&);

    35.           //Destructor...
    36.           ~shapeRec();

    37.           //Accessors...
    38.           double getLength() const;
    39.           double getWidth() const;

    40.           //Mutators...
    41.           void setDimensions(double, double);

    42.           //Calculators...
    43.           double calcPerimeter() const;
    44.           double calcArea() const;

    45.      private:
    46.           //Private Data...
    47.           double length;
    48.           double width;
    49. };

    50. #endif

  • //Overloaded Stream Operators...
    1. //Overloaded Stream Insertion Operator...
    2. ostream& operator<<(ostream& varName, const className& varName) {
    3.      return varName;
    4. }

    5. //example...
    6. //Overloaded Stream Insertion Operator Prototype (in Class Declaration .h)
    7. friend ostream& operator<<(ostream&, const shapeRec&);

    8. //Overloaded Stream Insertion Operator Definition (in Class Definitions .cpp)
    9. ostream& operator<<(ostream& osObj, const shapeRec& myRec) {
    10.      osObj << fixed << setprecision(2);
    11.      osObj << “Length = ” << myRec.length << endl;
    12.      osObj << “Width = ” << myRec.width << endl;
    13.      osObj << “Perimeter = ” << myRec.calcPerimeter() << endl;
    14.      osObj << “Area = ” << myRec.calcArea() << endl;
    15.      return osObj;
    16. }

    17. //Overloaded Stream Insertion Operator Call (in Main Definition .cpp)
    18. int main() {
    19.      shapeRec aRec;
    20.      cout << aRec;
    21. }



    22. //Overloaded Stream Extraction Operator...
    23. istream& operator>>(istream& varName, shapeRec& varName) {
    24.      return varName;
    25. }

    26. //example...
    27. //Overloaded Stream Extraction Operator Prototype (in Class Declaration .h)
    28. friend istream& operator>>(istream&, shapeRec&);

    29. //Overloaded Stream Extraction Operator Definition (in Class Definitions .cpp)
    30. istream& operator>>(istream& isObj, shapeRec& myRec) {
    31.      double tempLength = 0.0;
    32.      double tempWidth = 0.0;
    33.      char temp = '\0';
    34.      cout << “Please enter length and width (1.0,1.0):\n”;
    35.      isObj >> tempLength >> temp >> tempWidth;
    36.      myRec.setDimensions(tempLength, tempWidth);
    37.      return isObj;
    38. }

    39. //Overloaded Stream Extraction Operator Call (in Main Definition .cpp)
    40. int main() {
    41.      shapeRec aRec;
    42.      cin >> aRec;
    43. }

  • //Overloaded Arithmetic Operators...
    1. //Overloaded Addition Operator...

    2. //example...
    3. //Overloaded Addition Operator Prototype (in Class Declaration .h)

    4. //Overloaded Addition Operator Definition (in Class Definitions .cpp)

    5. //Overloaded Addition Operator Call (in Main Definition .cpp)



    6. //Overloaded Subtraction Operator...

    7. //example...
    8. //Overloaded Subtraction Operator Prototype (in Class Declaration .h)

    9. //Overloaded Subtraction Operator Definition (in Class Definitions .cpp)

    10. //Overloaded Subtraction Operator Call (in Main Definition .cpp)



    11. //Overloaded Multiplication Operator...

    12. //example...
    13. //Overloaded Multiplication Operator Prototype (in Class Declaration .h)

    14. //Overloaded Multiplication Operator Definition (in Class Definitions .cpp)

    15. //Overloaded Multiplication Operator Call (in Main Definition .cpp)



    16. //Overloaded Division Operator...

    17. //example...
    18. //Overloaded Division Operator Prototype (in Class Declaration .h)

    19. //Overloaded Division Operator Definition (in Class Definitions .cpp)

    20. //Overloaded Division Operator Call (in Main Definition .cpp)



    21. //Overloaded Modulus Operator...

    22. //example...
    23. //Overloaded Modulus Operator Prototype (in Class Declaration .h)

    24. //Overloaded Modulus Operator Definition (in Class Definitions .cpp)

    25. //Overloaded Modulus Operator Call (in Main Definition .cpp)

  • //Overloaded Assignment Operator...
    1. //Overloaded Assignment Operator...

    2. //example...
    3. //Overloaded Assignment Operator Prototype (in Class Declaration .h)

    4. //Overloaded Assignment Operator Definition (in Class Definitions .cpp)

    5. //Overloaded Assignment Operator Call (in Main Definition .cpp)

  • //Overloaded Compound-Assignment Operators...
    1. //Overloaded Addition-Equals Assignment Operator...

    2. //example...
    3. //Overloaded Addition-Equals Assignment Operator Prototype (in Class Declaration .h)

    4. //Overloaded Addition-Equals Assignment Operator Definition (in Class Definitions .cpp)

    5. //Overloaded Addition-Equals Assignment Operator Call (in Main Definition .cpp)



    6. //Overloaded Subtraction-Equals Assignment Operator...

    7. //example...
    8. //Overloaded Subtraction-Equals Assignment Operator Prototype (in Class Declaration .h)

    9. //Overloaded Subtraction-Equals Assignment Operator Definition (in Class Definitions .cpp)

    10. //Overloaded Subtraction-Equals Assignment Operator Call (in Main Definition .cpp)



    11. //Overloaded Multiplication-Equals Assignment Operator...

    12. //example...
    13. //Overloaded Multiplication-Equals Assignment Operator Prototype (in Class Declaration .h)

    14. //Overloaded Multiplication-Equals Assignment Operator Definition (in Class Definitions .cpp)

    15. //Overloaded Multiplication-Equals Assignment Operator Call (in Main Definition .cpp)



    16. //Overloaded Division-Equals Assignment Operator...

    17. //example...
    18. //Overloaded Division-Equals Assignment Operator Prototype (in Class Declaration .h)

    19. //Overloaded Division-Equals Assignment Operator Definition (in Class Definitions .cpp)

    20. //Overloaded Division-Equals Assignment Operator Call (in Main Definition .cpp)



    21. //Overloaded Modulus-Equals Assignment Operator...

    22. //example...
    23. //Overloaded Modulus-Equals Assignment Operator Prototype (in Class Declaration .h)

    24. //Overloaded Modulus-Equals Assignment Operator Definition (in Class Definitions .cpp)

    25. //Overloaded Modulus-Equals Assignment Operator Call (in Main Definition .cpp)

  • //Overloaded Increment & Decrement Operators...
    1. //Overloaded Pre-Increment Operator...

    2. //example...
    3. //Overloaded Pre-Increment Operator Prototype (in Class Declaration .h)

    4. //Overloaded Pre-Increment Operator Definition (in Class Definitions .cpp)

    5. //Overloaded Pre-Increment Operator Call (in Main Definition .cpp)



    6. //Overloaded Post-Increment Operator...

    7. //example...
    8. //Overloaded Post-Increment Operator Prototype (in Class Declaration .h)

    9. //Overloaded Post-Increment Operator Definition (in Class Definitions .cpp)

    10. //Overloaded Post-Increment Operator Call (in Main Definition .cpp)



    11. //Overloaded Pre-Decrement Operator...

    12. //example...
    13. //Overloaded Pre-Decrement Operator Prototype (in Class Declaration .h)

    14. //Overloaded Pre-Decrement Operator Definition (in Class Definitions .cpp)

    15. //Overloaded Pre-Decrement Operator Call (in Main Definition .cpp)



    16. //Overloaded Post-Decrement Operator...

    17. //example...
    18. //Overloaded Post-Decrement Operator Prototype (in Class Declaration .h)

    19. //Overloaded Post-Decrement Operator Definition (in Class Definitions .cpp)

    20. //Overloaded Post-Decrement Operator Call (in Main Definition .cpp)

  • //Overloaded Relational Operators...
    1. //Overloaded Equality Operator...

    2. //example...
    3. //Overloaded Equality Operator Prototype (in Class Declaration .h)

    4. //Overloaded Equality Operator Definition (in Class Definitions .cpp)

    5. //Overloaded Equality Operator Call (in Main Definition .cpp)



    6. //Overloaded In-Equality Operator...

    7. //example...
    8. //Overloaded In-Equality Operator Prototype (in Class Declaration .h)

    9. //Overloaded In-Equality Operator Definition (in Class Definitions .cpp)

    10. //Overloaded In-Equality Operator Call (in Main Definition .cpp)



    11. //Overloaded Less-Than-or-Equal-To Operator...

    12. //example...
    13. //Overloaded Less-Than-or-Equal-To Operator Prototype (in Class .h)

    14. //Overloaded Less-Than-or-Equal-To Operator Definition (in Class .cpp)

    15. //Overloaded Less-Than-or-Equal-To Operator Call (in Main .cpp)



    16. //Overloaded Less-Than Operator...

    17. //example...
    18. //Overloaded Less-Than Operator Prototype (in Class Declaration .h)

    19. //Overloaded Less-Than Operator Definition (in Class Definitions .cpp)

    20. //Overloaded Less-Than Operator Call (in Main Definition .cpp)



    21. //Overloaded Greater-Than-or-Equal-To Operator...

    22. //example...
    23. //Overloaded Greater-Than-or-Equal-To Operator Prototype (in Class .h)

    24. //Overloaded Greater-Than-or-Equal-To Operator Definition (in Class .cpp)

    25. //Overloaded Greater-Than-or-Equal-To Operator Call (in Main .cpp)



    26. //Overloaded Greater-Than Operator...

    27. //example...
    28. //Overloaded Greater-Than Operator Prototype (in Class Declaration .h)

    29. //Overloaded Greater-Than Operator Definition (in Class Definitions .cpp)

    30. //Overloaded Greater-Than Operator Call (in Main Definition .cpp)
  • Read More...

  • //Coplien's Orthodox Canonical Form - Design:

    • //COCF CLASS PROTOTYPES:
    • //DEFAULT CONSTRUCTOR PROTOTYPE...
    • //className();

    • //COPY CONSTRUCTOR PROTOTYPE...
    • //className(classNameReference);

    • //WORKING CONSTRUCTOR PROTOTYPE...
    • //className(dataTypesOfParameters);

    • //DEFAULT DESTRUCTOR PROTOTYPE...
    • //~className();

    • //COCF Class Prototypes...
      1. class className {
      2.      public:
      3.           className();
      4.           className(className&);
      5.           className(dataType, dataType, ...);
      6.           ~className();
      7.      protected:
      8.      private:
      9.           dataType varName;
      10. };

      11. //example...
      12. class myClass {
      13.           //Anything above declared sections defaults to public

      14.      public:
      15.           //Code within public is available to all modules
      16.           //Generally speaking it's good to put your functions in public

      17.           //Default Constructor Prototype...
      18.           myClass();

      19.           //Copy Constructor Prototype...
      20.           myClass(myClass&);

      21.           //Working Constructor Prototype...
      22.           //There should be a parameter for every data variable in the class
      23.           myClass(int, int, int);

      24.           //Default Destructor Prototype...
      25.           ~myClass();

      26.           //There should be an Accessor and Mutator for every data variable
      27.           int getANum();   //Accessor
      28.           int getAotherNum();   //Accessor
      29.           void setANum(int);   //Mutator
      30.           void setAnotherNum(int);   //Mutator

      31.      protected:
      32.           //Code within protected is ONLY available to child classes
      33.           //Private data MUST be here to be accessed with inherited classes

      34.      private:
      35.           //Code within private is ONLY availabe to this class
      36.           //Generally speaking it's good to put your data in private
      37.           int aNum;
      38.           int anotherNum;
      39.           int *anArray;
      40. };
    • Read More...
    • //COCF CLASS DEFINITIONS:
    • //DEFAULT CONSTRUCTOR DEFINITION...
    • //className::className(){ }

    • //COPY CONSTRUCTOR DEFINITION...
    • //className::className(className classInstanceNameReference){ }

    • //WORKING CONSTRUCTOR DEFINITION...
    • //className::className(dataTypesOfParameters varNames){ }

    • //DEFAULT DESTRUCTOR DEFINITION...
    • //className::~className(){ }

    • //COCF Class Definitions...
      1. //Default Constructor Definition...
      2. //Constructors have no return type, but do NOT need the keyword void
      3. className::className() {
      4. }

      5. //example...
      6. myClass::myClass() {
      7.      aNum = 0;
      8.      anotherNum = 0;
      9.      //NEVER dynamically allocate memory in a header file (not inline)
      10.      anArray = new int[10];
      11. }


      12. //Copy Constructor Definition...
      13. //Constructors have no return type, but do NOT need the keyword void
      14. className::className(className classInstanceName&) {
      15. }

      16. //example...
      17. myClass::myClass(myClass anotherClass&) {
      18.      //Use the parameter passed to the Constructor to assign values...
      19.      aNum = anotherClass.aNum;
      20.      anotherNum = anotherClass.anotherNum;
      21.      anArray = anotherClass.anArray;
      22. }


      23. //Working Constructor Definition...
      24. //Constructors have no return type, but do NOT need the keyword void
      25. className::className(dataType varName, dataType varName, ...) {
      26. }

      27. //example...
      28. myClass::myClass(int temp1, int temp2, int temp3) {
      29.      //Use the parameters passed to the Constructor to assign values...
      30.      aNum = temp1;
      31.      anotherNum = temp2;
      32.      //NEVER dynamically allocate memory in a header file (not inline)
      33.      anArray = new int[temp3];
      34. }


      35. //Default Destructor Definition...
      36. //Destructors have no return type, but do NOT need the keyword void
      37. inline className::~className() {
      38.      delete varName;
      39. }

      40. //example...
      41. //It's ok to define Destructors in header files (inline)
      42. inline myClass::~myClass() {
      43.      //ALWAYS delete variables with dynamically allocated memory!
      44.      delete anArray;
      45. }

    • Read More...
    • //CALLING COCF CLASSES:
    • //CALLING A DEFAULT CONSTRUCTOR...
    • //className classInstanceName;

    • //CALLING A COPY CONSTRUCTOR...
    • //className classInstanceName(classInstanceName);

    • //CALLING A WORKING CONSTRUCTOR...
    • //className classInstanceName(varNames);

    • //CALLING A DEFAULT DESTRUCTOR...
    • //Destructors are automatically called by the system

    • //Calling COCF Classes...
      1. //Calling a Default Constructor...
      2. className classInstanceName;

      3. //example...
      4. //ONLY functions in the public category can be called from other modules
      5. //MUST #include “headerFileName.h” to declare a Class Instance...

      6. #include “myClass.h”
      7. int main() {
      8.      myClass aClass;   //Call the Default Constructor
      9.      return 0;   //Return a value to exit the main module
      10. }


      11. //Calling a Copy Constructor...
      12. className classInstanceName(classInstanceName);

      13. //example...
      14. //ONLY functions in the public category can be called from other modules
      15. //MUST #include “headerFileName.h” to declare a Class Instance...

      16. #include “myClass.h”
      17. int main() {
      18.      myClass aClass;   //Call the Default Constructor
      19.      myClass anotherClass(aClass);   //Call a Copy Constructor
      20.      return 0;   //Return a value to exit the main module
      21. }


      22. //Calling a Working Constructor...
      23. className classInstanceName(varNames);

      24. //example...
      25. //ONLY functions in the public category can be called from other modules
      26. //MUST #include “headerFileName.h” to declare a Class Instance...

      27. #include “myClass.h”
      28. int main() {
      29.      int num1 = 5, num2 = 15, num3 = 10;   //Initialize some integers
      30.      myClass aClass(num1, num2, num3);   //Call a Working Constructor
      31.      return 0;   //Return a value to exit the main module
      32. }


      33. //Calling a Default Destructor...
      34. //Destructors are automatically called by the system
    • Read More...
Last Updated: Sunday September 30, 2012 - 20:03:04.