Home CPSC 340

More C++ Programming

Classes in C++

Using classes and objects in C++ is largely similar to using them in Java, but there are some differences. Below is the declaration of a simple class representing a circle:


#include <iostream>
using namespace std;

const double PI = 3.14159265358979323846;

class Circle {
  public:
      Circle() {
          radius = 0.0;
      }

      // set the radius
      Circle(double r) {
          if(r >= 0.0) {
              radius = r;
          } else {
              radius = 0.0;
          }
      }

      void setRadius(double r) {
          if(r >= 0.0) {
              radius = r;
          } else {
              radius = 0.0;
          }
      }

      double getArea() {
          return PI * radius * radius;
      }

      double getCircumference() {
          return 2.0 * PI * radius;
      }

  private:
      double radius;
};

One big syntactical difference from Java is that C++ does not use the public or private on each variable or function. Instead, it uses public and private sections. Everything under the "public:" label is public, while everything under the "private:" label is private.

There can be multiple public and private sections, and they can appear in any order. The convention in C++ is to have one public section at the top of the class, and one private section at the bottom.

Another difference is that the class block must end in a semi-colon after the closing curly brace.

There are also few differences in creating classes:


int main() {
    Circle c1;
    Circle c2(2.5);

    // print circle info
    cout << "Circle1: Area = " << c1.getArea() << ", Circumference = "
        << c1.getCircumference() << endl;

    cout << "Circle2: Area = " << c2.getArea() << ", Circumference = "
        << c2.getCircumference() << endl;

    return 0;
}

In Java, all objects are created with "new", but that is not the case in C++, where objects can be declared the same way as regular variables. Here two Circle objects are declared, and the methods of them are called.


Parameter Passing

In Java, parameters are passed into function differently depending on whether the parameter is an object or a simple type (such as int or double). When an object is passed, a "reference" to the object is passed into the function. This means changes to that object will affect the original one passed in. When a simple type is passed, a copy is made, and no changes to the variable have an affect.

In C++, we can choose which method of passing to use for all variables. The default is "by value" and is how simple types in Java are passed. The following function takes two parameters, both passed by value:


// parameters are passed by value
void byValue(int x, Circle circle) {
    x++;
    circle.setRadius(10.0);
}

Even though this function is changing the parameters, those changes won't affect the original values that are passed in.

We can also choose to pass "by reference" so that the function can change the original object. This is done by placing an & between the type and the parameter name:


// parameters are passed by reference
void byReference(int& x, Circle& circle) {
    x++;
    circle.setRadius(10.0);
}

Now the changes made in this function will affect the original values passed in. Pass by reference passes the memory location of the parameters, while pass by value passes in a copy of the data.

The following program demonstrates this difference:


int main() {
    // declare two variables
    Circle circle(0.0);
    int x = 1;

    // print values
    cout << "Initial values: " << endl;
    cout << "x = " << x << ", Circle area = " << circle.getArea() << endl;

    // pass them to a function by value
    byValue(x, circle);

    // print values
    cout << "Initial values: " << endl;
    cout << "x = " << x << ", Circle area = " << circle.getArea() << endl;

    // pass them to a function by reference
    byReference(x, circle);

    // print values
    cout << "Initial values: " << endl;
    cout << "x = " << x << ", Circle area = " << circle.getArea() << endl;

    return 0;
}

Parameters can also be passed "by constant reference" in C++. This is like pass by reference in that no copy is made, but doesn't allow the function to change the values of the parameters being passed in.

This is done by putting the const keyword before the parameter. C++ uses const instead of final. The following function takes its parameters by constant reference:


// parameters are passed by constant reference
void byConstantReference(const int& x, const Circle& circle) {
    // cannot modify the parameters
}

In general, you should use pass by reference when the function actually needs to change parameter values. When the function doesn't need to change the parameters, you should use pass by value for simple types and small objects, and pass by constant reference for larger objects (because making a copy is inefficient).


Arrays in C++

Arrays in C++ also can be declared without using new. The syntax for declaring an array in C++ is as follows:


// an array of 100 integers
int array[100];

// an array of 200 characters
char string[200];

Like Java, C++ arrays can be accessed with the index notation, beginning at 0 and going until one less than the size of the array:


// print an element
cout << array[5];

// assign an element
array[10] = 42;

Unlike Java, there is no way to get the size of an array. Arrays are not objects and do not have a "length" property. You must keep track of the size yourself to avoid going out of bounds!

This means that the size of an array will usually have to be passed into functions taking an array as an argument. Note that the brackets are empty here. It is legal to put a size in the brackets, but it makes no effect on the program:


#include <iostream>
using namespace std;

int sum(int numbers[], int length) {
    int total = 0;
    for (int i = 0; i < length; i++) {
        total += numbers[i]; 
    }

    return total;
}

int main() {
    int array[5] = {1, 2, 3, 4, 5};
    cout << "Sum = " << sum(array, 5) << endl;

    return 0;
}

Also note that arrays are implicitly passed by reference in C++. If we change the contents of an array, then it will change the original array passed in from main.


Two-Dimensional Arrays

In declaring a 2D array, we need to give two sizes, one for the number of rows, and one for the number of columns. For example:

int array[3][5];

This would create a two-dimensional grid that would look something like this:

     
     
     

When using the array, we specify both the row and column to be used:


array[0][2] = 9;
array[2][4] = 18;
Running this code would give us:
  9  
     
    18

You can also think of a multi-dimensional array as an "array of arrays".

We can also have arrays that have even more dimensions. A three-dimensional array can be declared as:


int array[10][10][10];

This will create a three dimensional array containing 1,000 integers.

Arrays of more than two dimensions are not very commonly done, but there is no limit to the number of dimensions you could create.

Passing multi-dimensional arrays to functions works a little differently than single-dimension ones. This is because the compiler has to know how big each row is in order to use the array. For this reason, the first pair of brackets can be empty, but every other one must be given a size:


// OK
void function(int array[][100])

// Also OK
void function(int array[100][100])

// Not OK
void function(int array[][])

Program Parameters

Oftentimes we want to pass a parameter to our program. This is commonly done with file names, we would rarely want to hard code file names into a program.

To do this, we give the main function two parameters:


int main(int argc, char* argv []) {

}

The first is the number of program parameters, and the second is an array of strings giving the parameters.

Then when we run the program on the command line, any text we include after the program name is passed in (including the program name itself). For example, if we run:


a.out have some arguments

Then argc will equal 4, and argv will be the array:


["a.out", "have", "some", "arguments"]

This program demonstrates this.

This is also used in GUI systems. If you double click a file, the OS will pass the name of that file to whichever program is associated with it.

Copyright © 2018 Ian Finlayson | Licensed under a Creative Commons Attribution 4.0 International License.