An Introduction to C++

by Kristoffe Brodeur.

All of this code works on DEV C++ (4.9.9.2) for Windows Xp, Vista, and 7. It also compiles and runs on Visual Studio (C++) 2005-2010 without error.


arrays


#include <iostream>
#include <string>

using namespace std;

int main()
{
//uncomment to see cardDeck[0]'s memory position move for array roomsInSchool some space
     string roomsInSchool[128]={"main room","basement","hallway A"};
     string cardDeck[52]={"hearts-ace","hearts-king","hearts"};
cout << "[0]=" << cardDeck[0] << endl;
cout << "[1]=" << cardDeck[1] << endl;
cout << "[2]=" << cardDeck[2] << endl;
     
     //flipping two values using a third extranneous location to hold one of the values, like scatch paper would
     string tempCard;
tempCard=cardDeck[0];//copy this value like ctrl+c (copy) does in word INTO tempCard
cardDeck[0]=cardDeck[1];//now copy cardDeck[1]'s value INTO [0]
cardDeck[1]=tempCard;//a->c b<-a c<-b, safely making a flip possible without forgetting the values using the third var
cout << "-----after flipping 0 and 1-----\n";
cout << "[0]=" << cardDeck[0] << endl;
cout << "[1]=" << cardDeck[1] << endl;
     //
     //--loop through showing card values
     int cardsDefined=3;
     //
     for(int i=0;i<cardsDefined;i++)
      {
          cout << "card[" << i << "] is the " << cardDeck[i] << "\n";
          }
     cout << "The amount of bytes to point to cardDeck array item[0] and all items is: " << sizeof(cardDeck[0]) << endl;
     cout << "since there are 52 cards defined possible in the array, 52 x 4 is: " <<sizeof(cardDeck) << endl;
     //
     cout << "pointer example-----\n";
     cout << "The cardDeck[0] item has the value " << cardDeck[0] << endl;
     //cardDeck is a Array of ... strings, so the pointer has to know it is pointing to a ... string
     string *pointerTest;
     //now fill in the position in memory that cardDeck[0] is at (&)
     pointerTest=&cardDeck[0];
     cout << "The memory location for it is " << pointerTest << endl;
     //
     cout << "\n\n-----memory locations\n";
     //
     int cardAmt=sizeof(cardDeck)/sizeof(cardDeck[0]);
     cout << "I count a total of " << cardAmt << " cards.\n";
     //-----
     string *mempos;
     //
     for(int c=0;c<cardAmt;c++)
      {
          mempos=&cardDeck[c];                     
          cout << "card[" << c << "] title: "<< cardDeck[c]<<" memory position:" << mempos << endl;
          }
     system("PAUSE");
return EXIT_SUCCESS;
}

cin_cout


#include <cstdlib>
#include <iostream>
#include <string.h>

using namespace std;

int main(int argc, char *argv[])
     {
     /*---------------------------------------------------
     integers
     */
     int guess=12345;
     int guess2=67890;
     int guess3=10293;
     
     cout << "Integer memory locations\n----------\n";
     //pointers defined by type*, here int*, same type as the variable they point to
     int* pntEx=&guess;
     int* pntEx2=&guess2;
     int* pntEx3=&guess3;
     
     cout << pntEx << " | " << guess << endl;
     cout << pntEx2 << " | " << guess2 << endl;
     cout << pntEx3 << " | " << guess3 << endl;
     
     /*---------------------------------------------------
     strings
     */
     string message="Hi there";
     string message2="How are you feeling";
     
     cout << "\n\nString memory locations\n----------\n";
     //pointers defined by type*, here string*, same type as the variable they point to
     string* strPntEx=&message;
     string* strPntEx2=&message2;
     
     cout << strPntEx << " | " << message << endl;
     cout << strPntEx2 << " | " << message2 << endl;
     
     /*---------------------------------------------------
     char arrays
     
          chars are denoted with a single character
          enclosed with single quotes (') not double quotes (")

          char arrays use double quotes(")
     */
     char* nameFirst="Kristoffe";
     char* nameLast="Brodeur";
     
     cout << "\n\nChar memory locations\n----------\n";
     cout << &nameFirst << " | " << nameFirst << endl;
     cout << &nameLast << " | " << nameLast << endl;

     string pauseDummy;
     cout << "Pausing the program with a phony input (cin)\n"
          << "check with a program the above memory locations\n"
          << "input:";
     cin >> pauseDummy;
     
     cout << "\n\n";
          
     system("PAUSE");
     return EXIT_SUCCESS;
     }

data_types


#include <iostream>
#include <string>

using namespace std;
//-----
class CalculateAnswer
{
public:
CalculateAnswer(){};
~CalculateAnswer(){};
float findScore(float sentCorrect, float sentTotal);
private:
float theScore;
     };
CalculateAnswer::CalculateAnswer()
{
}
CalculateAnswer::~CalculateAnswer()
{
}     
//-----
float scoreTotal(float sentCorrect, float sentTotal)
{
float scoreVal=sentCorrect/sentTotal;
return scoreVal;
     }
//-----
int main(int argc, char *argv[])
{
int age=35;
cout << "My age is " << age << endl;
float score;
float correct=7;
float total=11;
score=correct/total;
cout << "A floating point of your current score is " << correct << "\\" << total << "=" << score << endl;
string worker="kim";
cout << "Is your name " << worker << "?" << endl;
cout << "Another way to find the score is to put it in a function. Score is " << scoreTotal(correct,total) << endl;

system("PAUSE");
return EXIT_SUCCESS;
}

friends


#include <iostream>

using namespace std;

class Person
{
public:
     /*
     default costructor
     same name as the class (runs as soon as the class instance is made)
     ie Person kim; tells the computer, make a new object 'kim' from the class 'Person' and define
     it with the command programming in Person::Person() which means 'this happens when Person is built
     */
     Person();
     /*
     parameter constructor
     allows you to send variable definitions WHEN you begin the class Person, no need to 'identifyFriend' for instance
     */
Person(string bestFriendName);
     
     void identifyFriend(string sentName)
     {
     bestFriend=sentName;                
     }
     void showInfo (void)
     {
     cout << "My Best Friend is " << bestFriend << endl;
     }

           
private:
string bestFriend;

};
/*
the constructos CAN be defined IN the public: area by putting the code { } in thee too
by seperating it, maybe there are 40 Person functions, and each function might have 30 lines of code. 1200 lines?
its easier to have 40 in the Person Class definition area, and externally write the functions outside as PERSON::*functionName
*/
//default constructor
Person::Person()
{
bestFriend="not defined yet, find me a best friend!";
cout << "Person created!\n";                      
}
//paramterized constructor
Person::Person(string sentName)
{
bestFriend=sentName;
}

int main()
{

Person kim;
kim.identifyFriend("rusty");
kim.showInfo();

Person kristoffe;
kristoffe.identifyFriend("Garfield");
kristoffe.showInfo();

Person obama("Johnny");
obama.showInfo();

system("PAUSE");
return EXIT_SUCCESS;
}

inheritance


#include <cstdlib>
#include <iostream>

/*
understanding class and inheritance. by Kristoffe Brodeur. ©2010 All Rights Reserved.
06-10-2010
*/
using namespace std;

class Employee
{
     public:
      //default constructor
          Employee();
          
          /*
          parameterized constructor
          a char is an array of characters, one to however many...
          [] means array sentName has ??? I don't know how many characters, just fill it in when it comes here
          */
          Employee(char sentName[]);
          
          //methods (functions etc...)
          // whatAmI myName (whatAreYouSendingMe)
          void showInfo(void);
          
          //variables
          /*
          a string is a basically limitless expandable character array, so it grows with your input to it
          c++ does this invisibly for us
          char string[]={'a','b','r','a','h','a','m',' ','l','i','n','c','o','l','n','\0'};
          '\0' meaning NULL end of string (invisible to us)
          */
          string eName;           
          
};

void Employee::showInfo(void)
{
cout << "EMPLOYEE CLASS CALLS (showInfo)\n"
      << "Name:" << eName << endl;
}

Employee::Employee()
{
cout << "\nDefault constructor called\n";
     }
     
Employee::Employee(char sentName[])
     {
cout << "\nParameterized construcor called\n";
     cout << "variable char array sentName is:" << sentName << endl;
     /*
     copy a character array (sentName) into a string(eName)? no problem
     c++ understands and copies it all over in a loop 'under the hood' i.e. 'behind closed doors'
     */
     eName=sentName;
     cout << "and to test to see if the copy worked... " << eName << endl;
     }
                         
/*
---------------------------------------------------------------------
derived class Manager : Employee
---------------------------------------------------------------------
*/

/*
public here means, I want to be an Employee AND have my own functions, variables
I ALSO want to access the PUBLIC things in EMPLOYEE if I want to.
*/
class Manager:public Employee
{
     private:
//variables, methods(only the class can see, even an instance in main can't call it and see it, cout, etc
          string privateKeyCode;
          
     public:
      //default constructor
Manager();

//parameterized constructor
/*
In a big company like The Gap, Radio Shack, Target...
a MANAGER can have a keyCode to a safe that holds the store money that an EMPLOYEE shouldn't
so, when we make a MANAGER, let's ADD 'keyCode' as well as 'sentName'

notice also that you ONLY need to send the vars in Employee to the call Employee(****) not keyCode, etc
the original class only needed one variable, the new one Manager has keyCode and uses it only for iself.
share only what Employee needs to instantiate its 'like' or 'similar' constructor you're calling
*/
          Manager(char sentName[],char keyCode[]):Employee(sentName)
{
               cout << "DERIVED parameterized constructor called\n";
               cout << "As a manager I have a keyCode only I can see.";
               privateKeyCode=keyCode;
               }
               
          string policeAccessToCode(string password)
           {
               string retStr="";
               //
               if(password=="donkeykong")
                {
      retStr=privateKeyCode;
                     }     
               else
                {
                     retStr="\naccess denied. invalid password.\n";      
                     }
               return retStr;     
               }
          
                    
};

Manager::Manager()
{
cout << "\nDerived class called\n";
     }


int main(int argc, char *argv[])
{
cout << "-----Testing Employee class\n";
Employee e1;
/*
Double quotes do not send character strings, single quotes do.
BUT! If you are sending an array of characters to a variable type 'char' like 'char sentName[]'
it is stating, I need a string of characters, so go BACK to double quotes to send inline "mary" :)
*/
Employee e2("mary");
e2.showInfo();

cout << "-----Testing Manager class\n";
Manager m1;
Manager m2("william","202345");
m2.showInfo();
/*
this won't work. luckily, a private variable, method, function, is totally hidden once defined :)
but...if you wrote a function INSIDE of 'Manager' that was public which returned the 'privateKeyCode' you could see it.
*/

//cout << m2.privateKeyCode << endl;
cout << "\n**Accessing keyCode**\n"<< m2.policeAccessToCode("popeye123");
cout << "\n**Accessing keyCode**\n"<< m2.policeAccessToCode("donkeykong");
system("PAUSE");
return EXIT_SUCCESS;
}

looping


#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
      const int correct=8;//switch needs a const type int, not just 'int correct=8'
      int guess;
      int tries=0;
      //
      for(;;)
      {
           tries++;
           cout << "\nI am thinking of a number from (1-10).\n";
           cout << "Guess=";
           cin >> guess;
           //
           switch(guess)
           {
                 case(correct):
                          cout << "\n*****CORRECT*****";          
                break;
default:
           cout << "nope.\n";
           break;
                }
      //
      if(correct==guess)
      {
cout << "\nIt took you " << tries << " attempts to guess the number.\n" << "\nEnd of Program\n";
                break;
                }
           }
system("PAUSE");
return EXIT_SUCCESS;
}

overload_ops


#include <cstdlib>
#include <iostream>

using namespace std;

class greenhouse
{
     public:
          greenhouse();
          greenhouse(int sentWatts);
          greenhouse(char sentName[]);
          ~greenhouse();     

     //functions
     void setWatts(int sentWatts);
     void showWatts(void);
     void setName(char Name[]);

          //overload the addition operator (binary operation using 2 objects)
          greenhouse greenhouse::operator +(greenhouse sentObj);
          
     protected:
          int _watts;
          char *_roomName;
          
     };
     
void greenhouse::setName(char sentName[])
     {
     cout << "*****setName(" << sentName << ")\n";     
     int length=strlen(sentName);
     _roomName=new char[length];
     strncpy(_roomName,sentName,length);//[0]w [1]o [2]r [3]d
     //[w][o][r][d]['\0'] position is length=4 (really th 5th position)
     //added the NULL at the end of the string (char array) so it wont crash
     _roomName[length]='\0';
     }
     
void greenhouse::showWatts(void)
     {
     cout << "\n[" << _roomName << "] watts usage:" << _watts << "\n";
     }     
     
void greenhouse::setWatts(int sentWatts)
     {
     cout <<"*****setting watts:" << sentWatts << "\n";
     _watts=sentWatts;
     }                     

//addition implementation (sentObj will be 'jungleRoom' but internally, it is known as 'sentObj'
greenhouse greenhouse::operator +(greenhouse sentObj)
     {
     cout << "\n++++++++++\n" << "overloaded(+) and new object created\n";
     //create a new greenhouse object C=A+B, B being sentObj on the right side of the operator
     greenhouse newObj;//no parenthesis() means 'call the default constructor'
     
     //set the combined watts for both rooms into the new room (larger surrounding room as example only)
     
     //_watts by itself is referring to the object (A) which is calling (+), A+ means all methods alone refer to A
     //so, _watts really means 'desertRoom._watts' in this example
     newObj._watts=_watts + sentObj._watts;
     //
     return newObj;
     }

//default constructor
greenhouse::greenhouse()
{
     cout << "default constructor called\n";
     _roomName=new char[50];
     }
     
greenhouse::greenhouse(int sentWatts)
     {
     _watts=sentWatts;
     cout     << "watts usage of room:" << _watts << "\n";
     _roomName=new char[50];
     _roomName="unknown";
     }
     
greenhouse::greenhouse(char sentName[])
     {
     cout << "room name:" << sentName << "\n";
     int length=strlen(sentName);
     _roomName=new char[length];
     setName(sentName);
     
     cout     << "watts usage of room:" << _watts << "\n";
     //uh oh, the _watts isnt defined yet, so we should do it or garbage will occur
     
     _watts=0;
     }     
     
greenhouse::~greenhouse()
{
     cout << "Destructor called.\n";
     delete _roomName;
     }     

int main(int argc, char *argv[])
     {
     int a=5;
     int b=7;
     int c=a+b;
     cout << "a(" << a << ") + b(" << b << ") = c(" << c << ")\n";

     //
     greenhouse desertRoom(55);
     desertRoom.setName("Desert Room");
     desertRoom.showWatts();
     
     greenhouse jungleRoom("Nigerian Jungle");
     jungleRoom.setWatts(100);
     jungleRoom.showWatts();


     greenhouse flowerRoom("Flowers of the World");
     flowerRoom.setWatts(37);
     
     //create a new greenhouse object C=A+B
     
     //C=entireBldg
     //A=desertRoom
     //B=jungleRoom
     
     greenhouse entireBldg=desertRoom + jungleRoom;
     entireBldg.setName("Main Building");
     entireBldg.showWatts();

     cout << "\n*****sequence of additions test\n\n";
     
     greenhouse newAdditions=desertRoom + jungleRoom + flowerRoom;
     newAdditions.setName("Additions");
     newAdditions.showWatts();

     system("PAUSE");
     return EXIT_SUCCESS;
     }

pointers


#include <iostream>
#include <string>

using namespace std;

int main()
{
int numberArr[4]={1,3,7,11};
//
cout << "the array numberArr element(or item #) 3 is " <<numberArr[3] << endl;
//
//int a=0;
for(int a=0;a < 4;a++)
{
cout << "element["<< a <<"] value:" << numberArr[a] << "\n";
     }
//normal variable assignment, copying a value from an array element to a simple int variable
int notPointerEle=numberArr[0];
cout << "notPointerEle=" << notPointerEle << endl;
//pointing to a position that holds an element in an array AND the value can be seen too!
//* means pointer
//& means ref the location of     
int x=2;
int *pointerEle=&numberArr[x];
cout << "the memory location of numberArr[" << x <<"] holds this value:" << *pointerEle << endl;
/*
[900][901][902][903]
[1][3][7][11]
*pointerEle=&numberArr[x]=memory position [902] AND its contents
*/
cout << "the next memory location, where numberArr x+1 (2+1) is:" << *(pointerEle+1) << endl;
cout << "if you made a mistake with the syntax\n this would happen (*pointerEle=7; 7+1=8):" << *pointerEle+1 << endl;     
//



     
system("PAUSE");
return EXIT_SUCCESS;
}

switches


#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
//31 28 31 30 31 30 31 31 30 31 30 31
//jan[1] feb[2] mar[3] apr[4] may[5] jun[6] jul[7] aug[8] sep[9] oct[10] nov[11] dec[12]
cout << "A test of a switch.\n";
//replace with a number 1-12 to see if you follow the process
int theMonth=9;
int maxDays = 31;
     switch (theMonth)
      {
          //-----
          case 2:
           maxDays = 28;
           break;
          //-----
          //cases following each other left open with only : until the next case follow the last rules with break; after it
          case 4:
          case 6:
          case 9:
          case 11:
               maxDays = 30;
           break;
          //-----
          case 1:
          case 3:
          case 5:
          case 7:
          case 8:
          case 10:
          case 12:
               maxDays = 31;
               break;
      }
cout << "days in month:" << theMonth << "\n";
cout << "total days:" << maxDays << "\n";
system("PAUSE");
return EXIT_SUCCESS;
}

var_types


#include <cstdlib>
#include <iostream>

using namespace std;

int main()
     {
     int year=2010;
     cout << "This was written in " << year << endl;
     
     //-------------------------------------------------------------------------
     cout << "\n*****COUT AND IN, AND CLEARING THE BUFFER\n";
     char firstInitial;
     cout << "What is your first name's initial letter:";
     cin >> firstInitial;
     //after cin input, call cin again and clear the input buffer if its more than one character
     cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
     
     cout << "\n"; // "\n" = endl (newline,endline,etc...)
     
     //single quotes as ouput, double quotes cut strings and code inserts char 'firstInitial'
     cout << "Your first initial is '" << firstInitial << "'\n";
     
     //-------------------------------------------------------------------------
     cout << "\n*****CHAR ARRAYS STORING INPUT\n";
     //now make a char array with 9 places reserved in memory [0][1][2][3][4][5][6][7][8]
     char theQuickBrownA[9];
     //create a buffer for 9 characters to input
     char tempChars[9];
     //identify that length in a variable named 'cLength'
     int cLength=9;
          
     cout << "9 character limit test. Type in 'The Quick Brown Fox Jumped Over the Lazy Dog.\n";
     cin >> tempChars;
     //anything typed past 9 characters will be in 'tempChars' past the original 9th position
     // simple 'cin' stops input after a space ' ' and you will only see 'The'
     
     //use a counted length string copy
     //strncpy(destination,source,length of characters to copy from position 0)
     strncpy(theQuickBrownA,tempChars,cLength);
     //now, in C++, it likes to have a NULL character which is expressed as '\0' ending the string of chars
     //if you comment this line below out, you will see random garbage output to the screen
     theQuickBrownA[cLength]='\0';
     
     //again clear the input buffer past 9 characters
     //so the next cin won't already have input going into it
     cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n' );
     cout << "What C++ remembers:" << theQuickBrownA << endl;     
     
     //-------------------------------------------------------------------------
     cout << "\n*****LIMITING THE CIN CHARS TO SEND\n";
     //a newline one right after another, \n\n, created two carriage returns
     cout << "An easier way of limiting user input is by the 'getline' function.\n\n";
     cout << "Please enter (16 characters)\n" << "0123456789abcdef:";
     //the first 10 characters are 0123456789, its NULL at the end makes 11
     //[0][1][2][3][4][5][6][7][8][9]['/0']
     int limEx=10;
     char numEx[limEx];
     /*
     the get function in cin allows
     (array to store input,limit to send to that array-1)
     get puts a NULL at the end of the process when it stores the input '\0'
     so if you want 10 characters from cin.get and the NULL if produces at the end
     that would be limEx+1
     */
     cin.get(numEx,limEx+1);
     //again, clear all excess garbage
     cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n' );
     
     cout << "\nThis is what C++ remembers of numEx:" << numEx << endl;
     //-------------------------------------------------------------------------
     cout << "\n*****STRINGS ARE CHAR ARRAYS\n";
     //a string in C++ is an char array[] automatically managed by the string class
     string partyTitle="John Doe's 50th Birthday Party";
     cout << "Our hotel is booked for " << partyTitle << "\n";
     
     system("PAUSE");
     return EXIT_SUCCESS;
     }

copy_constructor


#include <iostream>
using namespace std;
//-----
class Person
{
private:
int age;
public:
Person(){}

~Person(){}

Person(int _age)
{
age=_age;
}

Person(Person& tmp)
{
age=tmp.age;
cout << "copy constructor" << endl;
}

void Info()
{
cout << "My age is " << age << endl;
}
};
//-----
int main()
{
Person Kris(36);
Person Genny(Kris);
Genny.Info();
system("PAUSE");
return EXIT_SUCCESS;
}