Lecture notes for CS 503, Advanced Programming I

Advanced Programming I Lecture Notes

19 January 2006 • C++ Review


Outline

Basic Things You Should Know

Basic C++ Data Types

the c++ type family tree

Integer Types

Integer Size

Controlling Integer Size

Integer Sign

Integer Ranges

Range Asymmetry

Integer Overflow

Why Bother?

Floating-Point Data

Two Points about Floating Point

  1. A floating-point value is like a dirt pile: the more you handle it, the smaller it gets and the messier everything else becomes.

  2. Never compare floating-point values directly
    if (x == y) { /* whatever */ }
    
    Always compare the difference between floating-point values to some epsilon.
    if (fabs(x-y) < epsilon) {/* whatever */}
    
    Picking the right epsilon can be tricky.

Character Types

The Boolean Type

Boolean Operators

Ahh, Pointers

Pointer Operations

Pointer Dereferencing

Pointer Assignment

Pointer Comparison

Pointer Arithmetic

Pointer Subtraction

Dynamic Storage

Dynamically-Allocated Storage

Freeing Dynamic Storage

Freeing Rules

Arrays

Array Operations

Array Size

Arrays and Pointers

Multidimensional Arrays

Classes and Pointers

Garbage is Born

Class Destructor

Unintentional Sharing

Unintentional Sharing Example

Class Instance Copying

The Copy Constructor

Copy Constructor Example

Class Instance Assignment

Instance Assignment Example

struct C {
  data * p;
  C() : p(new data) { }
  C(const C & c) 
    : p(data_clone(c.p)) {}
 ~C() { delete p; }
  };

static void t(C & c) { C c2; c2 = c; }

Instance Assignment Problems

The Assignment Operator

Assignment Operator Example

struct C {
  data * data_ptr;
  C() : data_ptr(new data) { }
  C(const C & c) : data_ptr(data_clone(c.data_ptr)) {}
 ~C() { delete data_ptr; }

  // Bad example.
  C & operator = (const C & c) {
    delete data_ptr;
    data_ptr = data_clone(c.data_ptr);
    return *this;
    }
  };

Refining Assignment

The Self-Assignment Problem

Self-Assignment Example

C & C::operator = (const C & rhs) {
  delete data_ptr;
  data_ptr = copy_data(rhs.data_ptr);
  return *this;
  }

Detecting Self-Assignment

Assignments as Expressions

Assignment Expressions

Assignment Return

Assignment and Copying

Assignment vs. Copying

The Rule of Three

Points to Remember

Bibliography


This page last modified on 25 July 2006.

This work is covered by a
Creative Commons License.