CS11 Introduction to C++ Spring Lecture 1

Similar documents
The C Programming Language course syllabus associate level

An Incomplete C++ Primer. University of Wyoming MA 5310

C++ INTERVIEW QUESTIONS

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

C++ Programming Language

Sources: On the Web: Slides will be available on:

Variable Base Interface

Ch 7-1. Object-Oriented Programming and Classes

Object Oriented Software Design II

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Computer Programming C++ Classes and Objects 15 th Lecture

Chapter One Introduction to Programming

Curriculum Map. Discipline: Computer Science Course: C++

ADVANCED SCHOOL OF SYSTEMS AND DATA STUDIES (ASSDAS) PROGRAM: CTech in Computer Science

Lab 2: Swat ATM (Machine (Machine))

El Dorado Union High School District Educational Services

Basics of I/O Streams and File I/O

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

arrays C Programming Language - Arrays

CS 111 Classes I 1. Software Organization View to this point:

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Computer Programming I

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

WORKSPACE WEB DEVELOPMENT & OUTSOURCING TRAINING CENTER

C++FA 5.1 PRACTICE MID-TERM EXAM

Comp151. Definitions & Declarations

1 Abstract Data Types Information Hiding

Integrating the C++ Standard Template Library Into the Undergraduate Computer Science Curriculum

vector vec double # in # cl in ude <s ude tdexcept> tdexcept> // std::ou std t_of ::ou _range t_of class class V Vector { ector {

Copyright 2001, Bill Trudell. Permission is granted to copy for the PLoP 2001 conference. All other rights reserved.

Grundlagen der Betriebssystemprogrammierung

6.S096 Lecture 1 Introduction to C

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Software Engineering Concepts: Testing. Pointers & Dynamic Allocation. CS 311 Data Structures and Algorithms Lecture Slides Monday, September 14, 2009

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

The little endl that couldn t

RARITAN VALLEY COMMUNITY COLLEGE ACADEMIC COURSE OUTLINE. CISY 105 Foundations of Computer Science

CORBA Programming with TAOX11. The C++11 CORBA Implementation

Crash Course in Java

Course Title: Software Development

Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1

Chapter 1 Java Program Design and Development

Basics of C++ and object orientation in OpenFOAM

CMPT 183 Foundations of Computer Science I

Syllabus for CS 134 Java Programming

N3458: Simple Database Integration in C++11

Visual C Tutorial

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

Note: Syntactically, a ; is needed at the end of a struct definition.

Binary storage of graphs and related data

Illustration 1: Diagram of program function and data flow

13 Classes & Objects with Constructors/Destructors

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Chapter 2: Elements of Java

Glossary of Object Oriented Terms

Course notes Standard C++ programming

Member Functions of the istream Class

Java (12 Weeks) Introduction to Java Programming Language

AP Computer Science A - Syllabus Overview of AP Computer Science A Computer Facilities

Moving from CS 61A Scheme to CS 61B Java

Object Oriented Software Design II

ALLIED PAPER : DISCRETE MATHEMATICS (for B.Sc. Computer Technology & B.Sc. Multimedia and Web Technology)

Sequential Program Execution

ECE 122. Engineering Problem Solving with Java

The Clean programming language. Group 25, Jingui Li, Daren Tuzi

A Summary of Operator Overloading

CP Lab 2: Writing programs for simple arithmetic problems

Konzepte objektorientierter Programmierung

Lab 4: Socket Programming: netcat part

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Course Name: ADVANCE COURSE IN SOFTWARE DEVELOPMENT (Specialization:.Net Technologies)

5 Arrays and Pointers

CS 241 Data Organization Coding Standards

Building Java Programs

High-Level Language. Building a Modern Computer From First Principles.

Syllabus Introduction to C++ Programming and Numerical Analysis Spring 2016

CEC225 COURSE COMPACT

CISC 181 Project 3 Designing Classes for Bank Accounts

Java Basics: Data Types, Variables, and Loops

Introduction to Python

Lab 2 - CMPS 1043, Computer Science I Introduction to File Input/Output (I/O) Projects and Solutions (C++)

C++ Language Tutorial

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

Semantic Analysis: Types and Type Checking

How To Write Portable Programs In C

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator=

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

5 CLASSES CHAPTER. 5.1 Object-Oriented and Procedural Programming. 5.2 Classes and Objects 5.3 Sample Application: A Clock Class

CS 2112 Spring Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions

Introduction to Programming System Design. CSCI 455x (4 Units)

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

Transcription:

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

Welcome! n Introduction to C++ Assumes general familiarity with C syntax and semantics n Loops, functions, pointers, memory allocation, structs, etc. n 8 Lectures (~1 hour) Slides posted on CS11 website http://courses.cms.caltech.edu/cs11 n No textbook is required All necessary material covered in slides, or available online n 7 Lab Assignments on course website Usually available on Monday evenings Due one week later, on Monday at 12:00 noon

Assignments and Grading n Labs focus on lecture topics and lectures cover tricky points in labs Come to class! I give extra hints. J n Labs are given a score in range 0..3, and feedback If your code is broken, you will have to fix it. 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++ (Lab 4 is a two-week lab, and is worth 6 points.) Can definitely pass without completing all labs n Please turn in assignments on time You will lose 0.5 points per day on late assignments

Lab Submissions n Using csman homework submission website: https://csman.cs.caltech.edu Many useful features, such as email notifications n Must have a CS cluster account to submit csman authenticates against CS cluster account n CS cluster account also great for doing labs! Can easily do the labs on your own machine, as long as your work builds with a recent g++ version

Tips and Tricks Books n Many great books! Effective C++, More Effective C++ n Scott Myers Exceptional C++, More Exceptional C++ n Herb Sutter Exceptional C++ Style n Herb Sutter n These books teach you how to use C++ well Not necessary for this track A great investment if you expect to use C++ a lot

C++ Origins n Original designer: Bjarne Stroustrup AT&T Bell Labs n First versions called C with Classes 1979 Most language concepts taken from C Class system conceptually derived from Simula67 n Name changed to C++ in 1983 n Continuous evolution of language features Many enhancements to class system; operator overloads; references; const; templates; exceptions; namespaces;

C++ Philosophy n Close to the problem to be solved Ability to build elegant and powerful abstractions Strong focus on modularity Big enhancements to C type-system n Close to the machine Retains C s focus on performance Also retains C s ability to do low-level manipulation of hardware and data

Two Components of C++ n The C++ core language Syntax, data-types, variables, flow-control, Functions, classes, templates, n The C++ Standard Library A collection of useful classes and functions written in the core language Generic strings, streams, exceptions Generic containers and algorithms n The Standard Template Library (STL)

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 Every C++ program must contain exactly one main() function

Make It Go. n Save your program in hello.cc 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++ Several other C++ compilers too, but g++ is widely available and widely used

Console IO in C++ n C uses printf(), scanf(), etc. Defined in the C standard header stdio.h #include <stdio.h> n C++ introduces Stream IO 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.

Stream Output n The << operator is overloaded for stream-output Compiler figures out when you mean shift left and when you mean output to stream Supports all primitive types and some standard classes 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;

Stream Input n The >> operator is overloaded for stream-input 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

C++ Stream IO Tips n Don t mix C-style IO and C++ stream IO! Both use the same underlying OS-resources Either API can leave stream in a state unexpected by the other one n Don t use printf() and scanf() in C++ At least, not in this class In general, use C++ IO in C++ programs n Can use endl to end lines, or "\n". These are actually not the same in C++ Use endl in this class

C++ Namespaces n Namespaces are used to group related items n All C++ Standard Library code is in std namespace 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

Classes and Objects n Objects are a tight pairing of two things: State a collection of related data values Behavior code that acts on those data values in coherent ways Objects = Data + Code n A class is a blueprint for objects The class defines the state and behavior of objects of that class Actually defines a new type in the language

C++ Terminology: Members n A class is made up of members n Data members are variable associated with the class They store the class state Also called member variables or fields n Member functions are operations the class can perform The set of member functions in a class specifies its behavior These functions usually involve the data members

Classes and Objects n Can have many objects of a particular class Each object has its own copy of data members Calling member functions on one object doesn t affect the state of other objects n An object is an instance of a class The terms object and instance are equivalent n A class is not an object

Member Function Terminology n Constructors initialize new instances of a class Can take arguments, but not required. No return value. Every class has at least one constructor No-argument constructor is called the default constructor n Destructors clean up an instance of a class This is where an instance s resources are released No arguments, no return value Every class has exactly one destructor n Accessors allow internal state to be retrieved Provide control over when and how data is exposed n Mutators allow internal state to be modified Provide control over when and how changes can be made

Simple Class-Design Example n Design a class to manage a computer-controlled milling machine n What state to maintain? Current milling head coords Current milling bit type n What operations to provide? Move to some location Change to another milling bit

Simple Class-Design Example (2) n State to maintain: Current milling head coords Current milling bit type n Should users of class access object state directly? User could change state in a way that breaks the machine! The class can provide general, useful operations The class itself should manage the machine s state (don t leave that up to the user!)

Abstraction and Encapsulation Key OOP Concepts n Abstraction: Present a clean, simplified interface Hide unnecessary detail from users of the class (e.g. implementation details) n n They usually don t care about these details! Let them concentrate on the problem they are solving. n Encapsulation: Allow an object to protect its internal state from external access and modification The object itself governs all internal state-changes n Methods can ensure only valid state changes

Access Modifiers n The class declaration states what is exposed and what is hidden. n Three access-modifiers in C++ public Anybody can access it private Only the class itself can access it 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.

Classes Declarations and Definitions n C++ makes a distinction between the declaration of a class, and its definition. The declaration describes member variables and functions, and their access constraints. n This is put in the header file, e.g. Point.hh 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"

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); };

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 }

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; }

Using Our Point n n 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); Point s guts are hidden. p1.x_coord = 452; // Compiler reports an error. Don t use parentheses with default constructor!!! Point p1(); // This declares a function!

What About The Destructor? n In the Point class, destructor doesn t do anything! Point doesn t dynamically allocate any resources 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 Compiler will generate one for you Always provide a destructor if your class dynamically allocates any resources!

C++ Function Arguments n Function arguments in C++ are passed by-value A copy of each argument is made 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!

C++ References n C++ introduces references A reference is like an alias for a variable 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" p is of type Point & - reference to a Point object Using p is identical to using loc here

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++; // j is a reference to i // 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 float &f is a reference to a float primitive Point &p is a reference to a Point object

More Characteristics of References n Always use object references as function arguments 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) Doesn t save any time Best to avoid, except in very special circumstances

C++ References Are Constrained n C++ references must refer to something. Nice for functions that require an object n Example: a function that takes a Point argument Modify the point in-place to rotate it by 90 Want the function to actually change the passed-in object n Pointer way: void rotate90(point *p) What if NULL is passed for p?? (Actually, in C++ we use 0 instead of NULL.) n Reference way: void rotate90(point &p) Not possible to pass in nothing!

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); f is changed by rotate90(). M If you just want efficient function calls, beware of accidental side-effects!

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

Pointer and Reference Syntax (2) n Does & or * appear in the type specification for a variable/argument declaration? It s a reference variable, or it s a pointer variable int *pint; void outputpoint(point &p); n Does & appear in an expression? 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? If it s followed by a pointer, it s a dereference operation Otherwise it s a multiplication operation

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; Point& p; // Space before & // Space after & Point & p; // Space before and after & n Best practice: space before, no space after Example: int* p, q; What is the type of q? q is an int, not an int* The * is associated with the variable, not the type-name

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

Next Time! n More details about classes in C++ (hold on to your hats ) n C++ dynamic memory allocation Destructors will quickly become very useful n Assertions Have your code tell you when there are bugs.