Lecture 1: C++ (1)


C++ is in some ways a combination of Java and C. It has syntax and a lot of other features borrowed from C, but also supports object-oriented programming similar to Java. One interesting aspect of C++ programming is that it is (typically, for most use cases and with a few small syntax changes) backwards compatibile with C. You can, for all intents and purposes, write a program in C and use a C++ compiler to compile it. We could do that for our raytracer, but object oriented programming is incredibly useful for writing a raytracer, so we will want to make use of C++ objects.

C++ objects are similar to C structs, but they allow you to define both data and behavior, unlike C structs which only support data definitions. The behavior of a C++ object takes the form of member functions, which should be familiar to you as a Java programmer.


void swap(int *a, int *b)
    int temp = *a;
    *a = *b;
    *b = temp;

// elsewhere

int x, y;
swap(&x, &y);
void swap(int &a, int &b)
    int temp = a;
    a = b;
    b = temp;

// elsewhere

int x, y;
swap(x, y);


Check out GeomObject.h.

Syntax for declaring inheritance:

class GeomObject
    // ...

class Sphere : public GeomObject
    // ...

public implies there are other types of inheritance. It’s true, there is protected and private inheritance. They are rarely used.

Memory Allocation

If we want to create instances of our classes, there are two ways to do it. We can either create them automatically (limited to current scope, sometimes called on the stack) or allocate them dynamicallly (on the heap).

// Automatic allocation
    Vector v1;
    Vector v2 = v1;
    v1.p_x = 3.0;
} // v1 and v2 go "out of scope" here and are deallocated
// Dynamic allocation
    Sphere *sphere = new Sphere();
    Sphere *other = new Sphere();


    delete other; // 'other' is deallocated now
} // The pointers 'sphere' and 'other' go out of scope, but what they point to is not deallocated.
// The Sphere instance we created on the first line still exists, and 'scene' can still use it

Note: Virtual functions only work on pointers and references. They don’t have to be dynamically allocated, though.

Here, new and delete replace the C usage of malloc and free. There should be no mallocs or frees anywhere in your code!

Note that to allocate arrays of something (instead of just a single copy), there are special commands:

int * my_int_array = new int[10];
my_int_array[4] = 2;
delete[] my_int_array;

Example Files