David Notkin Autumn 2009 CSE303 Lecture 24 "There is no reason anyone would want a computer in their home." Ken Olson, president, chairman and founder.

Slides:



Advertisements
Similar presentations
A C++ Crash Course Part II UW Association for Computing Machinery Questions & Feedback.
Advertisements

CSE 374 Programming Concepts & Tools Hal Perkins Winter 2012 Lecture 19 – Introduction to C++
David Notkin Autumn 2009 CSE303 Lecture 25. The plan 11/30 C++ intro12/2 C++ intro12/4 12/712/912/11 Final prep, evaluations 12/15 Final CSE303 Au092.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
1 Lecture-4 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
1 CSE 303 Lecture 20 Introduction to C++ slides created by Marty Stepp
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
Chapter 3: Input/Output
CS-2303 System Programming Concepts
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
CSE 332: C++ program structure and development environment C++ Program Structure (and tools) Today we’ll talk generally about C++ development (plus a few.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Elements of a C++ program 1. Review Algorithms describe how to solve a problem Structured English (pseudo-code) Programs form that can be translated into.
CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.
Working with Strings Lecture 2 Hartmut Kaiser
EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.
By Noorez Kassam Welcome to JNI. Why use JNI ? 1. You already have significantly large and tricky code written in another language and you would rather.
Programming Language C++ Xulong Peng CSC415 Programming Languages.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
1 Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables Declaring Named Constants String Concatenation.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Rossella Lau Lecture 1, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 1: Introduction What this course is about:
1 C++ Syntax and Semantics, and the Program Development Process.
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
Software Design 8.1 A Rose by any other name…C or Java? l Why do we use Java in our courses (royal we?)  Object oriented  Large collection of libraries.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 3 Formatting Output.
C ++ Basics by Bindra Shrestha sce.uhcl.edu/shresthab CSCI 3333 Data Structures.
Chapter 0 Getting Started. Objectives Understand the basic structure of a C++ program including: – Comments – Preprocessor instructions – Main function.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
Lecture 19 CIS 208 Wednesday, April 06, Welcome to C++ Basic program style and I/O Class Creation Templates.
C/C++ Basics. Basic Concepts Basic functions of each language: Input, output, math, decision, repetition Types of errors: Syntax errors, logic errors,
Topic 3: C Basics CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering University.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 16: Introduction to C++
CSC 143A 1 CSC 143 Introduction to C++ [Appendix A]
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Lecture 01a: C++ review Topics: Setting up projects, main program Memory Diagrams Variables / Types (some of) the many-types-of-const's Input / Output.
Java & C++ Comparisons How important are classes and objects?? What mechanisms exist for input and output?? Are references and pointers the same thing??
C++ Basics Programming. COMP104 Lecture 5 / Slide 2 Introduction to C++ l C is a programming language developed in the 1970s with the UNIX operating system.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
C++ Namespaces, Exceptions CSci 588: Data Structures, Algorithms and Software Design All material not from online sources copyright © Travis Desell, 2011.
CS116 SENEM KUMOVA METİN. Outline What is C++ ? Some features of C++ Input and Output Operations Manipulators C++ header files Namespaces and scope resolution.
C++ Programming Michael Griffiths Corporate Information and Computing Services The University of Sheffield
Computer Programming in C++ 黃鐘揚 教授 Prof. Chung-Yang (Ric) Huang Department of Electrical Engineering National Taiwan University 2007/06/26.
Week 13 - Friday.  What did we talk about last time?  Server communications on a socket  Function pointers.
1 ENERGY 211 / CME 211 Lecture 3 September 26, 2008.
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
Chapter 15 - C++ As A "Better C"
Lecture 2A Data Types Richard Gesick
Chapter 1.2 Introduction to C++ Programming
Chapter 13 Introduction to C++ Language
Introduction to C++ (Extensions to C)
Chapter 1.2 Introduction to C++ Programming
CS Computer Science IA: Procedural Programming
Introduction to C++ Systems Programming.
Programming Fundamentals
Working with Strings Lecture 2 Hartmut Kaiser
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
C++ Strings References: :" iomanip, sstream.
Strings, Line-by-line I/O, Functions, Call-by-Reference, Call-by-Value
Working with Strings Lecture 2 Hartmut Kaiser
Chapter 3: Input/Output
C++ Programming Basics
Programming Fundamental-1
Presentation transcript:

David Notkin Autumn 2009 CSE303 Lecture 24 "There is no reason anyone would want a computer in their home." Ken Olson, president, chairman and founder of Digital Equipment Corp., 1977 "C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do, it blows away your whole leg." Bjarne Stroustrup "Prediction is very hard. Especially about the future." Yogi Berra

The plan 11/30 C++ intro12/212/4 12/712/912/11 Final prep, evaluations 12/15 Final CSE303 Au092 Due time for HW#7? A delay for HW#6? Yes, I’ll really prep you for the final Topics you’d like to hear about?

History of C++ Bjarne Stroustrup, ATT Bell Labs,1980 A"mid-level" language, C plus OOP plus lots of new syntax –statically typed; compiled into native executables (like C) –designed to be forward-compatible (old C programs work as C++) –supports many programming styles; but difficult to master Current usage –most operating system software (Windows, Linux) is in C/C++ –most applications, games, device drivers, embedded software

Design goals of C++ Provide object-oriented features in C-based language, without compromising efficiency –backwards compatibility with C –better static type checking –data abstraction –objects and classes –prefer efficiency of compiled code where possible Important principle –if you do not use a feature, your compiled code should be as efficient as if the language did not include the feature

Difficulties in using C++ Casts –sometimes no-op, sometimes not (e.g., multiple inheritance) Lack of garbage collection Objects can be allocated on stack or heap –can be more efficient, but assignment works badly; dangling pointers Too many ways to do the same thing Multiple inheritance –efforts at efficiency lead to complicated behavior Lack of standardization between C++ compilers (improving)

Hello, world! // hello.cpp #include using namespace std; int main() { cout << "Hello, world!" << endl; return 0; }

Compiling a C++ program g++ -g -Wall -o executable source.cpp g++ -g -Wall -c source.cpp (make a.o file) program files named with.cpp, not.c –sometimes also named.cc g++ compiler, not gcc –same command-line arguments and concepts

Basic language syntax same as C: –all control statements (if/else, for, while, do), expressions, precedence, variables, braces, functions, parameters, returns, types (can use bool without including stdbool), comments (// officially allowed), preprocessor new/different: –classes and objects –inheritance (single and multiple!) –data structures (STL) –operator overloading –templates (generics) –exceptions –namespaces –reference parameters

I/O streams #include –I/O library; replaces some features of stdio.h –in C++ you can include system libraries without writing the.h stream: a source/target for reading/writing bytes in sequence. –other iostreams: fstream, stringstream, etc. variabledescription cin standard input stream cout standard output stream cerr standard error stream

Using I/O streams sends data "in the direction of the arrow" endl sends '\n' and flushes stream: –cout << "Student #" << i << endl; input with cin:(can also use getline to read entire line) int age; cout << "Type your age: "; cin >> age; commanddescription cout << expression output extraction operator; write the value of expression to standard out cin >> variable input extraction operator; read from standard input and store it in variable

Formatting: iomanip #include formatted output (a la printf) –setw(n)- set width of next field to be printed –setprecision(p)- set precision (decimal places) of next field –setfill, setbase,... –(you can still use printf if you want; often easier) cout << "You have " << setw(4) << x << " credits." << endl;

Namespaces using namespace name; namespace: An abstract container for holding a logical grouping of unique identifiers (names) in a program. –allows grouping of names, functions, classes –doesn't exist in C (all functions are global) –a bit like packages in Java; can be nested cin, cout, endl, strings, etc. are all found in namespace std –can 'use' that namespace to access those identifiers –or the :: scope resolution operator (also seen in OOP code): –std::cout << "Hello, world!" << std::endl;

Namespaces, cont'd. namespace name { } namespace integermath { int squared(int x) { return x * x; }... int main(void) { cout << integermath::squared(7); // 49 }

Functions and parameters functions can be overloaded in C++ –two functions with the same name, different parameters –compares how to polymorphism? parameters can have default values (must be the last param(s)) void printLetter(char letter, int times = 1) { for (int i = 1; i <= times; i++) { cout << letter; } cout << endl; }... printLetter('*'); // prints 1 star printLetter('!', 10); // prints 10 !s

References type& name = variable; reference: A variable that is a direct alias for another variable. –any changes made to the reference will affect the original –like pointers, but more constrained and simpler syntax –an effort to "fix" many problems with C's implementation of pointers Example: int x = 3; int& r = x; // now use r just like any int r++; // r == 4, x == 4 value on right side of = must be a variable, not an expression/cast

References vs. pointers don't use * and & to reference / dereference (just & at assignment) cannot refer directly to a reference; just refers to what it refers to a reference must be initialized at declaration –int& r; // error a reference cannot be reassigned to refer to something else int x = 3, y = 5; int& r = x; r = y; // sets x == 5, r == 5 a reference cannot be null, and can only be "invalid" if it refers to an object/memory that has gone out of scope or was freed

Reference parameters returntype name(type& name,...) {... } client passes parameter using normal syntax if function changes parameter's value, client variable will change you almost never want to return a reference –except in certain cases in OOP

const and references const: Constant, cannot be changed. –used much, much more in C++ than in C –can have many meanings (const pointer to a const int?) void printSquare(const int& i){ i = i * i; // error cout << i << endl; } int main() { int i = 5; printSquare(i); }

Strings #include C++ actually has a class for strings –much like Java strings, but mutable (can be changed) –not the same as a "literal" or a char*, but can be implicitly converted string str1 = "Hello"; // impl. conv. Concatenating and operators string str3 = str1 + str2; if (str1 == str2) { // compares characters if (str1 < str3) { // compares by ABC order char c = str3[0]; // first character

String methods string s = "Goodbye world!"; s.insert(7, " cruel"); // "Goodbye cruel world!" methoddescription append(str) append another string to end of this one c_str() return a const char* for a C++ string clear() removes all characters compare(str) like Java's compareTo find(str [, index]) rfind(str [, index]) search for index of a substring insert(index, str) add characters to this string at given index length() number of characters in string push_back(ch) adds a character to end of this string replace(index, len, str) replace given range with new text substr(start [, len]) substring from given start index

String concatenation a string can do + concatenation with a string or char*, but not with an int or other type: string s1 = "hello"; string s2 = "there"; s1 = s1 + " " + s2; // ok s1 = s1 + 42; // error to build a string out of many values, use a stringstream –works like an ostream (cout) but outputs data into a string –call.str() on stringstream once done to extract it as a string #include stringstream stream; stream << s1 << " " << s2 << 42; s1 = stream.str(); // ok

Libraries #include librarydescription cassert assertion functions for testing (assert) cctype char type functions (isalpha, tolower) cmath math functions (sqrt, abs, log, cos) cstdio standard I/O library (fopen, rename, printf) cstdlib standard functions (rand, exit, malloc) cstring char* functions (strcpy, strlen) (not the same as, the string class) ctime time functions (clock, time)

Arrays stack-allocated (same as C): type name[size]; heap-allocated: type* name = new type[size]; –C++ uses new and delete keywords to allocate/free memory –arrays are still very dumb (don't know size, etc.) int* nums = new int[10]; for (int i = 0; i < 10; i++) { nums[i] = i * i; }... delete[] nums;

malloc vs. new mallocnew place in languagea functionan operator (and a keyword) how often used in Coftennever (not in language) how often used in C++rarelyfrequently allocates memory foranythingarrays, structs, and objects returns what void* (requires cast) appropriate type (no cast) when out of memoryreturns NULL throws an exception deallocating free delete (or delete[] )

Exceptions exception: An error represented as an object or variable. –C handles errors by returning error codes –C++ can also represent errors as exceptions that are thrown / caught throwing an exception with throw: double sqrt(double n) { if (n < 0) { throw n; // kaboom }... can throw anything (a string, int, etc.) can make an exception class if you want to throw lots of info: #include

More about exceptions catching an exception with try/catch: try { double root = sqrt(x); } catch (double d) { cout << d << " can't be squirted!" << endl; } throw keyword indicates what exception(s) a method may throw –void f() throw(); // none –void f() throw(int); // may throw ints predefined exceptions (from std::exception): bad_alloc, bad_cast, ios_base::failure,...

Questions? CSE303 Au0927