Object-> Programming();

Size: px
Start display at page:

Download "Object-> Programming();"

Transcription

1 Object-> Programming();

2 2 c SM 2007

3 1 More C Introduction This book provides a succinct overview of C++ programming topics, and is designed assuming that the reader has completed an introductory C++ programming course. This chapter provides additional details on a selection of topics which may have been covered in an introductory course, but most likely require revision. 1.2 Advanced Variable Management The typedef Command The typedef command allows the programmer to specify another name for a type (or define a type-name). For example: typedef int number; Allows the programmer to use number to mean int. Usually typedef is used in a more useful manner, for example: typedef long studentid; If you use studentid throughout your program, and later decide that studentids only need to be four digits long, for example, then a smaller variable would be OK. Rather 3

4 than having to search through your code and change all of the relevant longs to ints, you can simply change the studentid typedef instead. You can also use typedef in more complex ways, for example: typedef char word[20]; //... //char test[20] = "Hello!"; -- replace with: word test = "Hello!"; Note that the array size comes after the new type name, and does not need to be repeated later in the program. This means you can quickly and easily change the size of the arrays throughout your program (similar to defining a const size variable, but nicer in some ways). Later we will learn to use typedef to make Generic Collections where instead of writing a new version of the code for each type you want to use, you just change a typedef statement Type-Casting Sometimes it is desirable to temporarily change the type of a variable. This can be done in C++ by using a technique known as type-casting. Warning: Type-casting can be dangerous! By casting a variable into another type, you are telling the compiler I know that this variable is a different type, but I want you to treat is as through it were one of these. Trust me!. You can cause serious errors in your program if you type-cast variables incorrectly! Type-casting can be performed one of in two ways: (type)variable, eg: (char)i type(variable), eg: char(i) Both methods do exactly the same thing: temporarily treat variable as though it was a type. For example: int i = 123; cout << (char)123 << endl; You can also store the result in a variable; for example: char c = (char)i;. EXERCISE 1.1 Write a simple program containing a for loop which runs from 0 to 255. For each iteration of the loop, cout << i << ": " << (char)i << endl; Run your program and examine the output. The output of your program is the ASCII character map - a standard mapping of which characters (chars) are represented by which numbers (ints). 4 c SM 2007

5 1.2.3 Enumerations Enumerations are used in C++ for defining new types for which there are a fixed number of options. For example: enum Colour{Red, Orange, Yellow, Green, Blue, Indigo, Violet; This allows you to define variables of type Colour and assign any one of those value to them; for example: Colour mycarcolour = Green; To understand why enumerations are useful, think about what other ways you could possibly have stored this data. As a string (char array)? Then it would take up more space than necessary one byte for each character. Plus you would need to decide on a maximum size of the string. Issues might also arise with spelling/capitalisation (eg. "red"!= "Red"). As a char? R for red, O for orange, etc. That certainly takes less space. But what if you need to store two colours with the same letter (eg. Blue and Black, Green and Gold, etc?). As a number? OK, But then you need to remember which number represents which colour... In actual fact, C++ does store enums as numbers. But you don t need to remember which number is which. In our Colour example above, C++ would automatically represent Red as 0, Orange as 1, and so on. EXERCISE 1.2 Check if this is true by declaring the Colour enumeration in a simple program, typecasting the colours into ints and printing them using cout. You can also control which enum entry is which number, if you like. For example: enum Month{January=1,February,March,April,May,June; //... In this example, January will be stored as 1, February as 2, and so on, instead of starting from 0. You can also control the numbering more specifically; eg: enum CardRank{A=1,J=11,Q,K; EXERCISE 1.3 What are the values of Q and K? 5

6 1.3 Multiple-Source Programs Most of the programs you have written so far have probably consisted of a single file, like main.cpp. As your programs get larger and more advanced, it will become necessary to use multiple files to organise the code. You have probably already come across header files (.h files) when using libraries such as time.h or math.h, for example. Header files are sometimes also referred to as interface files. Header files do not contain the actual instruction code for the program, but data about the implementation code for example, function prototypes, typedef statements, enumerations, structs, constants, etc. Implementation files (.cpp files) contain the actual program code variables and functions. A program can consist of any number of header or implementation files. There must be at least one implementation file, as there must be a main() function to start the program. If there a program has more than one implementation file, the compiler usually requires these to be grouped together in a project so that the linker knows to link them all together. Each implementation (.cpp) file is usually compiled separately to create an object (.o) file. These are then linked together to create an executable (.exe, in Microsoft Windows) file. Header (.h) files must be #included from within the implementation files wherever necessary; every implementation file which uses a function declared in a particular header file must #include that header file itself. 1.4 Preprocessor Directives Preprocessor directives are commands which instruct the compiler how to process your source code. Preprocessor directives begin with a hash symbol (#). For example, #include <iostream.h> instructs the compiler to include the standard header file iostream.h inside your program. This means that anything defined in this header file (function prototypes, etc) is available for use in your program. You can also #include files using double-quotes ( ): #include "test.h" this means the file is not a standard library file, but probably a header file you have written yourself. The compiler will look for the header file in the directory where the.cpp file is located, unless you include a path before the filename. In a large program, it is likely that the same header file will be included by multiple implementation files, and possibly even other header files. As the program gets larger, it becomes quite likely that a header file will be included twice for the same object file, causing redefinition compiler errors. To avoid this, we can use preprocessor directives to define special variables to test whether or not the file has been already included. For example: 6 c SM 2007

7 #ifndef TEST_H #define TEST_H //Contents of file test.h... #endif This example works as follows: #ifndef means if not defined this line checks if TEST_H has been defined yet (which it won t have been on the first read) #define defines a new macro variable with the name provided. Now TEST_H is defined, so the #ifndef statement will be false next time #endif is the end of the if statement started by #ifndef when #ifndef is false, the compiler skips all the way down to the #endif statement at the end of the file, thus avoiding processing the file twice. There are other useful preprocessor directives also, such as: #undef undefine a variable #ifdef if variable is defined #elif similar to C++ else if() command #else similar to C++ else command Preprocessor directives can be useful for quickly changing the operation of your program. For example: #define DEBUG //... #ifdef DEBUG cout << "x is " << x << ", y is " << y << endl; #endif in this example, debugging output can be easily turned on or off by defining or undefining DEBUG. 7

8 1.5 Understanding Runtime Errors Occasionally whilst developing a program, your code will compile OK, but the program will crash when you run it, and possibly display an error message such as segmentation fault or bus error. If you understand what these terms mean, you will have a much better chance of quickly finding the error in your code Segmentation Faults A segmentation fault occurs when the program attempts to access an invalid memory address, or a part of memory which is not allocated to your program. This can occur by using an invalid array index, or an uninitialised/invalid pointer (which we will learn about later). For example: int myarray[10] = {10,9,8,7,6,5,4,3,2,1; for(int i = 0; i <= 10; i++){ cout << myarray[i] << endl; EXERCISE 1.4 What is the error in the above code and why could it cause a segmentation fault? Note that this code will not always produce a segmentation fault sometimes it may go undetected! Bus Errors Memory is divided into words fixed size units of memory. On a 32-bit machine, a word is 4-bytes long. Bus error usually indicate that the program has tried to access an unaligned memory address. For example, a double is eight bytes long, and must be aligned on a word-boundary (address which is a multiple of four). This kind of error is usually caused by misuse of pointers (again, which we will learn about later), but could also be caused by something like: char temp[] = "Trying to cause a bus error..."; double d = (double)temp[1]; //unaligned address 8 c SM 2007

9 1.6 Bitwise operators Normal C++ operators (+, *, etc) operate on entire variables (ints, floats, etc). C++ also includes bitwise operators which allow you to manipulate the individual bits within a variable. These include: & AND 1&1==1, 1&0==0, 0&0==0 OR 1 1==1, 1 0==1, 0 0==0 ^ XOR (exclusive OR) 1^1==0, 1^0==1, 0^0==0 ~ NOT (complement) ~1==0, ~0==1 >> Shift Right >>1== , >>3== << Shift Left <<1== , <<3== EXERCISE 1.5 What does the following program do? char c; cin >> c; for(int i = 7; i >=0; i--){ cout << ((c>>i)&1); 9

10 1.7 Random Access to Files Normally in C++ a file is opened and read or written sequentially from start to end. In some applications, particularly when reading or writing binary data, it is desirable to be able to read/write to specific locations within the file (random access). This can be achieved using the seekp and seekg commands. For each open file, C++ maintains two pointers a put-pointer (for writing) and a get-pointer (for reading). These are usually initialised to point at the beginning of the file (unless the file is opened with ios::ate (at-the-end) or ios::app (append) modifiers). seekg(i) move the get-pointer to byte #i (addressed from 0). seekp(i) move the put-pointer to byte #i (addressed from 0) Binary File Access Normally data is read from/written to files one variable at a time (int, char, string, float, etc). When using files to store an array of struct records, for example, it can work out simpler to output the entire struct in binary form. You can even output an entire array of structs at once. In order to output binary data, the file must be opened for binary I/O, for example: struct Student{ long studentid; int age; char firstname[100], lastname[100]; ; //... fstream file; //open file for binary I/O file.open("test.dat",ios::in ios::out ios::binary); Student records[100]; //load struct array from file: file.read((char*)records,sizeof(student)*100); //... //save struct array to file: file.seekp(0); file.write((char*)records,sizeof(student)*100); Explaination of example: sizeof(student) returns number of bytes needed to store a Student struct. 10 c SM 2007

11 file.read(address,nbytes) reads nbytes bytes from file (at get-pointer) and store at address file.seekp(0) move put-pointer to start of file ready for output file.write(address,nbytes) read nbytes bytes from address in memory and writes to file (at put-pointer). Note that it would be necessary to intialise the array of Students in memory and write to the file before it is possible to read it from the file! Using random access, it is also possible to read and write individual records in the array, for example: cout << "Enter student index: "; int i; cin >> i; file.seekg(sizeof(student)*i); //position get-pointer file.read((char*)&records[i],sizeof(student)); //read one Student //... //save student #i back to file: file.seekp(sizeof(student)*i); file.write((char*)&records[i],sizeof(student)); 11

12 12 c SM 2007

13 2 Pointers 2.1 Variables and memory locations Have you ever thought about what the line: int i = 0; actually means to the computer? It looks simple enough, however the computer must perform several operations to carry out this instruction. Allocate some space in the computer s memory to store this new variable. To do this, the computer must check what data type you have requested (an integer in this example), and allocate enough bytes of memory to store it. An integer typically occupies four bytes - though sizes of variables may vary on different systems; we will learn how to check the size of a variable shortly. Once a section of memory has been allocated, the computer must memorise the address of the memory location so that it knows where to look when you try to reference this new variable named i. The computer can then take the value you have requested to be stored in this variable, format it as an integer and store it in the four bytes of memory which have been allocated. 13

14 EXERCISE 2.1 C++ has an operator called sizeof which allows you to check how many bytes a particular variable or type occupies on your system. For example: cout << sizeof(int); will report how many bytes an integer occupies. You can also use the name of a particular variable rather than the type name; eg: cout << sizeof(i); Write a simple program to output the size of some common C++ data types - int, float, double, short, char and bool. Hadn t heard of bool? It is a simple data type for storing boolean values; ie: true or false. You may have used integers with the value 1 or 0 in the past, but it is more efficient, more readable and less prone to errors to use a bool. Instead of using 1 or 0 you can use the keywords true or false. If you ve not used bools before, write a simple program to test them out. EXERCISE 2.2 Try running the program variables.cpp. There is a lot of code in here that you won t understand yet; don t worry about understanding the code at this point, just run the program and experiment with it. The program allows you to choose a datatype and a value for a variable. The program then creates the variable, stores the value in it, and reports the location and size of the variable and the binary data bytes. Try creating variables of different types and watch how different values are stored. 14 c SM 2007

15 2.2 Address operator (&) You should have noticed that variables.cpp was able to tell you the exact address in memory at which the variable was stored. This is very simple to achieve, using the address operator (&). For example: cout << &i; will output the address of variable i. This is normally output in hexadecimal format. If you would like to view the address as a decimal number, you can type-cast it into an integer - eg: cout << (int)&i; In fact to see the address of a char, you have to type-cast it, because char addresses are treated differently by cout - it will think you are trying to output a string (char array), not an address - we will learn more about this shortly. TIP: &i means the address of i EXERCISE 2.3 Write your own simple program to print out the addresses of some variables of different types. Try type-casting the addresses to integers to view the addresses in decimal format. Note the relationships between the addresses. Declare a few variables, note their addresses, and try to guess where the next variable will be allocated if you add another. REVISION: Pass by Reference You should recognise the & operator, because you have used it before - whenever you passed a variable argument to a function by reference. This is because when you passed by reference rather than by value, all the function needed was the address of the variable in memory so that it could access it, rather than making a temporary copy for the function. 15

16 2.3 Pointers You may wonder why you should care what memory address has been assigned to your variables. Unless you are analysing the system s memory allocation scheme, the numeric address information is irrelevant. However, C++ allows you to store the address in another variable, which you will soon find useful indeed. A variable which contains the address of another variable is called a pointer - simply because it effectively points at another variable. TIP: A pointer contains the address of another variable For example: int a; int b = &a; defines an integer which holds the address of another integer; this is effectively a pointer. However, C++ requires pointer variables to be declared specially - this allows us to easily differentiate between, for example, an integer which contains the value 123 and an integer which points at the address 123. The correct definition of a pointer is as follows: int a; int *b = &a; The * indicates that variable b is a pointer. Note that you still need to specify that b is of type int. This is because C++ requires you to specify what type of variable b will point to. Thus if you try to point an int pointer at a float, for example, like this: float a; int *b = &a; the compiler will generate an error message indicating that the pointer cannot be used in this way. This restriction helps to make sure you do not use pointers incorrectly. EXERCISE 2.4 Write a short program that creates three variables (int, float, char) and a pointer to each. Use cout to print the address of the variables using the pointers. 16 c SM 2007

17 Warning: Pointers can be declared in any of these ways: int* p1; int *p2; int * p3; (note the locations of the *s). The * is technically a part of the type, not the variable name, so it would makes sense to write it next to the type (like in the declaration of p1 above)... however: int* p1, p2; does not declare two pointers - it p1 will be a pointer, p2 will just be a normal int. TIP: To declare more than one pointer, you must put a * before each one, like this: int *p1, *p2; For this reason it is recommended that pointers are always declared with the * next to the variable name, to avoid confusion. Note that the pointers which have been declared in the previous example do not actually point at anything yet. Like with all other variables, it is usually a good idea to provide them with a value when you declare them, to avoid errors involving uninitialised variables (which may have strange values). For an int, you would usually declare something like: int i = 0; For a pointer, 0 is a special value - it is not a valid address, therefore the pointer points at nothing (and should not be used as thought it did). When setting a pointer to 0, however, we normally use a special constant called NULL. This is declared in header files such as iostream. It is exactly the same as 0, but helps us to remember that we are using a pointer and it points at nothing. Therefore, when declaring pointers before they need to point at anything, you should use: int *p = NULL; REVISION: NULL Can you recall any other special constants in C++ which simply mean 0? When printing C++ strings of chars (known as c-strings), code such as cout functions simply regard each byte from the start of the array to be a character in the string until a zero-byte (or null-byte) is found. Thus we used the null-character ( \0 ) - simply a char equal to 0 - to terminate strings. 17

18 2.4 Reference operator Once you have stored the address of a variable in a pointer, you won t usually want to print out the address. What you may want to do, however, it to print out the value of the variable it points to. This is done by using the reference operator (*). Warning: Note that this is the same symbol (*) used to declare a pointer variable - but in this case it means something totally different (just as it means something different again when used in multiplication) - beware confusing these different uses. Just as placing the address operator (&) before a variable name refers to the address of that variable, placing the reference operator (*) before a pointer variable name refers to the value of the variable at the address stored in the pointer. TIP: *p means the value pointed at by pointer p EXERCISE 2.5 What will be the output of the following code? int *p = NULL; int i = 123; p = &i; cout << i << endl; cout << &i << endl; cout << p << endl; cout << &p << endl; cout << *p << endl; EXERCISE 2.6 Trace the contents of the variables in this program and state the output: int *p = NULL; int i = 123, j = 456, k = 789; p = &i; int temp = i; i = k; k = temp; temp = j; j = *p; *p = temp; p = &j; cout << i << " " << j << " " << k << " " << *p << endl; 18 c SM 2007

19 2.5 Pointers and arrays You may yet fail to see the point of pointers. Are they useful for anything but confusing exercises? Yes! As a matter of fact, you have probably already been using pointers in your C++ programming without realising it. When you write code such as: int numbers[10]; what does C++ do? It allocates enough space for ten integers in a row in memory, and creates a pointer called numbers which points to the first element of the array! The only difference between the numbers pointer and a normal pointer which you declare yourself is that numbers is constant - you cannot point it at anything else. Saying: numbers[0] = 100; has exactly the same effect as saying: *numbers = 100; because numbers is a pointer to the first element. Likewise, can be restated as: numbers[1] = 99; *(numbers+1) = 99; The [] operators hide all of the ugly pointer details from the programmer and make it look simpler. But behind the scenes, a pointer is doing all the work of finding each element in the array according to the index you provide. TIP: The variable name of an array is simply a pointer to the first element of the array TIP: numbers[n] is equivalent to *(numbers+n) TIP: &numbers[n] is equivalent to (numbers+n) EXERCISE 2.7 Write a short program that declares an array of integers and uses a for loop to print out the contents of the array using pointer notation instead of array subscripting ([]). 19

20 EXERCISE 2.8 What does the following code do? const int n = 10; int numbers[n]; for(int *p = numbers; p < numbers+n; p++){ cout << *p << endl; 2.6 Pointer arithmetic You may have noticed that in our examples regarding arrays, pointers were used in arithmetic equations such as: *(numbers+n) What does this actually mean? Practically, it allows us to find the address of subsequent array elements. If numbers points to an integer at address 4321, you might think that numbers+1 would point to address Does it? EXERCISE 2.9 What output does the following program give: int i = 10, *p = &i; cout << (int)p << endl; //output address of i in decimal cout << (int)(p+1) << endl; What is the difference between the two numbers? If it is not 1, why not? Because C++ requires you to specify the type of a pointer, it will know the size of the variable that it points to. Thus if you have an integer pointer p, p+1 and p++ will refer to the next integer address, which is actually four bytes (the size of an integer) away. You don t have to worry about this - just understand that C++ will take care of it for you. 2.7 Void pointers We have now seen several reasons why C++ requires us to specify the type of variable to which a pointer may point. In some situations, however, you may require a generic pointer variable which can point at anything. This is possible, but in doing so the programmer must be very careful to use the pointer properly as C++ will be less able to help keep you from making mistakes. A pointer of type void can point at any type of variable. You may need to use a lot of type-casting in a program which utilises void pointers. 20 c SM 2007

21 2.8 Pointers to structs and classes Remember when you declare a struct in C++ you normally use the. operator to access the member variables within the struct, like: struct Student{ long studentid; char name[max]; ; //... Student s1; s1.studentid = 1234; When you use a pointer to a structure, you cannot use the. operator directly: Student* sp = &s1; sp.studentid = 1234; //DOESN T WORK (*sp).studentid = 1234; //OK However C++ also provides a nicer way of working with pointers to structs and classes (we will learn about classes shortly) the -> operator can be used: sp->studentid = 1234; //OK TIP: The -> operator can be used to access members of a struct or class using a pointer 21

22 2.9 Function Pointers Another handy use of pointers in C++ involves using pointers to functions. Just as a normal pointer allows the programmer to perform operations on whichever variable is referenced by the pointer at the time, function pointers allow a statement to call different functions. Just as array names can be used like pointers to the first element of the array, normal function names can be treated as pointers to the functions. This means you can declare your own function pointer variable and use it to point at different functions. Just as C++ requires you to specify what type a variable pointer can point at, with function pointers you must specify the return-type and argument list for the function pointer. Function pointers declarations look the same as the function prototype, but with the name of the function in parentheses (brackets) and an asterisk (*) inserted before the function name. For example: //if you have a function like this: int sum(int a, int b){ return a+b; int main(){ //you can declare a pointer like this: int (*myfunctionpointer)(int,int); myfunctionpointer = sum; int x = (*myfunctionpointer)(123,456); cout << x << endl; //... Or here is a more useful example: const int MAX = 50; struct Animal{ char name[max]; char noise[max]; void (*actionfunction)(); ; 22 c SM 2007

23 void cowfunction(){ cout << "Would you like to see the cow? "; char c; cin >> c; if(c== n ) return; cout << " /(_)\\ * " << endl; cout << " )o_o( / " << endl; cout << " (^_^) ( ) \\ " << endl; cout << " T ~ /~\\ ~\\/ " << endl; cout << " \\_/ " << endl; cout << " (II) " << endl; cout << " _ _ _ _ " << endl << endl; void sheepfunction(){ cout << "Enter number of sheep: "; int nsheep; cin >> nsheep; for(int i = nsheep; i > 0; i--){ cout << "Sheep #" << i << " jumped the fence." << endl; cout << "Goodnight!" << endl << endl; int main(){ const int nanimals = 3; Animal farmyard[nanimals] = { {"cow","moo",cowfunction, {"sheep","baa",sheepfunction, {"aardvark","?",null ; cout << "Old Macdonald had a farm... " << endl; for(int i = 0; i < nanimals; i++){ cout << "...and on that farm he had a "; cout << farmyard[i].name << "..." << endl; if(farmyard[i].actionfunction!=null) (*(farmyard[i].actionfunction))(); else cout << "... which did nothing at all..." << endl; cout << endl << "Thank you for visiting the farm!" << endl; return 0; 23

24 24 c SM 2007

25 3 Dynamic Memory Another area of C++ programming where pointers become invaluable is that of dynamic memory. In Section 2.1 we learned how the computer allocates a section of memory for a variable at the time it is declared, and links the variable name to that address. This link is permanent - the variable will remain at that memory location until it goes out of scope and ceases to exist. REVISION: Array allocation What is the error in the following code: int n; cout << "How many numbers do you want to enter? "; cin >> n; int numbers[n]; for(int i = 0; i < n; i++){ cout << "Enter number #" << i << ": " << endl; cin >> numbers[i]; Remember that C++ requires you to specify the size of arrays before compilation, so that it knows in advance how much space to allocate in memory. 25

26 There are certain situations in which this memory allocation scheme will not be suitable (for example, in writing a program like the previous example). You may need to decide the size of the array at runtime (after compilation, when you execute the program). It is not always practical to declare a MAX_ARRAY_SIZE variable, as you may waste a lot of memory space trying to accomodate the largest possible value. You may also want to change the size of an array during the execution of your program. It is possible to create and delete variables and arrays at runtime according to the operation of the program, by taking advantage of C++ s dynamic memory management features. Like pointers, dynamic memory management is a very powerful and useful language feature, but requires careful thought from the programmer to avoid creating serious errors. Variables declared dynamically are stored in a special section of memory. The dynamic memory section is often also referred to as the heap. Warning: Any variables created in this section of memory are your responsibility. Once you have declared them, they remain allocated until you delete them. Even program termination may not free the memory you have allocated! When you declare a variable in dynamic memory, C++ gives you its address in a pointer; make sure you do not lose the address before you delete the variable, or you will create what is called a memory leak. 3.1 The new operator To declare a variable to be stored in dynamic memory, simply use the new operator: int *i = new int; Note that new returns an address and must therefore be stored in a pointer. Therefore to use i like a normal integer, you must use the reference operator; for example: cout << "Enter value: "; cin >> *i; //not cin >> i; 26 c SM 2007

27 Warning: Find two problems in the following code: double *d = new double; cout << "Address of double: " << &d << endl; cout << "Size of double: " << sizeof(d) << endl; //... You do not need to use the address operator (&) to print the address of dynamically declared variables, since you can only access the variable using the pointer returned by new thus in the above example, &d refers to the address of the pointer itself, not that of dynamically declared integer. Likewise, sizeof(d) will give the size of the pointer (all pointers are the same size, regardless of what datatype they point to), not the size of the double. A correct version of the previous code fragment follows: double *d = new double; cout << "Address of double: " << d << endl; //pointer IS address cout << "Size of double: " << sizeof(*d) << endl; EXERCISE 3.1 Try declaring three variables; one in dynamic memory using new, two declared normally. Print out the addresses of the variables in decimal format (by type-casting to int). Compare the addresses of the three variables. Does it look like dynamic variables are stored in a different section of memory? You can also declare a dynamic array similarly: int n; cout << "How many? "; cin >> n; int *a = new int[n]; Note that a can now be used just like a normal array - since we learned that normal array names are actually just pointers to the first element of the array anyway. TIP: Each and every time you use new in your program, you must later use delete to avoid memory leaks 27

28 3.2 The delete operator The delete operator must be used to free the dynamic memory which was allocated by new. For example: int *i = new int; \\... delete i; This must be done for each and every variable which is created using new. Warning: A different operator exists to delete arrays - you cannot use the normal delete operator: int *a = new int[n]; \\... delete a; //WRONG! This will only delete the first element! To delete an array from dynamic memory, use delete[]: int *a = new int[n]; \\... delete[] a; //CORRECT! The whole array is deleted. EXERCISE 3.2 Write a new, correct version of the program at the beginning of this chapter in which the user can select how many numbers they wish to enter into an array ensure you use new to allocate the array correctly, and delete to prevent memory leaks. 28 c SM 2007

29 4 Objects 4.1 Classes and Objects All of the C++ programming you have been doing up until now has probably been what is known as procedural programming. This means your program is simply based on procedures start here, do this, do that, allocate this memory, then loop ten times and do this, read this file, print the output, wait for keyboard instruction, if read q then terminate program.... Your program is just a big list of instructions, like a recipe that the computer needs to follow one step at a time. We are about to learn about object-oriented programming, which is a bit different. Object-based programming involves describing different types of objects to the computer, including what they are and what they can do then at runtime the computer will create the objects you described and their interaction will define the operation of your program. Thus instead of your program being a collection of functions (or procedures), your program will be a collection of interacting objects. Your program can still be broken down into a pile of basic instructions, but the way you program it is very different. Object-oriented programming has a number of advantages. It can often be easier to write, read and understand object-oriented programs. Object-oriented programs are naturally broken down into logical object units, which are often stored in their own separate files. This is very helpful when developing larger programs (applications, games, operating systems, etc) with a team of programmers the design of the program can be looked 29

30 at from a very high level, the designers can choose what objects will be involved, and individual programmers can work on their own objects to perform their particular tasks. This tends to be much more managable than working with large procedural programs. Note that so far we have been talking about objects. Some of the uses of the term object above are actually incorrect; the term class should sometimes be used instead. What is a class? A class refers to a category of object. It is similar to a datatype in C++. Consider the declaration int i,j; i and j are variables of type int. Now consider the declaration myobject a,b;. In this example, myobject is a type of object or a class of object and a and b are the actual objects (also known as instances of that particular class or object). TIP: A class defines a type of object; an object is an individual instance or variable of that type. So what exactly is an object? An object in the real world tends to be a physical thing ; for example a pen or a computer could be considered an object. Programming objects are obviously not physical; they are software things that usually contain information and can do things. For example, a pen object in software might store information such as its colour, the width of the line that it can draw, and perhaps even how many millilitres of ink it has remaining! A pen object might also be able to do things, such as draw lines on the screen. Your software objects may or may not be representative of real physical objects. You can create whatever weird and wonderful imaginary objects you like. We have established that an object can: store information, and do things. In C++ this means that a class of objects has: variables (for storing information), and functions (for performing tasks). 30 c SM 2007

31 4.2 Classes and Structs Classes are very similar to structs. structs allow the programmer to group a number of variables into one logical unit for a particular purpose. For example: struct Student{ long studentid; char firstname[max]; char lastname[max]; int age; ; This is very useful, as we can now treat Student as a normal datatype. Thus we can easily create a whole array of students: Student school[500]; or pass a whole student to a function as an argument: void enrol(student s1); But remember classes have functions too. Well in actual fact, structs are also capable of containing functions! EXERCISE 4.1 Write a short program that declares a Student struct similar to the one described earlier. Try declaring a void print() function inside the struct which prints out the student s details. Test your struct by creating an instance (variable) of type Student in your main function and calling the print() function (you may want to initialise the Student s variable members first). Accessing a function inside a struct is done in the same way as accessing a member variable use the. operator (eg. s1.print()). Note how much neater it is to declare the print() function inside the struct rather than having an external function. You can then very neatly include all code related to Students inside functions in the Student struct itself. You may not realise it, but in the previous exercise you have almost finished writing your first class. The only changes required to change the Student from a struct to a class are: change the word struct to class insert a line stating public: as the first line within the Student definition TIP: The functions and variables within a class are often referred to as being members of that class. 31

32 4.3 public and private members So why bother using classes when structs are basically the same? Normally structs are used for data-only structures (without functions). The main difference is the fact that within a class, the programmer has control over which member functions and variables are public or private. What does it means for a member to be public or private? These keywords give the programmer control over whether the functions or variables are allowed to be accessed by code outside of the class itself; private functions and variables can only be accessed by code inside the class in which they were declared, whereas public members can be accessed from any code. This helps to ensure that the class you write is used correctly remember that other programmers might be writing code that uses your class. The public members of a class form the interface of the class the code with which other classes and functions can interact. The private members of a class are used only for internal operations within the class itself, and are kept private so that other classes or functions cannot interfere with the data. When declaring a struct, all members are automatically made public. When declaring a class, all members are assumed to be private unless specified as public. Here is a simple example class: class Student{ private: public: ; long studentid; char firstname[max]; char lastname[max]; int age; void print(){ cout << "Student #" << studentid << ": "; cout << firstname << " " << lastname; cout << " (age " << age << ")" << endl; Note that you do not need to specify private or public for every variable or function; classes are normally declared with a private section and a public section, as in the previous example. In this example, the variables in the class cannot be directly accessed by other classes or functions. EXERCISE 4.2 Declare the Student class above in a C++ file, and try accessing the variables using a main function. Does the compiler give you any errors or warnings? Can you access the print() function from main? What happens if you remove the public and private labels from the class altogether? 32 c SM 2007

33 4.4 Accessors and Mutators Often you may want to keep variables in your class private, but allow other classes readonly access to them. Or you may want to allow other classes to modify your variables, but with certain restrictions on their use. This can be achieved by providing special public functions which access the private variables. A public function which returns a copy of a private variable is called an accessor function (because it provides access to the private variable) for example: long getstudentid(){ return studentid; Note that this will allow other classes and functions to read the value of the studentid variable, but modifying the returned value will not affect the object s private variable, as only a copy is returned (ie. it is not returned a reference or pointer). Accessor functions are usually named getvariablename(), where VariableName is the variable s name. A mutator function is one which allows other classes to modify ( mutate ) private variables under controlled circumstances. It will usually receive the requested value as an argument, and return a value indicating whether or not the modification was successful. For example: bool setstudentid(long newid){ if(newid> && newid<= ){ studentid = newid; return true; cout << "Student ID must be 7 digits." << endl; return false; EXERCISE 4.3 Write accessor and mutator functions for the private variables in your Student class. Make sure that the student ID is seven digits long, the names are at least one character long, and the age is greater than zero. 33

34 Accessor and mutator functions which access arrays are a little tricky; for the previous exercise, you may have written an accessor for firstname like: char* getfirstname(){ return firstname; This works fine, but there is one problem. Since you cannot return an array (unless you put it inside a struct, for example), you have to return a pointer. However this pointer will point at the actual firstname array inside the Student object. This means that if the calling function does something like this: char* temp = s1.getfirstname(); //... strcpy(temp,"abc"); this will actually change the Student s firstname variable! This is bad, because firstname is supposed to be private, however we ve just given away a pointer to it, so other functions can now do what they like with it, including modify it. It would be better to return a copy of the array. This could be done like this: void getfirstname(char temp[]){ strcpy(temp,firstname); This would mean that the calling function must now declare its own array: char temp[max]; s1.getfirstname(temp); 34 c SM 2007

35 4.5 Constructors Note that you cannot initialise any variables when you declare them in you class; for example: int i = 0; declared inside your class will generate a compiler error, because you cannot assign values to (initialise) non-constant variables inside classes as they are declared. Instead you must initialise your variables in a special function called a constructor. A constructor is a special class function that contains all code that should be executed whenever an object variable of that class type is created. That means when you create an object, like: Student s1; C++ will automatically call a special Student constructor function (if one exists) to initialise your s1 object. What does a constructor look like? It has two special properties that identify it as being a constructor: It has NO return type (ie. not even void) The function name is exactly the same as the class name So a constructor for the Student class would look like: Student(){ //initialise variables, etc A constructor such as this which has no arguments is called a default constructor. It is possible to declare multiple constructor functions for a single class by using overloading. Overloading refers to the declaration of several functions with the same name but different arguments. This can be done for any function; C++ can tell which function to use by examining the arguments in the function call. When declaring an object, C++ allows the specification of constructor arguments after the variable name; for example: Student s1; //calls default constructor with no args Student s2(1234); //calls a constructor with an arg //etc. For the declaration of s2 above, a constructor with a single numeric argument would need to have been declared: Student(long ID){ //initialise variables, etc studentid = ID; //... 35

36 Declaring constructors with arguments allows objects to be created and initialised quickly and easily. Note that if you declare constructors with arguments but do not declare a default constructor (which has no arguments), C++ will automatically generate an empty one for you (which does nothing). EXERCISE 4.4 Experiment with declaring some constructors for your Student class. Write a default constructor which initialises the variables and prints "Default". Try creating a Student object in main and see if this constructor is indeed called. EXERCISE 4.5 Write a second constructor with four arguments that allow the student s ID, first and last name and age all to be initialised. Include a call to the print() function inside this constructor. Test your constructor in your main function. There is another special type of constructor known as a copy constructor. A copy constructor is used when creating an objects which should be an exact copy of another object. If you do not write a copy constructor, C++ will automatically generate a basic one for you, but beware the automatic copy constructor written by the compiler will not properly handle complex objects with pointers and dynamic memory, as it only performs a simple shallow copy (ie. it copies the pointer, but not the memory that it points to). A copy constructor is simply a constructor with a constant reference to another object of that class as an argument; for example: Student(const Student& other){ studentid = other.studentid; //copy other data from other... This constructor will be called automatically in the following situations: Student s2(s1); //where s1 is another Student object Student s3 = s1; EXERCISE 4.6 Write a copy constructor for your Student class and include a line which outputs "Copy". Try creating some Student objects in main as copies of another Student object, as shown in the previous example. Run your program and see if these do indeed call the copy constructor (by checking if "Copy" is output each time). Do both of the following situations call the copy constructor? Student s3 = s1; Student s4; s4 = s1; Why or why not, do you think? 36 c SM 2007

37 4.6 The this Pointer You may have been intrigued by the line in the example copy constructor which stated: studentid = other.studentid; It makes sense that the studentid being copied belongs to object other, but how does the compiler know which Student to copy it to? There is no object name given, just studentid. In actual fact, the compiler can tell which object the statement refers to by knowing which object it is constructing; that is, if the function was called by the statement: Student s2(s1); //where s1 is another Student object Then the argument to the function is s1, so s1 will be refered to by other. The object being initialised is obviously s2. Likewise, in a function like: void print(){ cout << "Student ID: " << studentid << endl; //... The studentid belongs to the object whose print() function was called, for example: s2.print(); The way this actually works in C++ is that the object whose function is being called (that is, the variable name before the. before the function name, in this case s2) is passed automatically to the function via an invisible pointer argument called this. You might need to read that sentence a few times to understand it fully. So if you don t specify an object name inside a function when refering to a member variable or function, C++ will assume you are referring to the object this (the object whose function was called, ie. the object before the. ). If you like, you can explicitly use the this pointer yourself to make it clearer; for example: this->studentid = other.studentid; this does exactly the same thing whether you include this-> or not, but it might make more sense to you this way; it is entirely up to you, the programmer. EXERCISE 4.7 Try rewriting the print() function and constructors of your Student class making use of the this-> operator wherever applicable. Does it make more or less sense to you? 37

38 4.7 Destructors You should now understand what constructors are, how they are declared and used, and why they are useful. They basically give the computer a construction manual for your object, usually just involving variable initialisation, sometimes dynamic memory allocation, sometimes other operations altogether. A constructor function is called automatically everytime you create an object, and the compiler decides which constructor to call based on the situation in which the object is declared. There is a very similar special class function in C++ which is almost the exact opposite of a constructor a destructor. Destructors tell the computer how to destruct/destroy your object; or more specifically, they define any operations that should take place when a variable is deleted either explicitly using delete or by going out of scope. For some classes of object this is unnecessary, however any classes which utilise dynamic memory should usually clean up all of their dynamic variables in their destructor function. A destructor function looks very similar to a constructor, in that it also has no return type and the same name as the class name however it has a tilde (~) at the beginning of the function name. For example: ~Student(){ //clean up dynamic memory for object, etc Unlike constructors, destructors cannot be overloaded there is just a single destructor function which is called automatically when the object is deleted. EXERCISE 4.8 The Student class you have been working on so far does not have any dynamic memory associated with it, so does not technically need a destructor. However, for the purposes of experimentation, add a destructor which simply prints "Goodbye" (and perhaps the name of the student so you can tell which Student object was just deleted). Experiment with your destructor by creating and deleting Student objects in the main function; try using delete to remove a dynamically allocated Student, and try just making the objects go out of scope. Does it work with arrays of objects? EXERCISE 4.9 Try allocating an array of Students in dynamic memory, and then deleting them. See what happens if you forget to use delete[] and use delete instead. 38 c SM 2007

Preprocessor Directives

Preprocessor Directives C++ By 6 EXAMPLE Preprocessor Directives As you might recall from Chapter 2, What Is a Program?, the C++ compiler routes your programs through a preprocessor before it compiles them. The preprocessor can

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

COMP322 - Introduction to C++ Lecture 02 - Basics of C++ COMP322 - Introduction to C++ Lecture 02 - Basics of C++ School of Computer Science 16 January 2012 C++ basics - Arithmetic operators Where possible, C++ will automatically convert among the basic types.

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

C++ for Java Programmers

C++ for Java Programmers Basics all Finished! Everything we have covered so far: Lecture 5 Operators Variables Arrays Null Terminated Strings Structs Functions 1 2 45 mins of pure fun Introduction Today: Pointers Pointers Even

More information

Intro. Scheme Basics. scm> 5 5. scm>

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 08 Constants and Inline Functions Welcome to module 6 of Programming

More information

QUIZ. What is wrong with this code that uses default arguments?

QUIZ. What is wrong with this code that uses default arguments? QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code

More information

377 Student Guide to C++

377 Student Guide to C++ 377 Student Guide to C++ c Mark Corner January 21, 2004 1 Introduction In this course you will be using the C++ language to complete several programming assignments. Up to this point we have only provided

More information

Variables and Constants

Variables and Constants HOUR 3 Variables and Constants Programs need a way to store the data they use. Variables and constants offer various ways to work with numbers and other values. In this hour you learn: How to declare and

More information

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT C Review MaxMSP Developers Workshop Summer 2009 CNMAT C Syntax Program control (loops, branches): Function calls Math: +, -, *, /, ++, -- Variables, types, structures, assignment Pointers and memory (***

More information

Pointers. Reference operator (&) ted = &andy;

Pointers. Reference operator (&)  ted = &andy; Pointers We have already seen how variables are seen as memory cells that can be accessed using their identifiers. This way we did not have to care about the physical location of our data within memory,

More information

A Fast Review of C Essentials Part I

A Fast Review of C Essentials Part I A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types

More information

Physics 306 Computing Lab 5: A Little Bit of This, A Little Bit of That

Physics 306 Computing Lab 5: A Little Bit of This, A Little Bit of That Physics 306 Computing Lab 5: A Little Bit of This, A Little Bit of That 1. Introduction You have seen situations in which the way numbers are stored in a computer affects a program. For example, in the

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

QUIZ. What are 3 differences between C and C++ const variables?

QUIZ. What are 3 differences between C and C++ const variables? QUIZ What are 3 differences between C and C++ const variables? Solution QUIZ Source: http://stackoverflow.com/questions/17349387/scope-of-macros-in-c Solution The C/C++ preprocessor substitutes mechanically,

More information

Objectives. In this chapter, you will:

Objectives. In this chapter, you will: Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about

More information

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

Arrays array array length fixed array fixed length array fixed size array Array elements and subscripting

Arrays array array length fixed array fixed length array fixed size array Array elements and subscripting Arrays Fortunately, structs are not the only aggregate data type in C++. An array is an aggregate data type that lets us access many variables of the same type through a single identifier. Consider the

More information

6. Pointers, Structs, and Arrays. 1. Juli 2011

6. Pointers, Structs, and Arrays. 1. Juli 2011 1. Juli 2011 Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 1 of 50 Outline Recapitulation Pointers Dynamic Memory Allocation Structs Arrays Bubble Sort Strings Einführung

More information

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE? 1. Describe History of C++? The C++ programming language has a history going back to 1979, when Bjarne Stroustrup was doing work for his Ph.D. thesis. One of the languages Stroustrup had the opportunity

More information

PIC 10A Objects/Classes

PIC 10A Objects/Classes PIC 10A Objects/Classes Ernest Ryu UCLA Mathematics Last edited: November 13, 2017 User-defined types In C++, we can define our own custom types. Object is synonymous to variable, and class is synonymous

More information

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

6. Pointers, Structs, and Arrays. March 14 & 15, 2011

6. Pointers, Structs, and Arrays. March 14 & 15, 2011 March 14 & 15, 2011 Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 1 of 47 Outline Recapitulation Pointers Dynamic Memory Allocation Structs Arrays Bubble Sort Strings Einführung

More information

Operator overloading

Operator overloading 1 Introduction 2 The copy constructor 3 Operator Overloading 4 Eg 1: Adding two vectors 5 The -> operator 6 The this pointer 7 Overloading = 8 Unary operators 9 Overloading for the matrix class 10 The

More information

Input And Output of C++

Input And Output of C++ Input And Output of C++ Input And Output of C++ Seperating Lines of Output New lines in output Recall: "\n" "newline" A second method: object endl Examples: cout

More information

Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo Chapter 10 Pointers and Dynamic Arrays 1 Learning Objectives Pointers Pointer variables Memory management Dynamic Arrays Creating and using Pointer arithmetic Classes, Pointers, Dynamic Arrays The this

More information

printf( Please enter another number: ); scanf( %d, &num2);

printf( Please enter another number: ); scanf( %d, &num2); CIT 593 Intro to Computer Systems Lecture #13 (11/1/12) Now that we've looked at how an assembly language program runs on a computer, we're ready to move up a level and start working with more powerful

More information

CS201 Latest Solved MCQs

CS201 Latest Solved MCQs Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

CE221 Programming in C++ Part 1 Introduction

CE221 Programming in C++ Part 1 Introduction CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab

More information

G52CPP C++ Programming Lecture 9

G52CPP C++ Programming Lecture 9 G52CPP C++ Programming Lecture 9 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture const Constants, including pointers The C pre-processor And macros Compiling and linking And

More information

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved.

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved. Chapter 10 Pointers and Dynamic Arrays Copyright 2016 Pearson, Inc. All rights reserved. Learning Objectives Pointers Pointer variables Memory management Dynamic Arrays Creating and using Pointer arithmetic

More information

Fall 2017 CISC/CMPE320 9/27/2017

Fall 2017 CISC/CMPE320 9/27/2017 Notices: CISC/CMPE320 Today File I/O Text, Random and Binary. Assignment 1 due next Friday at 7pm. The rest of the assignments will also be moved ahead a week. Teamwork: Let me know who the team leader

More information

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics PIC 10A Pointers, Arrays, and Dynamic Memory Allocation Ernest Ryu UCLA Mathematics Pointers A variable is stored somewhere in memory. The address-of operator & returns the memory address of the variable.

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

Cpt S 122 Data Structures. Introduction to C++ Part II

Cpt S 122 Data Structures. Introduction to C++ Part II Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function

More information

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012 MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012 Instructor: K. S. Booth Time: 70 minutes (one hour ten minutes)

More information

The C Programming Language Guide for the Robot Course work Module

The C Programming Language Guide for the Robot Course work Module The C Programming Language Guide for the Robot Course work Module Eric Peasley 2018 v6.4 1 2 Table of Contents Variables...5 Assignments...6 Entering Numbers...6 Operators...7 Arithmetic Operators...7

More information

Lab # 02. Basic Elements of C++ _ Part1

Lab # 02. Basic Elements of C++ _ Part1 Lab # 02 Basic Elements of C++ _ Part1 Lab Objectives: After performing this lab, the students should be able to: Become familiar with the basic components of a C++ program, including functions, special

More information

CS201 Some Important Definitions

CS201 Some Important Definitions CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data

More information

Software Design and Analysis for Engineers

Software Design and Analysis for Engineers Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 4 Date:

More information

Functions, Pointers, and the Basics of C++ Classes

Functions, Pointers, and the Basics of C++ Classes Functions, Pointers, and the Basics of C++ Classes William E. Skeith III Functions in C++ Vocabulary You should be familiar with all of the following terms already, but if not, you will be after today.

More information

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage: Discussion 1H Notes (Week 3, April 14) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs31 More on Arithmetic Expressions The following two are equivalent:! x = x + 5;

More information

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Quiz Start Time: 09:34 PM Time Left 82 sec(s) Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

QUIZ Friends class Y;

QUIZ Friends class Y; QUIZ Friends class Y; Is a forward declaration neeed here? QUIZ Friends QUIZ Friends - CONCLUSION Forward (a.k.a. incomplete) declarations are needed only when we declare member functions as friends. They

More information

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead.

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead. Chapter 9: Rules Chapter 1:Style and Program Organization Rule 1-1: Organize programs for readability, just as you would expect an author to organize a book. Rule 1-2: Divide each module up into a public

More information

Introducing C++ to Java Programmers

Introducing C++ to Java Programmers Introducing C++ to Java Programmers by Kip Irvine updated 2/27/2003 1 Philosophy of C++ Bjarne Stroustrup invented C++ in the early 1980's at Bell Laboratories First called "C with classes" Design Goals:

More information

CS112 Lecture: Working with Numbers

CS112 Lecture: Working with Numbers CS112 Lecture: Working with Numbers Last revised January 30, 2008 Objectives: 1. To introduce arithmetic operators and expressions 2. To expand on accessor methods 3. To expand on variables, declarations

More information

Variables. Data Types.

Variables. Data Types. Variables. Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable. We had to write several lines of code, compile them, and then execute the resulting

More information

A brief introduction to C++

A brief introduction to C++ A brief introduction to C++ Rupert Nash r.nash@epcc.ed.ac.uk 13 June 2018 1 References Bjarne Stroustrup, Programming: Principles and Practice Using C++ (2nd Ed.). Assumes very little but it s long Bjarne

More information

Reference operator (&)

Reference operator (&) Pointers Each cell can be easily located in the memory because it has a unique address and all the memory cells follow a successive pattern. For example, if we are looking for cell 1776 we know that it

More information

BLM2031 Structured Programming. Zeyneb KURT

BLM2031 Structured Programming. Zeyneb KURT BLM2031 Structured Programming Zeyneb KURT 1 Contact Contact info office : D-219 e-mail zeynebkurt@gmail.com, zeyneb@ce.yildiz.edu.tr When to contact e-mail first, take an appointment What to expect help

More information

G52CPP C++ Programming Lecture 8. Dr Jason Atkin

G52CPP C++ Programming Lecture 8. Dr Jason Atkin G52CPP C++ Programming Lecture 8 Dr Jason Atkin 1 Last lecture Dynamic memory allocation Memory re-allocation to grow arrays Linked lists Use -> rather than. pcurrent = pcurrent -> pnext; 2 Aside: do not

More information

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs. Lesson 2 VARIABLES Aim Understanding how computer programs store values, and how they are accessed and used in computer programs. WHAT ARE VARIABLES? When you input data (i.e. information) into a computer

More information

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file? QUIZ on Ch.5 Why is it sometimes not a good idea to place the private part of the interface in a header file? Example projects where we don t want the implementation visible to the client programmer: The

More information

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. 9 Self-Test Exercises p. 11 History Note p. 12 Programming and

More information

CS 376b Computer Vision

CS 376b Computer Vision CS 376b Computer Vision 09 / 25 / 2014 Instructor: Michael Eckmann Today s Topics Questions? / Comments? Enhancing images / masks Cross correlation Convolution C++ Cross-correlation Cross-correlation involves

More information

Lecture 2, September 4

Lecture 2, September 4 Lecture 2, September 4 Intro to C/C++ Instructor: Prashant Shenoy, TA: Shashi Singh 1 Introduction C++ is an object-oriented language and is one of the most frequently used languages for development due

More information

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine

More information

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the

More information

CSCI-1200 Data Structures Spring 2016 Lecture 6 Pointers & Dynamic Memory

CSCI-1200 Data Structures Spring 2016 Lecture 6 Pointers & Dynamic Memory Announcements CSCI-1200 Data Structures Spring 2016 Lecture 6 Pointers & Dynamic Memory There will be no lecture on Tuesday, Feb. 16. Prof. Thompson s office hours are canceled for Monday, Feb. 15. Prof.

More information

ME 461 C review Session Fall 2009 S. Keres

ME 461 C review Session Fall 2009 S. Keres ME 461 C review Session Fall 2009 S. Keres DISCLAIMER: These notes are in no way intended to be a complete reference for the C programming material you will need for the class. They are intended to help

More information

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26 COSC 2P95 Procedural Abstraction Week 3 Brock University Brock University (Week 3) Procedural Abstraction 1 / 26 Procedural Abstraction We ve already discussed how to arrange complex sets of actions (e.g.

More information

UNIT-2 Introduction to C++

UNIT-2 Introduction to C++ UNIT-2 Introduction to C++ C++ CHARACTER SET Character set is asset of valid characters that a language can recognize. A character can represents any letter, digit, or any other sign. Following are some

More information

5. Control Statements

5. Control Statements 5. Control Statements This section of the course will introduce you to the major control statements in C++. These control statements are used to specify the branching in an algorithm/recipe. Control statements

More information

Pointers, Dynamic Data, and Reference Types

Pointers, Dynamic Data, and Reference Types Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation The new operator The delete operator Dynamic Memory Allocation for Arrays 1 C++ Data Types simple

More information

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University Fundamental Data Types CSE 130: Introduction to Programming in C Stony Brook University Program Organization in C The C System C consists of several parts: The C language The preprocessor The compiler

More information

Chapter 1 Getting Started

Chapter 1 Getting Started Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different

More information

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING 1. Object Oriented Programming Paradigms 2. Comparison of Programming Paradigms 3. Basic Object Oriented Programming

More information

Programming. C++ Basics

Programming. C++ Basics Programming C++ Basics Introduction to C++ C is a programming language developed in the 1970s with the UNIX operating system C programs are efficient and portable across different hardware platforms C++

More information

Data Structure Series

Data Structure Series Data Structure Series This series is actually something I started back when I was part of the Sweet.Oblivion staff, but then some things happened and I was no longer able to complete it. So now, after

More information

For example, let s say we define an array of char of size six:

For example, let s say we define an array of char of size six: Arrays in C++ An array is a consecutive group of memory locations that all have the same name and the same type. To refer to a particular location, we specify the name and then the positive index into

More information

Come and join us at WebLyceum

Come and join us at WebLyceum Come and join us at WebLyceum For Past Papers, Quiz, Assignments, GDBs, Video Lectures etc Go to http://www.weblyceum.com and click Register In Case of any Problem Contact Administrators Rana Muhammad

More information

These are notes for the third lecture; if statements and loops.

These are notes for the third lecture; if statements and loops. These are notes for the third lecture; if statements and loops. 1 Yeah, this is going to be the second slide in a lot of lectures. 2 - Dominant language for desktop application development - Most modern

More information

Heap Arrays and Linked Lists. Steven R. Bagley

Heap Arrays and Linked Lists. Steven R. Bagley Heap Arrays and Linked Lists Steven R. Bagley Recap Data is stored in variables Can be accessed by the variable name Or in an array, accessed by name and index Variables and arrays have a type Create our

More information

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018 Pointer Basics Lecture 13 COP 3014 Spring 2018 March 28, 2018 What is a Pointer? A pointer is a variable that stores a memory address. Pointers are used to store the addresses of other variables or memory

More information

Text Input and Conditionals

Text Input and Conditionals Text Input and Conditionals Text Input Many programs allow the user to enter information, like a username and password. Python makes taking input from the user seamless with a single line of code: input()

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

CSCI 171 Chapter Outlines

CSCI 171 Chapter Outlines Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures

More information

Ch. 12: Operator Overloading

Ch. 12: Operator Overloading Ch. 12: Operator Overloading Operator overloading is just syntactic sugar, i.e. another way to make a function call: shift_left(42, 3); 42

More information

CS2141 Software Development using C/C++ C++ Basics

CS2141 Software Development using C/C++ C++ Basics CS2141 Software Development using C/C++ C++ Basics Integers Basic Types Can be short, long, or just plain int C++ does not define the size of them other than short

More information

EL6483: Brief Overview of C Programming Language

EL6483: Brief Overview of C Programming Language EL6483: Brief Overview of C Programming Language EL6483 Spring 2016 EL6483 EL6483: Brief Overview of C Programming Language Spring 2016 1 / 30 Preprocessor macros, Syntax for comments Macro definitions

More information

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010 CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011 Lectures 1-22 Moaaz Siddiq Asad Ali Latest Mcqs MIDTERM EXAMINATION Spring 2010 Question No: 1 ( Marks: 1 ) - Please

More information

A brief introduction to C programming for Java programmers

A brief introduction to C programming for Java programmers A brief introduction to C programming for Java programmers Sven Gestegård Robertz September 2017 There are many similarities between Java and C. The syntax in Java is basically

More information

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files CS113: Lecture 7 Topics: The C Preprocessor I/O, Streams, Files 1 Remember the name: Pre-processor Most commonly used features: #include, #define. Think of the preprocessor as processing the file so as

More information

Have examined process Creating program Have developed program Written in C Source code

Have examined process Creating program Have developed program Written in C Source code Preprocessing, Compiling, Assembling, and Linking Introduction In this lesson will examine Architecture of C program Introduce C preprocessor and preprocessor directives How to use preprocessor s directives

More information

Topic 6: A Quick Intro To C

Topic 6: A Quick Intro To C Topic 6: A Quick Intro To C Assumption: All of you know Java. Much of C syntax is the same. Also: Many of you have used C or C++. Goal for this topic: you can write & run a simple C program basic functions

More information

Topic 6: A Quick Intro To C. Reading. "goto Considered Harmful" History

Topic 6: A Quick Intro To C. Reading. goto Considered Harmful History Topic 6: A Quick Intro To C Reading Assumption: All of you know basic Java. Much of C syntax is the same. Also: Some of you have used C or C++. Goal for this topic: you can write & run a simple C program

More information

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings 19/10/2017 CE221 Part 2 1 Variables and References 1 In Java a variable of primitive type is associated with a memory location

More information

Ch. 11: References & the Copy-Constructor. - continued -

Ch. 11: References & the Copy-Constructor. - continued - Ch. 11: References & the Copy-Constructor - continued - const references When a reference is made const, it means that the object it refers cannot be changed through that reference - it may be changed

More information

Lecture Notes on Memory Layout

Lecture Notes on Memory Layout Lecture Notes on Memory Layout 15-122: Principles of Imperative Computation Frank Pfenning André Platzer Lecture 11 1 Introduction In order to understand how programs work, we can consider the functions,

More information

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC CMSC 341 Lecture 6 Templates, Stacks & Queues Based on slides by Shawn Lupoli & Katherine Gibson at UMBC Today s Topics Data types in C++ Overloading functions Templates How to implement them Possible

More information

Chapter 2 Basic Elements of C++

Chapter 2 Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2-1 Chapter 2 Basic Elements of C++ At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion

More information

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #29 Arrays in C (Refer Slide Time: 00:08) This session will learn about arrays in C. Now, what is the word array

More information

12. Pointers Address-of operator (&)

12. Pointers Address-of operator (&) 12. Pointers In earlier chapters, variables have been explained as locations in the computer's memory which can be accessed by their identifer (their name). This way, the program does not need to care

More information

Pointers and References

Pointers and References Steven Zeil October 2, 2013 Contents 1 References 2 2 Pointers 8 21 Working with Pointers 8 211 Memory and C++ Programs 11 212 Allocating Data 15 22 Pointers Can Be Dangerous 17 3 The Secret World of Pointers

More information

The C++ Language. Arizona State University 1

The C++ Language. Arizona State University 1 The C++ Language CSE100 Principles of Programming with C++ (based off Chapter 2 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

Memory Addressing, Binary, and Hexadecimal Review

Memory Addressing, Binary, and Hexadecimal Review C++ By A EXAMPLE Memory Addressing, Binary, and Hexadecimal Review You do not have to understand the concepts in this appendix to become well-versed in C++. You can master C++, however, only if you spend

More information