C++ Overview & Comparison to Java

Getting Started: Create a directory for this lab. You can either download the example programs to your directory from the Web as you go through this (go to the course web page at http://cs.roanoke.edu/Spring2009/CPSC270A to get this web page) OR just copy them all to your directory using cp as follows (assuming you are in your directory for this lab):

      cp ~cpsc/public_html/Spring2009/CPSC270A/lab1/*.java .
      cp ~cpsc/public_html/Spring2009/CPSC270A/lab1/*.cc .
    

Basic Structure

Input/Output

C++ input and output is done using objects and operators in the C++ library. For standard I/O the functions are in the iostream library files.

Compiling and Linking

Compilation in C++ results in an executable file (unlike Java where the result is bytecode which must then be interpreted). The compile command is g++. There are options that can be included: Exercise: The file hello.cc contains good ole "Hello World!" in C++. Examine the program then compile it in the two stages and create an executable named hello. Run the program.

Data Types and Basic Syntax

  • C++ uses the same identifiers for basic data types: int, float, double, long, short.

  • The syntax of basic programming constructs such as assignment statements, expressions, if statements, switch statements, and loops (for, while, and do) is the same in C++ and Java. However ...

  • Booleans in C++ are very different! In C++ zero means false and any non-zero value means true. This can get you into trouble! Consider the following:
          if (n = 0)
            ...
    
    What would happen in Java if you had this in your program? How would it be interpreted in C++?

    Exercise: See if you were correct by examining the behavior of JavaIf.java and CPlusIf.cc.

    1. Examine the code for each - same program, different languages.
    2. Compile and run the Java program (javac JavaIf.java then java JavaIf). What happened? Why?
    3. Compile the C++ program. Run it. Try different input values and see what it does. What is happening? Why is it happening?

    Constants in C++

    There are two ways to define constants in C++. As in Java, the convention is to use all caps for the constant identifiers.

    Arrays in C++

    The following declares list to be an array of 10 integers.
          const int MAX_SIZE = 10;
    
          int x[MAX_SIZE];
    
    This declaration allocates space for 10 ints. The space is allocated at compile-time and cannot be changed while the program is running. Later we will see a way to allocate space at run-time - dynamic rather than static allocation. C++ allows the programmer to be careless with array subscripts.

    Exercise: The programs JavaArrays.java and CPlusArrays.cc use arrays.

    1. Examine each program to see what it does.
    2. Compile and run JavaArrays.java. Try at least two different scenarios for input - in one have the number of elements to print be less than or equal to the number generated; in the other have the number of elements to print larger than the number generated.
    3. Compile and run CPlusArrays.cc. As above, try different combinations of input.
    4. Run the CPlusArrays.cc with 20 (or more) for the number of elements to fill and the same the number of elements to print. You may (you should but it doesn't always happen!) get a segmentation fault. A segmentation fault occurs in C++ when your program tries to access memory that has not been allocated to it.
    5. CPlusArrays2.cc is the same as the program above except it has 4 additional variables of type int declared (two before the array declaration and two after). These variables are assigned values in the program. Compile and run the program with 10 for the number of integers to generate and 20 the number to print. What do you notice? What is going on?

    Functions and Parameters

    Good programming dictates that we divide our program into logical tasks and use functions (or methods) to carry out each task. In C++, unlike Java, the compiler must have encountered the header (signature) of a function before it encounters a call to that function. When the function is in the same file as the call there are two ways to handle the requirement.

    References and Pointers

    Recall that in Java when you declare a variable to be some object type then the variable is actually a reference to the object, that is, it contains the address of the object rather than the object itself. So for example, if you have a Node class, then the declaration
        Node myNode;
    
    would declare myNode to be a reference (currently null) to a Node object. The actual object would be created using the new operator. In C++, the above declaration would create the actual Node (no new would be needed).

    To declare a reference (pointer) to an object we use *. The following declaration declares myNodePtr as a pointer to a Node:

         Node * myNodePtr;
    
    The actual node would be constructed using the new operator (details later!).

    The & operator gives the address of a variable. Some examples:

        myNodePtr = &myNode;  
    
        int * numPtr;
        int num = 5;
        cout << &num << " an address!";  //prints the address of num
    
        *numPtr = 13;   // *numPtr is the contents of the location pointed
                        // to by numPtr - * is "dereferencing" numPtr
    

    The program PointerFun.cc illustrates some of the properties of the & ("address of") operator and the * operator (when used to declare and when used to dereference a pointer variable). Study it then compile and run it.

    Parameter Passing

    The default mode of parameter passing in C++, as in Java, is pass by value. Parameters passed this way are not changed by the function (method). But in Java because the "value" of an object variable is a reference, the reference isn't changed but the object it refers to can be changed. An array in C++ is actually a pointer to the first element in the array. Thus, in the double every other element example you were able to change the actual array.

    To pass by reference in C++ your parameter must be a reference (a pointer). So, for example if you want to pass a Node object to a function so it can change the object you need to pass a pointer to the object - thus the declaration (signature) of the function would be

        returnType functionName (Node * theNode);
    
    or
    
        returnType functionName (Node *);
    
    Note: It is standard practice to just list the type of each parameter in the declaration; it isn't necessary at that point to have a formal parameter name.

    The call of the function would need to send a pointer to a Node as the actual parameter. Two examples are:

         Node * nodePtr;
         Node actualNode;
    
         ...
         ... functionName(nodePtr) ....
         ...
         ... functionName(&actualNode)
    
    The & operator gives the address of an object so &actualNode is a pointer to (or reference for) the object actualNode.

    Exercise: Write a C++ program that reads in three integers and arranges and prints them in sorted order (ascending). Your program must define and use a function swap that takes two integer parameters and swaps them (so, if a = 20 and b = 5, the call swap(a, b) will result in a = 5 and b = 20).