Introduction to C++: Lesson 4
Objects & Classes and Arrays & Strings, Pointers, Const, Reference, Bit Operators
| Overview: | |
|
|
|
| Arrays |
What is an array?
An Array is the ability of grouping a number of data items of the same type in sequentially ordered in memory.
How to declare an array?
Here is an example of array declaration:
int myArray[4];
In the example above, we have the array type is int. The name of the array, which is myArray, comes right after the two open and close brackets with a number in between. The number in between those brackets is the array size. In other words, we have myArray type of int with the size of 4.
Basically, to declare an array, you will need to tell the compiler what type of the array will be, the name of the array, and the size of it. You will need the open bracket and close bracket for the array size.
Array Elements
The array elements is the number of data items inside the array.
In our example,
int myArray[4];
will have four elements as follow:
Array Elements and Memory Table for myArray[4]
|
Elements: |
myArray[0] |
myArray[1] |
myArray[2] |
myArray[3] |
|
Memory: |
value |
value |
value |
value |
In the table above, we have four array elements starting from 0 to 3. The first element is 0. The second element is 1. The third element is 2, and the four element is 3. The array elements start counting from o to the array size. For each element, we can assign or initialize a value to it. In our case, we can assign integers to it.
For example:
|
int myArray[4]; myArray[0] = 10; myArray[1] = 20; myArray[2] = 30; myArray[3] = 40; |
|
Elements: |
myArray[0] |
myArray[1] |
myArray[2] |
myArray[3] |
|
Memory: |
10 |
20 |
30 |
40 |
To access an array element, you would use the name of the array followed by open bracket, position of the array element, and close bracket. Example: myArray[0];
Another way short way to initialize the array is declaring them on the fly.
Example:
int myArray[4] = {10, 20, 30, 40}; //short way
Or if your fingers can't type anymore, you can let the compiler specify the array for you.
Example:
int myArray[] = {10, 20, 30, 40}; //the compiler will create an array large enough to store these data
To list all of the array elements, you would use a for loop to do so.
Example:
for (int i = 0; i<4; i++) {
cout << myArray[i] << endl;
}
This will list all of the array elements like:
10
20
30
40
Make sure the i<4; in the for loop is the right number for the array size.
So, this is our first array example:
|
#include <iostream> using namespace std; int main() { // ******** Example code goes below here ******** int myArray[4]; myArray[0] = 10; myArray[1] = 20; myArray[2] = 30; myArray[3] = 40; for (int i = 0; i<4; i++) { cout << myArray[i] << endl; } // ******** Example code goes above here ******** return (0); } |
Now, let's look at another example:
|
/****************************************************** * * GENERAL-PURPOSE EXAMPLE PROGRAM - ARRAYEXAM * ******************************************************/ #include <iostream> #include <iomanip> //for setprecision using namespace std; int main() { // ******** Example code goes below here ******** //a const here is to make sure totalExams is readonly. const int totalExams(3); //initialize ArraySize as double with a value of 3; double myGrade[totalExams]; //declaring myGrade as an array of 3 with double type cout << "Please enter your first three exams: " << endl; //this for loop will ask the user to enter three score for each of the three tests for (int i = 0; i < totalExams; i++) { cin >> myGrade[i]; } double testGrade(0); //make it 0 as default //this for loop with add the total of all tests and assign to the test grade for (int j = 0; j < totalExams; j++) { testGrade += myGrade[j]; //adding myGrade to testgrade } double testAverage = testGrade / totalExams; //averaging the test grade by dividing it with 3 cout << "Your test average is : " << fixed << setprecision(2) //setprecision(2) limits the display for << testAverage << endl; //testAverage to two decimal places // ******** Example code goes above here ******** return 0; } |
In our ARRAYEXAM example, we declare our array as a double type array with the name of myGrade and the size is totalExams. The totalexam variable is const because clearly const is for constant which means for read-only access. Then, we ask for the user input to enter their test score on the last 3 exams. We then use the for loop again to add the scores for the exams and assign it to the testGrade. Next, we declare another double variable testAverage to compute the average of the three exams.
So far, we have looked at one dimensional array. In later lessons, we will use vector in replacing most of our arrays. For now, let's take a look at two dimensional array.
Multi-Dimensional Arrays
Multi-Dimensional Arrays can have two or more subscripts or dimensions. The way you can declare the multi-Dimensional array is by adding another size of the array after the first size.
Example:
int myArray[3][3];
Here, we have declared an array with 4 columns and 4 rows.
Think this like a tic tac toe board game.
Now, if you want to initialize the value for one of the squares in the tic tac toe board game, then you would do the following:
|
myArray[0][0] = 4; myArray[1][1] = 5; myArray[2][2] = 6; |
Tic Tac Toe Board (Gray is the actual board shown in the game)
| Numbers: | 0 | 1 | 2 |
| 0 | 4 | ||
| 1 | 5 | ||
| 2 | 6 |
Theoretically, you will have a function that take the X of [0][0] to store the value 4 in the array element of [0][0]. In the game, you will display the letter X instead of number 4. You will use the number that store in that array element to compute how will win first if a player reaches three letter X for diagonal or horizontal or vertical. In our example, if the player A puts the letter x in row and column of [0][0], [1][1], [2][2], you will then have the Player A as a winner for this game. How so? You can have a function that add all of the numbers 4,5,6 which equals to 15. Huh? Well, you can assign the numbers from 1 to 9 for each of the array elements in the game board and have a function to check and add the total score of 15 for all directions. Here's an example of the game board you can assign the numbers with:
Tic Tac Toe Board (Gray is the actual board shown in the game)
| Numbers: | 0 | 1 | 2 |
| 0 | 4 | 9 | 2 |
| 1 | 3 | 5 | 7 |
| 2 | 8 | 1 | 6 |
By looking at the table above, you will initialize all of the numbers above in the multi-dimensional array. If you add the three numbers in vertical or horizontal or diagonal, the results will be 15. So, have a function to the do the calculation for that. Whichever player put the X or O in one of the slots in the table, you will then assign that number appropriately to that user and show the X or O in the table instead of number. How do the players play the game? well, you can ask them to give the coordinate of the board or use the direction like:
Tic Tac Toe Board (Gray is the actual board shown in the game)
| Numbers: | 0 | 1 | 2 |
| 0 | N.W | North | N.E |
| 1 | West | Center | East |
| 2 | S.W. | South | S.E |
Example of a player prompt:
Please enter your move position ( (c)Center, (nw)North West, (n)north, (ne)North East etc...) :
If this is one player game, you will need to make a computer AI for it. For now, just have the random number function ( rand () )to generate the random position after the player has moved. Make sure to check for position collision of random number computer generated vs the player specified move position.
That's the idea of the text based tic tac toe game. When you get to the data structure course, you will learn a much better way to handle this game!
Moreover, another short way for you to create multi-dimensional array is as follow:
Example:
in myArray[2][2] = {10, 20, 30, 40};
OR
int myArray[2][2] = { {10,20}, {30, 40} };
Minesweeper Concept Text Based Game:
If you don't know what minesweeper game is, you can try to play it by going to Start, Programs, Games, and click on Minesweeper. As you play, pay attention on the concept of the game and the algorithm behind it.
Here is the screenshot of the game:

The game is played on the 9 by 9 board, so you will need to load the board with 9 rows and 9 columns. Only ten of the 81 squares have mines and those mines are all well hidden to users. What you will need to do is to load the board with the 10 random generated mines (use the number 9 for mines) and store those mines in the random squares. You will also need to load the checking mines number algorithm. What it means is that you will need to check the number of mines in the surround squares. For example, the above picture in column 1 row 7 there is a number 2 in green. It means that there are two mines surrounding that number. Since this is not graphical game, you will need to ask the user for move position similar to the tic tac toe game above. Again, in later lessons, when we get to STL and data structures, you will know a much better way to handle this game.
What else do you need to know before you can start to work on these two text based game projects?
well, you will need to finish and grasp the basic concept of this four lessons. For now, keep that game concept in mind and refer to it when you're ready to rock.
A quick mention of declaration of 3D and 4D array:
For example:
|
int array3d[2][2][2] = { { {1,2}, {3,4} }, { {5,6}, {7,8} } }; int array3d[2][2][2][2] = { { { {1,2}, {3,4} }, { {5,6}, {7,8} } } }, { { {9,10}, {11,12} }, { {13,14}, {15,16} } } }; |
In C++, there are two famous kinds of strings. There are c-string and string.
C-string are a set of the array type char versus string doesn't need array type of char.
C-string examples:
|
/****************************************************** * * GENERAL-PURPOSE EXAMPLE PROGRAM * ******************************************************/ #include <iostream> using namespace std; const int LEN = 100; int main() { // ******** Example code goes below here ******** char words[LEN]; cout << "Please enter three words: "; cin.get(words, LEN, '.'); cout << words << endl; // ******** Example code goes above here ******** return 0; } |
The above example will ask the user to enter some words with the length of 100 and enter the period to end the program.
To use cstring, you will need to include the cstring header file.
Here is an example:
|
/******************************************************* * * GENERAL-PURPOSE EXAMPLE PROGRAM * ******************************************************/ #include <iostream> #include <cstring> using namespace std; const int LEN = 100; int main() { // ******** Example code goes below here ******** char words[LEN]; cout << "Please enter three words: "; cin.get(words, LEN, '.'); cout << words << endl; char cpy_words[LEN]; strcpy(cpy_words,words); cout << cpy_words << endl; // ******** Example code goes above here ******** return 0; } |
In the example above, we added the cstring header file so that we can use the function strcpy, which is string copy, to copy from one string to another string. The strcpy(cpy_words,words); tells that we're copying words to cpy_words.
There are many more functions you can use in cstring. Feel free to check out the MSDN online.
Moreover, you can use String to manipulate the text data.
You can declare a string like this:
string stringName; //declaring stringName as string
string stringName ("My message goes here"); //declaring stringName with the default text data My message goes here
In the stringName, you can access each individual characters by using the index of array. Like stringName[0] you're accessing the character M at the position 0, stringName[1] you're accessing the character y at the position 1
So, what is the character at position 16, stringName[16]? It's the character h.
Besides accessing the individual character in a string, there are many ways you can do to strings.
Creating strings:
|
string s; //declares an instance of a string named s string sOne; //declares an instance of a string named sOne string sOne("text goes here"); //initialize sOne string //with the value 'text goes here' string sTwo(sOne); //copying sOne to sTwo |
Operations on strings:
|
//returns the length of string sOne sOne.size(); sOne.length(); sOne[n]; //access the nth char in sOne sOne = sOne + "boy"; //concatenates 'boy' to the end of sOne string u = sOne + sTwo; //append sOne in front of sTwo and store in u. s.empty(); //returns true if empty string, false otherwise s.find("bo") //returns index of the first occurrence of "bo" in s starting from s[0]; //returns constant string::npos if not found //returns index of the first occurrence of character ch starting from s[0]. s.find(ch); s.find('a',1); //returns index of 'a', starting from s[1]. s.rfind(ch,pos); //returns index of the last occurrence of the specified string or //character, searching backwards from pos. //Search for the first occurrence of a character that appears //or does not appear in the ch. If found, return the position //of the character that satisfies the search condition; otherwise, //return string::npos. s.find_first_of(ch,pos); s.find_first_not_of(ch,pos); //Search for the lastoccurrence of a character that appears or //does not appear in the ch. If found, return the position of //the character that satisfies the search condition; otherwise, //return string::npos. s.find_last_of(ch,pos); s.find_last_not_of(ch,pos); |
Now, let's look at the Examples:
|
/****************************************************** * * GENERAL-PURPOSE EXAMPLE PROGRAM * ******************************************************/ #include <iostream> #include <string> using namespace std; int main() { // ******** Example code goes below here ******** string s = "abcdef"; string sTwo = "ghijkl"; //initialize string two string copiedString = s + sTwo; //copy string s and sTwo to copiedString cout << copiedString << endl; //concatenate the Yeah to the end of the copiedString copiedString = copiedString + "Yeah"; cout << copiedString << endl; int copiedStringSize = copiedString.size(); cout << copiedStringSize << endl; //string size 16 int pos = copiedString.find_first_of (sTwo, 0); cout << pos << endl; // 4 pos = copiedString.find_last_not_of ("heaY"); cout << pos << endl; // 11 unsigned k = s.find("ab"); //return 0 k = s.find('e'); //return 4 k = s.find('q'); //return string::npos if not found if (k == string::npos) { cout << "not found" << endl; } // ******** Example code goes above here ******** return 0; } |
In the example above, we declared two string and do the manipulation on them. Here are more operations on string you can do:
s.insert(pos,t); //inserts a copy of string t into s at position pos
s.substr(pos,n); //returns a copy of the substring of s consist of n characters from s, beginning at position pos. If n is too large, or if the argument n is omitted, characters are copied only until the end of s is reached.
s.replace(pos,n,t); //replace the substring in s of length n at position pos with the string t. Note: you can delete portions of a string by replacing them with " ".
s.erase(pos,n); //erase n characters string at pos position
s.c_str(); //convert a string object into a pointer to a null-terminated character array ("C-style string").
Examples:
string s = "abcdef";
string sTwo = "abcdef";
string t = s.substr(1,2); //the string "bc"
t = s.substr(3); //the string "def"
s.insert(3,"xxx"); //s is now "abcxxxdef"
sTwo.replace(0,1,"xyz"); //sTwo is now "xyzbcdef"
sTwo.erase(5,3); //erase 3 characters starting at position 5 of sTwo string, sTwo is now "xyzbc"
Operator in String:
|
s == t; //true if string s and t have //the same characters s < t; //compares string alphabetically //returns true if s comes before t s > t; s != t; s <= t; s >= t; |
Well, that's pretty much about strings but there are more strings operations you can use especially the iterator, file manipulation with string etc..You will get learn these in the next few lessons.
| Pointers, Const, References |
A pointer is a variable that holds an address of another variable. When you initialize a variable, the compiler reserves a memory space for usage. Within that space, it has a memory address.
For example:
|
int myVar = 10; cout << &myVar << endl; //print the address of myVar variable int* p_myVar; //initialize pointer p_myVar p_myVar = &myVar; //pointer p_myVar will point to myVar cout << p_myVar << endl; //print out the pointer |
In the above example, we declare myVar as int variable that holds the value of 10. We then print out the address of it. The next line, we declare a pointer variable with the * asterisk next to the variable type which is int type in our case. We then print out the pointer.
So whenever you want to declare a pointer, you will use the * next to the type.
Like:
|
char* p_myChar; int* p_pointer; double* p_prt; |
Pointers and Arrays
Let's look at the example of pointer and array.
|
/****************************************************** * * GENERAL-PURPOSE EXAMPLE PROGRAM * ******************************************************/ #include <iostream> using namespace std; int main() { // ******** Example code goes below here ******** int theArray[] = { 10, 20, 30, 40 }; int* prt; prt = theArray; for (int j = 0; j < 4; j++) { cout << *prt++ << endl; } // ******** Example code goes above here ******** return 0; } |
In the above example, you declared a pointer prt with an address to the theArray variable. We then went through each of the array index with the for loop by dereferencing it with the *(prt) or *prt, which allows you to call the pointer.
Pointers and Functions
you can pass arguments to a function by value, reference, and by pointer. If the function needs to modify objects/variables during calling, you can't passed by value. You will need to do it with a reference or a pointer.
Example of simple passing simple variable:
|
/****************************************************** * * GENERAL-PURPOSE EXAMPLE PROGRAM * ******************************************************/ #include <iostream> #include <string> using namespace std; int timesTwo(int* numb); int main() { // ******** Example code goes below here ******** int numb(6); timesTwo(&numb); cout << numb << endl; // ******** Example code goes above here ******** return 0; } int timesTwo(int* numb) { return *numb *= 2; } |
In the above example, we have a function that takes care of multiplying the number 2 and we return it with the pointer. In our main program, we call the function to do the caculation.
Function Pointer is another subject you need to know. You can check out one of the good tutorials page on function pointer is at http://function-pointer.org
Memory Management: New and Delete for pointer
When you allocate the pointer, you borrow the memory for the usage. When you're done, you will need to return it back.
Example:
prt = new Object;
....
delete prt;
OR if you have an array pointer, you will need to delete with brackets like below:
delete [] prt;
const is a keyword in C++, and it makes objects or functions as constant that can't be changed. Const refers to whichever follows right to it.
Example:
| const int LEN = 100; |
In the line above, the LEN has the value of 100 and can't be changed. You can refer to it by using LEN. This is more efficient than using #define LEN 100. Using const gives you more safety because the compiler does the checking for you.
Pointers and Const
you can make pointer and data as const like:
|
int * p_LEN; const int * p_LENb; int * const p_LENc; const int * const p_LENd; |
Function and Const
You can also use const in the function too like:
|
//you have a constant numb as an argument void dosomething(const int* numb); //both function and argument are constant and can be used to //return an object and can't be modify the object at anytime const void showMessage(const string* str) const; |
A reference is just an alias for an object.
For instance:
|
int numb = 10; int & refNumb = numb; refNumb = 35; |
In these few lines, we assigned the numb integer variable to refNumb integer as reference. We then called refNumb and assigned it with the new value 35. When we call refNumb, we're calling the numb variable.
Reference vs Pointers - What's the different? Aren't the same?
There are some differences between them.
- reference has a simple syntax and ease to read. It uses the . to refer to it and & to declare
- reference can't be a NULL and only need to be initialize once.
- as soon as you declare a reference, you will need to initialize it.
- you don't have to use new or delete like pointer
Reference using in functions
If you look at the swap function in our lesson 2, we use the reference to do it because it's less expensive operation and better performance than just passing plain value.
| Bit Operators |
Bit operator is one of the important that game programmers need to know. It's important because game programmers need to be an expert or good at big-mapped graphics.
The smallest addressable unit of storage is a byte, which consists of 8 binary bits (0's and 1's). in C++, a byte is accessible as a char which C++ treats as a number but prints as a character. There are actually two char types: signed char, and unsiged char. The latter is the one you want to use for 8 bit data. For 16 bit data, unsiged int is the preferred data type.
Consider an 8 bit binary number such as 0010 1011. Just as each decimal digit in a decimal number represents the number of 1's, 10's, 100's, etc..
43 means 4 tens + 3 ones
so 0010 1011 means
1 one
1 two
0 four
1 eight
0 sixteen
1 thirty two
0 sixty four
0 one hundred twenty eight
Adding the place values with the 1's bits set, we get
0010 1011 (binary) = 32 + 8 + 2 + 1 = 43
The data stored in an unsigned char can be represented in several ways. For example, consider the ASCII character '5':
| Representation | Values |
| character (unsiged char) | '5' |
| binary form (bit string) | 0011 0101 |
| decimal form | 53 |
| hexadecimal integer (base 16) | 0X35 |
The actual 8 bits are 0011 0101. It prints to cout as a character '5'. If you convert it to an int, it will print as 53. The hexadecimal is easier to write and read than binary. Both 4-bit halves are represented as a character from 0 to F.
| 4-bits | Hexadecimal Character |
| 0000 | 0 |
| 0001 | 1 |
| 0010 | 2 |
| 0011 | 3 |
| 0100 | 4 |
| 0101 | 5 |
| 0110 | 6 |
| 0111 | 7 |
| 1000 | 8 |
| 1001 | 9 |
| 1010 | A |
| 1011 | B |
| 1100 | C |
| 1101 | D |
| 1110 | E |
| 1111 | F |
So, how do we get the 0X35 for the character '5'? Because in binary, character '5' or in decimal form is 53, which is 0011 0101, you can look up the hexa table, we get 0011 is 3 and 0101 is 5. We have 0X35. In C++, hexadecimal characters are preceded by '\x' in a single quote. So the character '5' could also be written '\x35'
Bit as "switches"
When we work with bits in a program, we are usually the individual bits as on-off switches rather than as numbers. For example, in a graphic, a bit might indicate that the corresponding pixel is black (1) or white(0). The set operations we need for working with bits is as follows:
| Operation | Examples | Result |
| shift leff >> . Fill left bits with 0's | 0011 0101 >> 1 0011 0101 >> 2 |
0001 1010 0000 1101 |
| shift right << n positions. Fill rights bits with 0's |
0011 0101 << 1 0011 0101 << 2 |
0110 1010 1101 0100 |
| one's complement ~ If 0, turns it on to 1 . If 1 turns off to 0 | ~ 0011 0101 | 1100 1010 |
| bitwise "and" & .The resulting bit is 1 only both corresponding bits are 1 | 0011 0101 & 0101 0100 | 0001 0100 |
| bitwise "or" | . The result bit is 1 if either corresponding bit is 1 | 0011 0101 | 0101 0100 | 0111 0101 |
| bitwise "xor" ^ .The resulting bit is 1 if the corresponding bits are different or 0 if the same. | 0011 0101 ^ 0101 0100 | 0110 0001 |
Example:
|
/************************************************** * * print the bits in a bit vector * * **************************************************/ #include <iostream> #include <string> using namespace std; void printBits(unsigned char c); int main () { unsigned char x('5'); // 0011 0101 printBits(x); return 0; } void printBits(unsigned char c) { cout << showbase << hex; unsigned char mask('\x80'); unsigned char y; for (int i = 0; i < 8; i++) { //test for i y = c & mask; if (y ==0) { cout << "0"; } else { cout << "1"; } mask = mask >> 1; } cout << endl; } |
In the above example, we create a printBits function that prints the bits in a bit vector in readable form, then we call it in our main to print it in hexadecimal form.
Let's look at another example:
|
/************************************************** * * bit manipulation * * **************************************************/ #include <iostream> #include <string> using namespace std; int main () { unsigned char x('\x1A'); //0001 1010 unsigned char y; cout << showbase << hex; //compliment bitwise cout << unsigned(x) << endl; y =~x; cout << unsigned(x) << endl; //set bit 0 for last bit OR | operation unsigned char mask('\x01'); y = x | mask; cout << unsigned(y) << endl; //set bit 5 from the right to left starting 0,1,2, etc.. unsigned char mask2('\x20'); y = x | mask2; cout << unsigned(y) << endl; //reset bit 4 from the right to left using & 'AND' operation mask = '\xef'; y = x & mask; cout << unsigned(y) << endl; //test bit 5 using long way mask = 0x20; y = mask & x; //y is 0 if the bit is 0 and non zero otherwise if (y == 0) { cout << "bit 5 is off" << endl; } else { cout << "bit is on" << endl; } //test bit 4 using better way shift bit mask = 0x01; mask = mask << 4; y = mask & x; //y is 0 if the bit is 0, and non zero otherwise if (y == 0) { cout << "bit 5 is off" << endl; } else { cout << "bit is on" << endl; } return 0; } |
The example above is self explanatory. Feel free to take a careful look at it and see what it's doing.
| Objects and Classes |
This is what makes C++ different from C, Classes. The classes is object oriented programming in C++ and has the following features:
- simple classes
- abstraction
- polymorphism
- inheritance
- reusable code
In this lesson, we will only cover simple classes. We will cover the rest in the few lessons.
The class is a way for grouping all data and function into one package for representation and manipulation.
Here is the syntax for the class:
|
class MyClass { private: variables here; public: functions go here; //usually calls methods }; |
If you leave out the private, the compiler will provide a default one for you. When you design a class, you will need to separate them out into multiple files.
MyClass.h - is the header file where my class is declare
MyClass.cpp - is the source file for the class definition and implementation
Let's look at an example of class:
In the Website.h header file:
|
#ifndef _WEBSITE_H_ #define _WEBSITE_H_ /************************************************** * * Website.h: header for Website class * * **************************************************/ #include <string> class Website { private: std::string url; std::string lastChangeDate; long hitsPerDay; bool hasPopUps; public: Website(); // constructor ~Website(); // destructor // "get" functions std::string getUrl(); std::string getLastChangeDate(); long getHitsPerDay(); bool getHasPopUps(); // "set" functions void setUrl(std::string theUrl); void setLastChangeDate(std::string theDate); void setHitsPerDay(long theHitsPerDay); void setHasPopUps(bool popups); }; // end of Website class #endif |
When you design a class in the header file, you will need
|
#ifndef _WEBSITE_H_ #define _WEBSITE_H_ |
This will make sure that if and not define website.h file, go ahead and define website.h file. We end it with #endif.
Let's look at the website.h header file. In the Class declaration, we have private and public. In Private, we have few variables, string, long, and a function bool that returns true or false. In the public, we have the constructor. The constructor provides the default values for our private variables. The constructor also can be copy constructor where you can copy one class to another class. The copy constructor also needs an assignment operator. It also can be an explicit constructor where you're explicitly giving the values. We will cover all of this in the next few lessons.
Next, we have the set and get functions. The set functions responsible for assigning values to the private variables. The get functions get the private variables and give them to the calling function. We then end the class with }; don't forget the semicolon.
Now, let's take a look at the definition and implementation file for the website class.
|
/************************************************** * * implementation of Website class website.cpp * * **************************************************/ #include "Website.h" #include <string> using namespace std; Website::Website() { // basic constructor: initialize all member variables url = ""; lastChangeDate="1/1/1900"; hitsPerDay = 0; hasPopUps = false; } Website::~Website(){ // destructor // nothing to do } // "get" functions string Website::getUrl() { return url; } string Website::getLastChangeDate() { return lastChangeDate; } long Website::getHitsPerDay() { return hitsPerDay; } bool Website::getHasPopUps() { return hasPopUps; } // "set" functions void Website::setUrl(string theUrl) { url = theUrl; } void Website:: setLastChangeDate(string theDate) { lastChangeDate = theDate; } void Website::setHitsPerDay(long theHitsPerDay) { hitsPerDay = theHitsPerDay; } void Website::setHasPopUps(bool popups) { hasPopUps = popups; } |
The implementation is very straightforward. The only thing you need to know in this example is how the function written, and the constructor and destructor.
The constructor initializes all private members variables with the assigned values. The destructor is doing nothing. Usually, the destructor is handling the clean up operation after everything is done such as deleting pointers.
We then we have the function definition by adding the name of the class with two semicolon
Like: in class header file we have,
| void setHasPopUps(bool popups); |
In our website.cpp, we write it like this:
|
void Website::setHasPopUps(bool popups) { hasPopUps = popups; } |
We use Website:: next to the name of the function to define it's a class function.
Now, let's look at our main.cpp where the calling is:
|
/************************************************** * * main.cpp: test driver for Website class * * Requires: Website.h * * **************************************************/ #include <iostream> #include "Website.h" using namespace std; int main () { Website site1; site1.setUrl("gameprogramming"); site1.setHasPopUps(false); site1.setLastChangeDate("Nov. 25, 2003"); site1.setHitsPerDay(2855); // print site1 cout << "First site:" << endl; cout << "url: " << site1.getUrl() << endl; cout << "last changed: " << site1.getLastChangeDate() << endl; cout << site1.getHitsPerDay() << " hits per day, average." << endl; if (site1.getHasPopUps()) { cout << "This site has pop-up adds" << endl; } return 0; } |
In our main program, we initialize site1 as a Website class. Then we call the methods, which are the functions in the Website class, to set and get the data we want. We also go through the if expression to check if the site has pop up or not. The important point to pay attention in this is how the methods are called.
That's a very brief introduction to classes. In the next few lessons, you will learn more on classes.
In this folder, you can check out the Student classes example and play around with it.
| Practice Assignments |
Your assignment is as follows:
1. In the classesexample folder, you find the 2dGeometry classes. Some of the functions have bugs in it. Find the bugs and fix them. In the main.cpp, provides all methods for all classes to make sure they're working properly. This assignment is preparing you for the 2D game we will introduce to you using the CM graphics library next time. So be sure to complete this.
2. Design a simple tic-tac-toe game. See the design ideas in the array example above in this lesson.
3. Design the minesweeper game. Here is what you need to do
- provide the board with 9 X 9
- randomly assigns integer 9 (the integer 9 will represent as a mine or 'M') into random squares in the board for mines.
- the program writes in each of the remaining square of the board the number of mines in the surrounding squares. Look at the example picture below:

- then prints out a listing of the board 9 x 9 (be sure to provide user friendly)
- ask the user to pick a square. If the square user picked has an integer 9 or mine, show the listing of number of mines in the surrounding square. Show zeroes for empty slots.
Have fun and happy coding!
Don't forget to buy a C++ book for reference!