cs11 – introduction to c++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf ·...

40
CS11 – Introduction to C++ Spring 2011-2012 Lecture 1

Upload: others

Post on 22-Jun-2020

9 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

CS11 – Introduction to C++

Spring 2011-2012 Lecture 1

Page 2: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

Welcome!

n  Introduction to C++ q  Assumes general familiarity with C syntax and semantics

n  Loops, functions, pointers, memory allocation, structs, etc.

n  8 Lectures (~1 hour) q  Slides posted on CS11 website q  http://courses.cms.caltech.edu/cs11

n  No textbook is required q  All necessary material covered in slides, or available online

n  7 Lab Assignments – on course website q  Usually available on Monday evenings q  Due one week later, on Monday at 12:00 noon

Page 3: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

Assignments and Grading

n  Labs focus on lecture topics q  …and lectures cover tricky points in labs q  Come to class! I give extra hints. J

n  Labs are given a score in range 0..3, and feedback q  If your code is broken, you will have to fix it. q  If your code is sloppy, you will have to clean it up.

n  Must have a total score of 18/24 to pass CS11 C++ q  (Lab 4 is a two-week lab, and is worth 6 points.) q  Can definitely pass without completing all labs

n  Please turn in assignments on time q  You will lose 0.5 points per day on late assignments

Page 4: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

Lab Submissions

n  Using csman homework submission website: q  https://csman.cs.caltech.edu q  Many useful features, such as email notifications

n  Must have a CS cluster account to submit q  csman authenticates against CS cluster account

n  CS cluster account also great for doing labs! q  Can easily do the labs on your own machine, as

long as your work builds with a recent g++ version

Page 5: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

“Tips and Tricks” Books

n  Many great books! q  Effective C++, More Effective C++

n  Scott Myers q  Exceptional C++, More Exceptional C++

n  Herb Sutter q  Exceptional C++ Style

n  Herb Sutter

n  These books teach you how to use C++ well q  Not necessary for this track q  A great investment if you expect to use C++ a lot

Page 6: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

C++ Origins

n  Original designer: Bjarne Stroustrup q  AT&T Bell Labs

n  First versions called “C with Classes” – 1979 q  Most language concepts taken from C q  Class system conceptually derived from Simula67

n  Name changed to “C++” in 1983 n  Continuous evolution of language features

q  Many enhancements to class system; operator overloads; references; const; templates; exceptions; namespaces; …

Page 7: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

C++ Philosophy

n  “Close to the problem to be solved” q  Ability to build elegant and powerful abstractions q  Strong focus on modularity q  Big enhancements to C type-system

n  “Close to the machine” q  Retains C’s focus on performance q  Also retains C’s ability to do low-level

manipulation of hardware and data

Page 8: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

Two Components of C++

n  The C++ core language q  Syntax, data-types, variables, flow-control, … q  Functions, classes, templates, …

n  The C++ Standard Library q  A collection of useful classes and functions written

in the core language q  Generic strings, streams, exceptions q  Generic containers and algorithms

n  The Standard Template Library (STL)

Page 9: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

My First C++ Program

n  Hello, World! #include <iostream> using namespace std; int main() { cout << "Hello, world!" << endl; return 0; }

n  main() function is program’s entry-point q  Every C++ program must contain exactly one main() function

Page 10: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

Make It Go.

n  Save your program in hello.cc q  Typical C++ extensions are .cc, .cpp, .cxx

n  Compile your C++ program > g++ -Wall hello.cc -o hello > hello Hello, world! >

n  We are using GNU C++ compiler, g++ q  Several other C++ compilers too, but g++ is

widely available and widely used

Page 11: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

Console IO in C++

n  C uses printf(), scanf(), etc. q  Defined in the C standard header stdio.h #include <stdio.h>

n  C++ introduces “Stream IO” q  Defined in the C++ standard header iostream #include <iostream>

n  cin – console input, from “stdin” n  cout – console output, to “stdout” n  Also cerr, which is “stderr,” for error-reporting.

Page 12: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

Stream Output

n  The << operator is overloaded for stream-output q  Compiler figures out when you mean “shift left” and when

you mean “output to stream” q  Supports all primitive types and some standard classes q  endl means “end of line” in C++

n  Example: string name = "series"; int n = 15; double sum = 35.2; cout << "name = " << name << endl << "n = " << n << endl << "sum = " << sum << endl;

Page 13: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

Stream Input

n  The >> operator is overloaded for stream-input q  Also supports primitive types and strings.

n  Example: float x, y; cout << "Enter x and y coordinates: "; cin >> x >> y;

n  Input values are whitespace-delimited. Enter x and y coordinates: 3.2 -5.6 Enter x and y coordinates: 4 35

Page 14: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

C++ Stream IO Tips

n  Don’t mix C-style IO and C++ stream IO! q  Both use the same underlying OS-resources q  Either API can leave stream in a state unexpected

by the other one n  Don’t use printf() and scanf() in C++

q  At least, not in this class q  In general, use C++ IO in C++ programs

n  Can use endl to end lines, or "\n". q  These are actually not the same in C++ q  Use endl in this class

Page 15: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

C++ Namespaces

n  Namespaces are used to group related items n  All C++ Standard Library code is in std namespace

q  string, cin, cout are part of Standard Library

n  Either write namespace::name everywhere… std::cout << "Hello, world!" << std::endl;

n  Or, declare that you are using the namespace! using namespace std; ... cout << "Hello, world!" << endl;

n  namespace::name form is called a qualified name

Page 16: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

Classes and Objects

n  Objects are a tight pairing of two things: q  State – a collection of related data values q  Behavior – code that acts on those data values in

coherent ways q  “Objects = Data + Code”

n  A class is a “blueprint” for objects q  The class defines the state and behavior of

objects of that class q  Actually defines a new type in the language

Page 17: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

C++ Terminology: Members

n  A class is made up of members n  Data members are variable associated with

the class q  They store the class’ state q  Also called “member variables” or “fields”

n  Member functions are operations the class can perform q  The set of member functions in a class specifies

its behavior q  These functions usually involve the data members

Page 18: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

Classes and Objects

n  Can have many objects of a particular class q  Each object has its own copy of data members q  Calling member functions on one object doesn’t

affect the state of other objects n  An object is an instance of a class

q  The terms “object” and “instance” are equivalent n  A class is not an object

Page 19: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

Member Function Terminology

n  Constructors initialize new instances of a class q  Can take arguments, but not required. No return value. q  Every class has at least one constructor q  No-argument constructor is called the default constructor

n  Destructors clean up an instance of a class q  This is where an instance’s resources are released q  No arguments, no return value q  Every class has exactly one destructor

n  Accessors allow internal state to be retrieved q  Provide control over when and how data is exposed

n  Mutators allow internal state to be modified q  Provide control over when and how changes can be made

Page 20: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

Simple Class-Design Example

n  Design a class to manage a computer-controlled milling machine

n  What state to maintain? q  Current milling head coords q  Current milling bit type

n  What operations to provide? q  Move to some location q  Change to another milling bit

Page 21: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

Simple Class-Design Example (2)

n  State to maintain: q  Current milling head coords q  Current milling bit type

n  Should users of class access object state directly? q  User could change state in a

way that breaks the machine! q  The class can provide general,

useful operations… q  The class itself should manage

the machine’s state (don’t leave that up to the user!)

Page 22: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

Abstraction and Encapsulation

n  Abstraction: q  Present a clean, simplified interface q  Hide unnecessary detail from users of the class

(e.g. implementation details) n  They usually don’t care about these details! n  Let them concentrate on the problem they are solving.

n  Encapsulation: q  Allow an object to protect its internal state from

external access and modification q  The object itself governs all internal state-changes

n  Methods can ensure only valid state changes

Key OOP Concepts

Page 23: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

Access Modifiers

n  The class declaration states what is exposed and what is hidden.

n  Three access-modifiers in C++ q  public – Anybody can access it q  private – Only the class itself can access it q  protected – We’ll get to this later…

n  Default access-level for classes is private. n  In general, other code can only access the

public parts of your classes.

Page 24: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

Classes – Declarations and Definitions

n  C++ makes a distinction between the declaration of a class, and its definition. q  The declaration describes member variables and

functions, and their access constraints. n  This is put in the “header” file, e.g. Point.hh

q  The definition specifies the behavior – the actual code of the member functions. n  This is put in a corresponding .cc file, e.g. Point.cc

n  Users of our class include the declarations #include "Point.hh"

Page 25: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

Point Class Declaration – Point.hh

// A 2D point class! class Point { double x_coord, y_coord; // Data-members public: Point(); // Constructors Point(double x, double y); ~Point(); // Destructor double getX(); // Accessors double getY(); void setX(double x); // Mutators void setY(double y); };

Page 26: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

Defining the Point’s Behavior – Point.cc

#include "Point.hh" // Default (aka no-argument) constructor Point::Point() { x_coord = 0; y_coord = 0; } // Two-argument constructor - sets point to (x, y) Point::Point(double x, double y) { x_coord = x; y_coord = y; } // Cleans up a Point instance. Point::~Point() { // no dynamically allocated resources, so doesn't do anything }

Page 27: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

Defining the Point’s Behavior (continued)

// Returns X-coordinate of a Point double Point::getX() { return x_coord; } // Returns Y-coordinate of a Point double Point::getY() { return y_coord; } // Sets X-coordinate of a Point void Point::setX(double x) { x_coord = x; } // Sets Y-coordinate of a Point void Point::setY(double y) { y_coord = y; }

Page 28: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

Using Our Point

n  Now we have a new type to use! #include "Point.hh" ... Point p1; // Calls default constructor Point p2(3, 5); // Calls 2-arg constructor cout << "P2 = (" << p2.getX() << "," << p2.getY() << ")" << endl; p1.setX(210); p1.setY(154);

n  Point’s guts are hidden. p1.x_coord = 452; // Compiler reports an error.

n  Don’t use parentheses with default constructor!!! Point p1(); // This declares a function!

Page 29: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

What About The Destructor?

n  In the Point class, destructor doesn’t do anything! q  Point doesn’t dynamically allocate any resources q  Compiler can clean up static resources by itself

// Cleans up a Point instance. Point::~Point() { // no dynamic resources, so doesn't do anything }

n  In this case, you could even leave the destructor out q  Compiler will generate one for you q  Always provide a destructor if your class dynamically

allocates any resources!

Page 30: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

C++ Function Arguments

n  Function arguments in C++ are passed by-value q  A copy of each argument is made q  The function works with the copy, not the original

n  Example: void outputPoint(Point p) { cout << "(" << p.getX() << "," << p.getY() << ")"; } ... Point loc(35,-117); outputPoint(loc); // loc is copied

n  Copying lots of objects gets expensive!

Page 31: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

C++ References

n  C++ introduces references q  A reference is like an alias for a variable q  Using the reference is exactly like using what it refers to

n  Updating our function: void outputPoint(Point &p) { cout << "(" << p.getX() << "," << p.getY() << ")"; } ... Point loc(35,-117); outputPoint(loc); // loc is passed "by-reference"

q  p is of type Point & - “reference to a Point object” q  Using p is identical to using loc here

Page 32: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

Characteristics of C++ References

n  The referent can be changed – just like a pointer // A simple, contrived example: int i = 5; int &j = i; // j is a reference to i j++; // i == 6 now, too

n  Much cleaner syntax than pointers! // Same contrived example, with pointers: int i = 5; int *j = &i; // j is a pointer to i (*j)++; // parentheses are necessary here

n  Can use references to primitive variables or objects q  float &f is a reference to a float primitive q  Point &p is a reference to a Point object

Page 33: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

More Characteristics of References

n  Always use object references as function arguments q  The object itself isn’t copied, so it’s much faster!

n  Conversion from variable to reference is automatic void outputPoint(Point &p) { ... } ... // No extra syntax needed to pass loc to fn. Point loc(35, -117); outputPoint(loc);

n  Don’t use references for primitive types (usually) q  Doesn’t save any time q  Best to avoid, except in very special circumstances

Page 34: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

C++ References Are Constrained

n  C++ references must refer to something. q  Nice for functions that require an object

n  Example: a function that takes a Point argument q  Modify the point in-place to rotate it by 90° q  Want the function to actually change the passed-in object

n  Pointer way: void rotate90(Point *p)

q  What if NULL is passed for p ?? q  (Actually, in C++ we use 0 instead of NULL.)

n  Reference way: void rotate90(Point &p)

q  Not possible to pass in nothing!

Page 35: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

References Allow Side-Effects

n  References are great when you want side-effects void rotate90(Point &p) { double x = p.getX(); double y = p.getY(); p.setX(y); p.setY(-x); } ... Point f(5, 2); rotate90(f);

q  f is changed by rotate90(). M If you just want efficient function calls, beware of

accidental side-effects!

Page 36: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

Pointer and Reference Syntax

n  Pointers are indicated with * in the type int *pInt; // A pointer to an integer double *pDbl = &d; // A pointer to a double

n  References are indicated with & in the type int &intRef = i; // A reference to an integer

n  The * and & symbols are reused (ugh) int *pInt = &i; // Here, & means "address-of" int j = *pInt; // Here, * means "dereference" int k = i * *pInt; // First * means "multiply" // Second * means "dereference"

n  You should avoid ugly code like this. J

Page 37: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

Pointer and Reference Syntax (2)

n  Does & or * appear in the type specification for a variable/argument declaration? q  It’s a reference variable, or it’s a pointer variable

int *pInt; void outputPoint(Point &p);

n  Does & appear in an expression? q  If it’s used as a unary operator, it’s the address-of operator

double d = 36.1; double *pDbl = &d;

n  Does * appear in an expression? q  If it’s followed by a pointer, it’s a “dereference” operation q  Otherwise it’s a multiplication operation

Page 38: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

Spacing Out

n  These are all equivalent: int *p; // Space before * int* p; // Space after * int * p; // Space before and after *

n  Same with references: Point &p; // Space before & Point& p; // Space after & Point & p; // Space before and after &

n  Best practice: space before, no space after q  Example: int* p, q; q  What is the type of q? q  q is an int, not an int* q  The * is associated with the variable, not the type-name

Page 39: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

This Week’s Homework

n  Create a simple 3D point class in C++ n  Use your class in a simple math program n  Use console IO to drive your program

n  Learn how to compile and run your program

n  Test your program to make sure it’s correct

Page 40: CS11 – Introduction to C++users.cms.caltech.edu/~donnie/cs11/cpp/lectures/cs11-cpp-lec1.pdf · Assignments and Grading ! Labs focus on lecture topics " …and lectures cover tricky

Next Time!

n  More details about classes in C++ q  (hold on to your hats…)

n  C++ dynamic memory allocation q  Destructors will quickly become very useful…

n  Assertions q  Have your code tell you when there are bugs.