1 Introduction to C++ C++ basics, simple IO, and error handling

Size: px
Start display at page:

Download "1 Introduction to C++ C++ basics, simple IO, and error handling"

Transcription

1 1 Introduction to C++ C++ basics, simple IO, and error handling 1 Preview on the origins of C++ "Hello, World!" programs namespaces to avoid collisions basic textual IO: reading and printing values exception handling: reporting and handling errors standard C++ exception class hierarchy assertions: writing self-checking programs/objects invariants, preconditions, and postconditions assertions vs. exceptions 2 1

2 On origins of C++ C++ was designed to provide both object-oriented facilities for program organization object-oriented features originated from the Simula language (classes, virtuals, etc.) Stroustrup had used Simula for simulation of distributed systems (his thesis involved distributing UNIX kernel over a network of computers) C s efficiency and flexibility for systems programming Stroustrup didn t like alternatives such as Pascal: too simple and inflexible for real work 3 First version C with Classes ( ): originally implemented as a preprocessor features already include classes derived classes (i.e., subclasses) public/private access control friend classes constructors and destructors more static type checking (than C) Classes: an abstract data type facility for the C language. ACM Sigplan Notices, Jan Adding classes to the C language, Software - Practice and Experience, Feb 1983, pp

3 "Hello world!" #include <iostream> using std::cout; using std::endl; // std::cout is located here int main (int argc, char*argv [ ]) { cout << "Hello world!" << endl; return 0; // as C main // can be omitted as in C, IO operations are provided by libraries note the missing ".h" suffix in standard headers 5 Evolution of C++ from 1982 virtual functions (already in Simula, 1967) function name and operator (+, *,..) overloading references (&), in addition to old C pointers const variables and parameters user-controlled heap, via new and delete operations a version of multiple inheritance overloading of assignment and initialization ("=") pure virtual functions and abstract classes const member functions enumerations exceptions: throw, and try - catch construct templates & Standard Template Library (STL) evolution and standardization (2003) goes on.. 6 3

4 // another "Hello world" program in C++ #include <iostream> // get std::cout #include <string> // get std::string class World { // user-defined data type public: explicit World (std::string const& what) : msg_(what) { // initializer list void say () const { std::cout << msg_<< '\n'; ~World () { std::cout << "Bye!"; // destructor private: std::string msg_; // data member ; int main () { // start the program World world ("Hello!"); // local obj (variable) world.say (); World * ptrworld = new World ("How are you."); ptrworld->say (); // use dynamic object delete ptrworld; // release object 7 Notes on the "Hello!" program includes headers <.. > for text IO, std::string, etc. members may be public, protected, or private (best declared in this recommended order) data members are initialized within constructors, in a special initialization list the function member say is defined as const: declared not to modify the state of the object the write statement uses an overloaded output operator << (explained more later) the destructor (~World) cleans up (and often releases resources) before the memory space of the object is deallocated (here just prints trace) the constructor is defined explicit to disable implicit (automatic) conversions from strings to World values 8 4

5 Notes on the "Hello!" (cont.) the data member msg_ is a fixed part of an object (a field), and is automatically destructed along its owner dynamic objects are allocated on the free store or heap (with new), and must be destructed by calling the delete operation the execution starts at main - after construction of global objects (e.g., std::cout) local objects (= variables) are allocated on the call stack, and automatically destructed when exiting from the block the object world is destructed at the exit from main global objects are allocated in static memory, and automatically destructed at the end of the program - after main (e.g., the system-defined std::cout) 9 Namespaces define hierarchical scopes (not executable block) namespace Engine { // usually in a header file class Game { public:... ; // Engine access name from a namespace using the scope operator Engine::Game // in header or source file prevent name collisions between different libraries, while libraries are combined, extended, and modified correspond somewhat to Java packages namespaces can be nested (and unnamed, see later) 10 5

6 Namespaces (continued) standard libraries are placed in the namespace std #include <string> // get std::string using declaration is used to import a name into the local scope: #include <string> // get std::string using std:: string; // locally declares "string"... string name = "abcdef"; // OK without qualification #include is usually a textual inclusion (but a programming environment may use internally precompiled headers) 11 Namespaces (cont.) a using declaration is used to add a name from a namespace to a local scope to make all the names from the namespace potentially available, can specify the whole namespace with the using directive using namespace std; // directive: "imports" all however, using directive is not recommended makes maintenance harder: code is more vulnerable to changes, has fewer checks.. namespaces are open: can be extended with new declarations, within different header files namespace Engine {.. class GameEntity

7 Basic I/O three predefined ("console") streams std::cout - the standard output stream std::cin - the standard input stream std::cerr - the standard error stream (unbuffered) std::clog - the buffered error stream the insertion operator << is used for output ("put to") the extraction operator >> used for input ("get from") included via the header <iostream> these are exceptional global objects predefined by the system (created in the program's startup code) not generally recommended for C++ programs, since initializing and handling of globals can be tricky 13 Basic I/O (cont.) std::cout << "Enter value " << std::endl; // prompt int i = 0; std::cin >> i; // input an integer std::cout << "The value is "; std::cout << i << std::endl; // output the integer // or can freely chain io operations: std::out << "The value is: " << i << std::endl; double a = 0, b = 0; std::cin >> a >> b; // read two real numbers note that >> and << are overloaded operators: handle different kinds of values according to their (compiletime) types the manipulator std::endl prints a newline and flushes the buffer 14 7

8 // Read integer values until a positive value is entered. // If a non-integer value is entered, abort the program. #include <iostream> int main () { // Input with some error control int i = 0; std::cout << "Enter a positive integer" << std::endl; while (std::cin >> i) { // test for failure // input succeeds: got a number if (i > 0) // has correct sign? break; std::cout << "got non-positive value: re-enter: "; if (!std::cin) // failed for, e.g., format error std::cout << "Incorrect integer value" << std::endl; std::cout << "You entered " << i << std::endl; 15 Output operations and formatting an overloaded << operation (read: "put") formatting of output uses the format state operated on by objects called manipulators parameterized manipulators require the inclusion of the <iomanip> header file once a manipulator modifies the state of a stream, this state typically stays modified an important exception is setw: set output field width setw holds only for the next put operation after that the width sets to 0 (and uses max width) manipulators are "inserted" to the output stream // set field width (uses right justification) std::cout << std::setw (5) << i << std::endl; 16 8

9 Input operations by default, the input operator >> skips whitespace two manipulators modify this default std::skipws to skip whitespace (default) std::noskipws to not to skip whitespace char c = 0, d = 0; std::cin >> std::noskipws >> c >> d; // read chars std::cout << c << d << std::endl; // print them the header <ios> defines these manipulators but typically they are included via other iostreams headers alternatively, the operation get reads without skip std::cin.get (ch) // read a single char into ch the user can define new manipulators (see C++ texts) 17 Input operations (cont.) the stream may be either OK or in an error state if (cin >> var) // means: cin >> var; if (!cin.fail ()).. attempts to read input of the type of the variable var if fails, changes the state of the istream to an error, and returns a special value which can be tested subsequent IO is ignored (not performed).. until the error state is cleared, using cin.clear () (default zero arg means: good, i.e., clears all flags) the state of istream can be inspected by operations cin.eof () cin.fail () cin.bad () cin.good () a bad implies fail; good implies not eof and not fail the test "(cin >> var)" tests fail (and bad) flag 18 9

10 Input operations (cont.) fail () returns true if an error other than eof has occurred fail: a format error (usually can recover) bad: some fatal error (usually cannot recover) // read int values until the eof or a non-int value // then output the sum of the read values int sum = 0, i = 0; while (std::cin >> i) sum += i; // just continue until fails if (!std::cin.eof ()) { // not eof but still failed (or bad) std::cout << "Invalid int value encountered\n"; if (!std::cin.bad ()) // safe to reset failbit only std::cin.clear (); std:: cout << " sum = " << sum << std::endl; 19 How to read a string from input? read a single, whitespace terminated word #include <iostream> #include <string> int main () { std::cout << "Please enter a word:" << std::endl; std::string s; // initially empty std::cin >> s; // grows as needed std::cout << "You entered: " << s << '\n'; similarly, can read many consequent words as whitespace separated strings (in a loop) very convenient: no explicit memory management, no exception handling, no fixed-sized buffer to limit the size 20 10

11 Reading a whole line to read a whole line (and not just a single word) #include <iostream> #include <string> int main () { std::cout << "Please enter a line:" << std::endl; std::string s; std::getline (std::cin, s); // omits '\n' character std::cout << "You entered: " << s << '\n'; default line delimiter parameter: '\n' the delimiter not inserted into the string but skipped 21 Reading from a string to read values from a given string (e.g., already read input line) #include <sstream>.. std::istringstream input (" text 122 & "); std::string symbol; long int_value; char ch; // read from string stream: input >> symbol >> int_value >> ch; if (input) // if success then.. // can process values

12 File IO: writing a text file #include <iostream> #include <fstream> int main () { std::ofstream myfile ("example.txt"); if (myfile.is_open ()) { // no exception handling myfile << "This is a line." << std::endl; myfile << "This is another line." << std::endl; myfile.close (); // destructor would close else std::cout << "Unable to open file\n"; can use the same output primitives: << the destructor can automatically handle closing 23 File IO: reading a text file #include <iostream> // std::cout #include <fstream> // std::ifstream #include <string> // std::string, std::getline int main () { std::ifstream myfile ("example.txt"); if (myfile.is_open ()) { // test state std::string line; while (std::getline (myfile, line)) // not incl. \n std::cout << line << std::endl; else std::cout << "Unable to open file\n"; as usual, std::getline returns the istream status 24 12

13 Exception handling exception handling is done within try blocks, e.g.: try {.. // any C++ code catch (std::exception const& e) {.. // do local recovery if necessary throw; // rethrows the original exception e symbol& means an "alias": the parameter name is used as a synonym for the original exception object resembles a Java reference/pointer value exception handling is strongly tied to C++ destructors: while propagating an exception back along the call chain (stack), the destructors of local objects (variables) become executed 25 Exception handling (cont.) exception objects may be of any type (incl. prim. value) throw "stack underflow"; // syntax OK but peculiar recommended to use exceptions of class types throw std::out_of_range ("at operation"); // better primitive constructs (from C) do not throw exceptions: an array index that is out of bounds for a primitive (Cstyle) array will not generate any exception C++ (library) operations may throw exceptions derived from the base class std::exception, e.g., invalid index for vector::at (), generates std::out_of_range exception (but not the operator [ ]) using standard exceptions recommended for userdefined libraries and components, too 26 13

14 Example: handling an allocation failure if the runtime system cannot allocate memory for an object on the heap, then a std::bad_alloc exception is thrown try { michael = new Student (321); // one student studentarr = new Student [ ]; // huge array.. catch (std::bad_alloc const&e){.. Note. You can also define a special new-handler function to deal with the failure of new, or use the nothrow-version of new (omitted here, see e.g. Stroustrup). 27 Standard exceptions standard library defines a hierarchy of exceptions with std::exception as the root (in header <stdexcept>) exceptions are divided into two categories logic errors: precondition violations that in principle should be guaranteed before calling an operation; a failure will often mean an error in program logic (e.g., pop from an empty stack, invalid array index, etc.) run-time errors: dynamic errors that cannot really be tested or anticipated, usually numeric errors (overflow), communication line failure, etc. plus some logic/run-time language-related errors: bad_cast, bad_alloc, bad_exception.. subclasses of logic errors use self-explanatory names; e.g., std::invalid_argument exception 28 14

15 Standard exceptions (cont.) Logic and runtime exceptions are included from the header <stdexcept>. The header <exception> provides std::exception, std::bad_exception, and related functions. The header <typeinfo> provides std::bad_typeid and std::bad_cast. The header <new> provides std:bad_alloc. Not the perfect design (says Stroustrup) - but supports portability, uniform handling of exceptions, and is ready for use. 29 Standard exceptions (cont.) Exceptions are used for library and run-time errors out_of_range: invalid index for a STL container (vector) length_error: a specified structure/range too long range_error: error in numeric computation Special exceptions are used for C++ features bad_alloc: operator new fails to allocate memory bad_cast: dynamic_cast operation fails (on reference&) bad_typeid: typeid operator fails on zero pointer (0) bad_exception: violation of exception specification ios_base::failure: IO failure (only when a stream is especially configured to throw exceptions) By default, no exceptions are thrown from IO errors

16 Standard exceptions (cont.) std::exception has a special operation to report on the error (can be redefined in subclasses).. std::cerr << e.what (); // caught exception e derived exception classes have constructors, used to specify the value returned by what (): logic_error::logic_error (std::string const& msg); there is a similar arrangement for other predefined exceptions the constructor takes a std::string value as a parameter but the query operation what returns a C-style character array 31 Assertions assertions are Boolean expressions that define conditions that should never fail C++ provides (#include<cassert>) the predefined macro assert (booleanexpression); // already in standard C by default, is turned on in the test version if NDEBUG is not defined and the argument of assert () evaluates to 0, then source file and line are displayed, and the execution of the program is aborted, by calling abort () is usually turned off in the production version when macro NDEBUG is defined, assert () does nothing (it's empty) and thus "extra" checks are eliminated from the code 32 16

17 Assertions (cont.) int maxi (int x, int y, int z) { // just illustrative // returns the largest of the three given integers int max = x;.. // the rest of the implementation // just before return, check the validity of result: assert (max >= x && max >= y && max >= z); return max; document and check assumptions about program states during debugging, to expose and report bugs redundant checks can are eliminated from the production version (when NDEBUG is defined) however: exceptions are often part of specified service, and thus are not redundant 33 Preconditions and postconditions a precondition is a fact that must be true prior to the execution of some code section a precondition must hold in order for the operation to be succesfully performed it should be guaranteed by the caller of the operation if (i >= 0) // precondition to sqrt(i) d = sqrt(i); else.. a postcondition is a fact that must be true just after the execution of some section of code describes the program state after the operation has been successfully performed postconditions are the responsibility of the implementation often tested using preprocessor assertions within code 34 17

18 Class invariants a class invariant is an assertion for a class that must always hold for every object of this class defines a valid state of an object more precisely, must be true before and after any operation manipulating an object updates have intermediate states where the class assertion may (temporarily) be false a logical precondition for a method is the combination of its precondition and the class invariant however, checking preconditions and internal invariants are usually separated in practice why? (see next slide) 35 Exceptions vs. assertions (1) assertions are useful in development versions assert (isinvalidinternalstate_); // aborts if not (2) in production versions, exception handling and (potential) recovery are more acceptable than aborting if (!precondition or other external failure) throw std::runtime_error ("msg"); // reports to caller // otherwise OK: can continue.. in theory, pre- and postconditions can be used to define fully abstract responsibilities; e.g., that a stack service fulfills Last-In-First-Out - regardless of implementation black-box testing and test drivers are used to verify this kind of abstract services and responsibilities need both unit testing and internal checks 36 18

19 Exceptions vs. assertions (cont.) Differences between exceptions and assertions failed assert immediately terminates the program you can catch exceptions and try to continue you can turn off assertions (but usually not exceptions) Differences between preconditions and other assertions preconditions often tests external failures which the component cannot handle itself; instead, must throw failures back to their original source (the caller) many run-time failures (e.g., math. overflow, memory alloc.) can be seen as a kind of "external" factors, too => must use exceptions invariants and (concrete) postconditions test the internal state that cannot make sense to outsiders and indicate a bug in the component => use asserts to eliminate them 37 Summary: Why checks? Why not leave all checks out of the production version we don't know the real reason of the failure: perhaps a programming error or some external resource/factor strongly-typed languages (such as Java) use checks and exceptions to always prevent unsafe operations preconditions/external failures provide a pragmatic trade-off what to check, at the boundary of a component or module note that the C++ standard library (mostly) uses the same convention (provides precondition checks for selected operations) to really use exceptions, must additionally design classes and operations to be exception safe (i.e., to tolerate unexpected errors and their handling thru exceptions) 38 19

20 Summary C++ classes are user-defined data types namespaces prevent global name collisions IO uses overloaded put and get operations (<<, >>): safety (thru type inference) and extensibility (user types) IO doesn't use exceptions (by default) but we test the state of a stream via state flags (possibly implicitly) asserts make checks to reveal internal errors (i.e., bugs) prim. C operations don't check for errors or throw exceptions report failures from external sources (memory allocation, invalid index, numerical overflow, etc.) prefer predefined standard exceptions see online material: more samples, instructions how to compile and execute 39 20

21. Exceptions. Advanced Concepts: // exceptions #include <iostream> using namespace std;

21. Exceptions. Advanced Concepts: // exceptions #include <iostream> using namespace std; - 147 - Advanced Concepts: 21. Exceptions Exceptions provide a way to react to exceptional circumstances (like runtime errors) in our program by transferring control to special functions called handlers.

More information

void fun() C::C() // ctor try try try : member( ) catch (const E& e) { catch (const E& e) { catch (const E& e) {

void fun() C::C() // ctor try try try : member( ) catch (const E& e) { catch (const E& e) { catch (const E& e) { TDDD38 APiC++ Exception Handling 134 Exception handling provides a way to transfer control and information from a point in the execution to an exception handler a handler can be invoked by a throw expression

More information

! Errors can be dealt with at place error occurs

! Errors can be dealt with at place error occurs UCLA Stat 1D Statistical Computing and Visualization in C++ Instructor: Ivo Dinov, Asst. Prof. in Statistics / Neurology University of California, Los Angeles, Winter 200 http://www.stat.ucla.edu/~dinov/courses_students.html

More information

CS11 Advanced C++ Fall Lecture 3

CS11 Advanced C++ Fall Lecture 3 CS11 Advanced C++ Fall 2006-2007 Lecture 3 Today s Topics C++ Standard Exceptions Exception Cleanup Fun with Exceptions Exception Specifications C++ Exceptions Exceptions are nice for reporting many errors

More information

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class C++ IO C++ IO All I/O is in essence, done one character at a time For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Concept: I/O operations act on streams

More information

Chapter 15 - C++ As A "Better C"

Chapter 15 - C++ As A Better C Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference

More information

Object-Oriented Principles and Practice / C++

Object-Oriented Principles and Practice / C++ Object-Oriented Principles and Practice / C++ Alice E. Fischer June 8, 2015 OOPP / C++ Lecture 7... 1/20 Program Errors Error Handling Techniques Exceptions in C++ Exception Definition Syntax Throwing

More information

C++ Exception Handling 1

C++ Exception Handling 1 C++ Exception Handling 1 An exception is a problem that arises during the execution of a program. A C++ exception is a response to an exceptional circumstance that arises while a program is running, such

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1.... COMP6771 Advanced C++ Programming Week 5 Part One: Exception Handling 2016 www.cse.unsw.edu.au/ cs6771 2.... Memory Management & Exception Handling.1 Part I: Exception Handling Exception objects

More information

Exception Handling in C++

Exception Handling in C++ Exception Handling in C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 Introduction 2 IS 0020 Program Design and Software Tools Exception Handling Lecture 12 November 23, 200 Exceptions Indicates problem occurred in program Not common An "exception" to a program that usually

More information

Assertions and Exceptions

Assertions and Exceptions CS 247: Software Engineering Principles Assertions and Exceptions Reading: Eckel, Vol. 2 Ch. 1 Exception Handling U Waterloo CS247 (Spring 2017) p.1/32 Defensive Programming The question isn t whether

More information

Exception Handling Pearson Education, Inc. All rights reserved.

Exception Handling Pearson Education, Inc. All rights reserved. 1 16 Exception Handling 2 I never forget a face, but in your case I ll make an exception. Groucho Marx It is common sense to take a method and try it. If it fails, admit it frankly and try another. But

More information

C++ Crash Kurs. Exceptions. Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck

C++ Crash Kurs. Exceptions. Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck C++ Crash Kurs Exceptions Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck http://www.itm.uni-luebeck.de/people/pfisterer C++ Exceptions: Introduction What are exceptions Exceptions are

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

CS102 C++ Exception Handling & Namespaces

CS102 C++ Exception Handling & Namespaces CS102 C++ Exception Handling & Namespaces Bill Cheng http://merlot.usc.edu/cs102-s12 1 Topics to cover C Structs (Ch 10) C++ Classes (Ch 11) Constructors Destructors Member functions Exception Handling

More information

C++ Namespaces, Exceptions

C++ Namespaces, Exceptions C++ Namespaces, Exceptions CSci 588: Data Structures, Algorithms and Software Design http://www.cplusplus.com/doc/tutorial/namespaces/ http://www.cplusplus.com/doc/tutorial/exceptions/ http://www.cplusplus.com/doc/tutorial/typecasting/

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010 CSE 374 Programming Concepts & Tools Hal Perkins Spring 2010 Lecture 19 Introduction ti to C++ C++ C++ is an enormous language: g All of C Classes and objects (kind of like Java, some crucial differences)

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

C++ TEMPLATES. Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type.

C++ TEMPLATES. Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type. C++ TEMPLATES http://www.tutorialspoint.com/cplusplus/cpp_templates.htm Copyright tutorialspoint.com Templates are the foundation of generic programming, which involves writing code in a way that is independent

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++ CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 19 Introduction to C++ C++ C++ is an enormous language: All of C Classes and objects (kind of like Java, some crucial differences) Many

More information

A Whirlwind Tour of C++

A Whirlwind Tour of C++ Robert P. Goddard Applied Physics Laboratory University of Washington Part 1: 3 November 2000: Object Model Part 2: 17 November 2000: Templates Part 3: 15 December 2000: STL Part 4: 30 March 2001 Exceptions

More information

Introduction to C++ Systems Programming

Introduction to C++ Systems Programming Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions

More information

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University) Estd: 1994 JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli - 621014 (An approved by AICTE and Affiliated to Anna University) ISO 9001:2000 Certified Subject Code & Name : CS 1202

More information

CSE 303: Concepts and Tools for Software Development

CSE 303: Concepts and Tools for Software Development CSE 303: Concepts and Tools for Software Development Hal Perkins Autumn 2008 Lecture 24 Introduction to C++ CSE303 Autumn 2008, Lecture 24 1 C++ C++ is an enormous language: All of C Classes and objects

More information

Chapter 2. Procedural Programming

Chapter 2. Procedural Programming Chapter 2 Procedural Programming 2: Preview Basic concepts that are similar in both Java and C++, including: standard data types control structures I/O functions Dynamic memory management, and some basic

More information

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter

More information

2 ADT Programming User-defined abstract data types

2 ADT Programming User-defined abstract data types Preview 2 ADT Programming User-defined abstract data types user-defined data types in C++: classes constructors and destructors const accessor functions, and inline functions special initialization construct

More information

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT Two Mark Questions UNIT - I 1. DEFINE ENCAPSULATION. Encapsulation is the process of combining data and functions

More information

Outline. Zoltán Porkoláb: C++11/14 1

Outline. Zoltán Porkoláb: C++11/14 1 Outline Handling exceptional cases: errno, assert, longjmp Goals of exception handling Handlers and exceptions Standard exceptions Exception safe programming C++11 noexcept Exception_ptr, nested_exceptions

More information

Lecture 10. To use try, throw, and catch Constructors and destructors Standard exception hierarchy new failures

Lecture 10. To use try, throw, and catch Constructors and destructors Standard exception hierarchy new failures Lecture 10 Class string Exception Handling To use try, throw, and catch Constructors and destructors Standard exception hierarchy new failures Class template auto_ptr Lec 10 Programming in C++ 1 Class

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

Homework 4. Any questions?

Homework 4. Any questions? CSE333 SECTION 8 Homework 4 Any questions? STL Standard Template Library Has many pre-build container classes STL containers store by value, not by reference Should try to use this as much as possible

More information

CS3157: Advanced Programming. Outline

CS3157: Advanced Programming. Outline CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching

More information

Introduction to C++ (Extensions to C)

Introduction to C++ (Extensions to C) Introduction to C++ (Extensions to C) C is purely procedural, with no objects, classes or inheritance. C++ is a hybrid of C with OOP! The most significant extensions to C are: much stronger type checking.

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 22 November 28, 2016 CPSC 427, Lecture 22 1/43 Exceptions (continued) Code Reuse Linear Containers Ordered Containers Multiple Inheritance

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 19 November 7, 2018 CPSC 427, Lecture 19, November 7, 2018 1/18 Exceptions Thowing an Exception Catching an Exception CPSC 427, Lecture

More information

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

CSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington

CSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington CSE 333 Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington Administrivia New exercise posted yesterday afternoon, due Monday morning - Read a directory

More information

Welcome to Teach Yourself Acknowledgments Fundamental C++ Programming p. 2 An Introduction to C++ p. 4 A Brief History of C++ p.

Welcome to Teach Yourself Acknowledgments Fundamental C++ Programming p. 2 An Introduction to C++ p. 4 A Brief History of C++ p. Welcome to Teach Yourself p. viii Acknowledgments p. xv Fundamental C++ Programming p. 2 An Introduction to C++ p. 4 A Brief History of C++ p. 6 Standard C++: A Programming Language and a Library p. 8

More information

Introduction to C++ Introduction to C++ 1

Introduction to C++ Introduction to C++ 1 1 What Is C++? (Mostly) an extension of C to include: Classes Templates Inheritance and Multiple Inheritance Function and Operator Overloading New (and better) Standard Library References and Reference

More information

CS 376b Computer Vision

CS 376b Computer Vision CS 376b Computer Vision 09 / 25 / 2014 Instructor: Michael Eckmann Today s Topics Questions? / Comments? Enhancing images / masks Cross correlation Convolution C++ Cross-correlation Cross-correlation involves

More information

CS2141 Software Development using C/C++ Stream I/O

CS2141 Software Development using C/C++ Stream I/O CS2141 Software Development using C/C++ Stream I/O iostream Two libraries can be used for input and output: stdio and iostream The iostream library is newer and better: It is object oriented It can make

More information

Evolution of Programming Languages

Evolution of Programming Languages Evolution of Programming Languages 40's machine level raw binary 50's assembly language names for instructions and addresses very specific to each machine 60's high-level languages: Fortran, Cobol, Algol,

More information

PIC10B/1 Winter 2014 Exam I Study Guide

PIC10B/1 Winter 2014 Exam I Study Guide PIC10B/1 Winter 2014 Exam I Study Guide Suggested Study Order: 1. Lecture Notes (Lectures 1-8 inclusive) 2. Examples/Homework 3. Textbook The midterm will test 1. Your ability to read a program and understand

More information

CS

CS CS 1666 www.cs.pitt.edu/~nlf4/cs1666/ Programming in C++ First, some praise for C++ "It certainly has its good points. But by and large I think it s a bad language. It does a lot of things half well and

More information

Problem Solving with C++

Problem Solving with C++ GLOBAL EDITION Problem Solving with C++ NINTH EDITION Walter Savitch Kendrick Mock Ninth Edition PROBLEM SOLVING with C++ Problem Solving with C++, Global Edition Cover Title Copyright Contents Chapter

More information

The Foundation of C++: The C Subset An Overview of C p. 3 The Origins and History of C p. 4 C Is a Middle-Level Language p. 5 C Is a Structured

The Foundation of C++: The C Subset An Overview of C p. 3 The Origins and History of C p. 4 C Is a Middle-Level Language p. 5 C Is a Structured Introduction p. xxix The Foundation of C++: The C Subset An Overview of C p. 3 The Origins and History of C p. 4 C Is a Middle-Level Language p. 5 C Is a Structured Language p. 6 C Is a Programmer's Language

More information

05-01 Discussion Notes

05-01 Discussion Notes 05-01 Discussion Notes PIC 10B Spring 2018 1 Exceptions 1.1 Introduction Exceptions are used to signify that a function is being used incorrectly. Once an exception is thrown, it is up to the programmer

More information

CSE 333 Lecture 9 - intro to C++

CSE 333 Lecture 9 - intro to C++ CSE 333 Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington Administrivia & Agenda Main topic: Intro to C++ But first: Some hints on HW2 Labs: The

More information

Preface to the Second Edition Preface to the First Edition Brief Contents Introduction to C++ p. 1 A Review of Structures p.

Preface to the Second Edition Preface to the First Edition Brief Contents Introduction to C++ p. 1 A Review of Structures p. Preface to the Second Edition p. iii Preface to the First Edition p. vi Brief Contents p. ix Introduction to C++ p. 1 A Review of Structures p. 1 The Need for Structures p. 1 Creating a New Data Type Using

More information

Throwing exceptions 02/12/2018. Throwing objects. Exceptions

Throwing exceptions 02/12/2018. Throwing objects. Exceptions ECE 150 Fundamentals of Programming Outline 2 In this lesson, we will: See that we can throw objects Know that there are classes defined in the standard template library These classes allow more information

More information

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers. cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... today: language basics: identifiers, data types, operators, type conversions, branching and looping, program structure

More information

CE221 Programming in C++ Part 1 Introduction

CE221 Programming in C++ Part 1 Introduction CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab

More information

Introducing C++ to Java Programmers

Introducing C++ to Java Programmers Introducing C++ to Java Programmers by Kip Irvine updated 2/27/2003 1 Philosophy of C++ Bjarne Stroustrup invented C++ in the early 1980's at Bell Laboratories First called "C with classes" Design Goals:

More information

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O Outline EDAF30 Programming in C++ 2. Introduction. More on function calls and types. Sven Gestegård Robertz Computer Science, LTH 2018 1 Function calls and parameter passing 2 Pointers, arrays, and references

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1.. COMP6771 Advanced C++ Programming Week 5 Part Two: Dynamic Memory Management 2016 www.cse.unsw.edu.au/ cs6771 2.. Revisited 1 #include 2 3 struct X { 4 X() { std::cout

More information

CSC 330 Object-Oriented Programming. Exception Handling CSC 330

CSC 330 Object-Oriented Programming. Exception Handling CSC 330 Object-Oriented Programming Exception Handling 1 C++ Exception Handling Topics Exception Handling C++ Exception Handling Basics Throwing and Catching Exceptions Constructors, Destructors and Exceptions

More information

Where do we go from here?

Where do we go from here? Where do we go from here? C++ classes and objects, with all the moving parts visible operator overloading templates, STL, standards, Java components, collections, generics language and performance comparisons

More information

AN OVERVIEW OF C++ 1

AN OVERVIEW OF C++ 1 AN OVERVIEW OF C++ 1 OBJECTIVES Introduction What is object-oriented programming? Two versions of C++ C++ console I/O C++ comments Classes: A first look Some differences between C and C++ Introducing function

More information

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts Strings and Streams Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

CS11 Introduction to C++ Fall Lecture 1

CS11 Introduction to C++ Fall Lecture 1 CS11 Introduction to C++ Fall 2006-2007 Lecture 1 Welcome! 8 Lectures (~1 hour) Slides posted on CS11 website http://www.cs.caltech.edu/courses/cs11 7 Lab Assignments on course website Available on Monday

More information

CSCI 1061U Programming Workshop 2. C++ Basics

CSCI 1061U Programming Workshop 2. C++ Basics CSCI 1061U Programming Workshop 2 C++ Basics 1 Learning Objectives Introduction to C++ Origins, Object-Oriented Programming, Terms Variables, Expressions, and Assignment Statements Console Input/Output

More information

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

Interview Questions of C++

Interview Questions of C++ Interview Questions of C++ Q-1 What is the full form of OOPS? Ans: Object Oriented Programming System. Q-2 What is a class? Ans: Class is a blue print which reflects the entities attributes and actions.

More information

Convenient way to deal large quantities of data. Store data permanently (until file is deleted).

Convenient way to deal large quantities of data. Store data permanently (until file is deleted). FILE HANDLING Why to use Files: Convenient way to deal large quantities of data. Store data permanently (until file is deleted). Avoid typing data into program multiple times. Share data between programs.

More information

Streams. Ali Malik

Streams. Ali Malik Streams Ali Malik malikali@stanford.edu Game Plan Recap Purpose of Streams Output Streams Input Streams Stringstream (maybe) Announcements Recap Recap - Hello, world! #include int main() { std::cout

More information

PHY4321 Summary Notes

PHY4321 Summary Notes PHY4321 Summary Notes The next few pages contain some helpful notes that summarize some of the more useful material from the lecture notes. Be aware, though, that this is not a complete set and doesn t

More information

Vector and Free Store (Vectors and Arrays)

Vector and Free Store (Vectors and Arrays) DM560 Introduction to Programming in C++ Vector and Free Store (Vectors and Arrays) Marco Chiarandini Department of Mathematics & Computer Science University of Southern Denmark [Based on slides by Bjarne

More information

Stream States. Formatted I/O

Stream States. Formatted I/O C++ Input and Output * the standard C++ library has a collection of classes that can be used for input and output * most of these classes are based on a stream abstraction, the input or output device is

More information

CS11 Intro C++ Spring 2018 Lecture 1

CS11 Intro C++ Spring 2018 Lecture 1 CS11 Intro C++ Spring 2018 Lecture 1 Welcome to CS11 Intro C++! An introduction to the C++ programming language and tools Prerequisites: CS11 C track, or equivalent experience with a curly-brace language,

More information

CS242 COMPUTER PROGRAMMING

CS242 COMPUTER PROGRAMMING CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing

More information

C++ Input/Output: Streams

C++ Input/Output: Streams C++ Input/Output: Streams Basic I/O 1 The basic data type for I/O in C++ is the stream. C++ incorporates a complex hierarchy of stream types. The most basic stream types are the standard input/output streams:

More information

Outline. 1 About the course

Outline. 1 About the course Outline EDAF50 C++ Programming 1. Introduction 1 About the course Sven Gestegård Robertz Computer Science, LTH 2018 2 Presentation of C++ History Introduction Data types and variables 1. Introduction 2/1

More information

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

the gamedesigninitiative at cornell university Lecture 7 C++ Overview Lecture 7 Lecture 7 So You Think You Know C++ Most of you are experienced Java programmers Both in 2110 and several upper-level courses If you saw C++, was likely in a systems course Java was based on

More information

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. 9 Self-Test Exercises p. 11 History Note p. 12 Programming and

More information

VALLIAMMAI ENGINEERING COLLEGE

VALLIAMMAI ENGINEERING COLLEGE VALLIAMMAI ENGINEERING COLLEGE SRM Nagar, Kattankulathur 603 203 DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING QUESTION BANK B.E. - Electrical and Electronics Engineering IV SEMESTER CS6456 - OBJECT ORIENTED

More information

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

Cpt S 122 Data Structures. Course Review Midterm Exam # 2 Cpt S 122 Data Structures Course Review Midterm Exam # 2 Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Midterm Exam 2 When: Monday (11/05) 12:10 pm -1pm

More information

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples. Outline Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples. 1 Arrays I Array One type of data structures. Consecutive group of memory locations

More information

Lecture Material. Exceptions

Lecture Material. Exceptions Lecture Material Exceptions 1 Grouping of Exceptions Often, exceptions fall naturally into families. This implies that inheritance can be useful to structure exceptions and to help exception handling.

More information

CHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object

CHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object CHAPTER 1 Introduction to Computers and Programming 1 1.1 Why Program? 1 1.2 Computer Systems: Hardware and Software 2 1.3 Programs and Programming Languages 8 1.4 What is a Program Made of? 14 1.5 Input,

More information

Exception Safe Coding

Exception Safe Coding Exception Safe Coding Dirk Hutter hutter@compeng.uni-frankfurt.de Prof. Dr. Volker Lindenstruth FIAS Frankfurt Institute for Advanced Studies Goethe-Universität Frankfurt am Main, Germany http://compeng.uni-frankfurt.de

More information

G52CPP C++ Programming Lecture 14. Dr Jason Atkin

G52CPP C++ Programming Lecture 14. Dr Jason Atkin G52CPP C++ Programming Lecture 14 Dr Jason Atkin 1 Last Lecture Automatically created methods: A default constructor so that objects can be created without defining a constructor A copy constructor used

More information

Programmazione. Prof. Marco Bertini

Programmazione. Prof. Marco Bertini Programmazione Prof. Marco Bertini marco.bertini@unifi.it http://www.micc.unifi.it/bertini/ Hello world : a review Some differences between C and C++ Let s review some differences between C and C++ looking

More information

A <Basic> C++ Course

A <Basic> C++ Course A C++ Course 5 Constructors / destructors operator overloading Julien Deantoni adapted from Jean-Paul Rigault courses This Week A little reminder Constructor / destructor Operator overloading Programmation

More information

use static size for this buffer

use static size for this buffer Software Design (C++) 4. Templates and standard library (STL) Juha Vihavainen University of Helsinki Overview Introduction to templates (generics) std::vector again templates: specialization by code generation

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 7 September 21, 2016 CPSC 427, Lecture 7 1/21 Brackets Example (continued) Storage Management CPSC 427, Lecture 7 2/21 Brackets Example

More information

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE PART A UNIT I 1. Differentiate object oriented programming from procedure oriented programming. 2. Define abstraction and encapsulation. 3. Differentiate

More information

17.1 Handling Errors in a Program

17.1 Handling Errors in a Program Chapter 17: Exceptions From the board game MONOPOLY, the rule to follow when your man lands on the illegal square: Go to jail. Go directly to jail, do not pass GO and do not collect $200. 17.1 Handling

More information

Lecture 5 Files and Streams

Lecture 5 Files and Streams Lecture 5 Files and Streams Introduction C programs can store results & information permanently on disk using file handling functions These functions let you write either text or binary data to a file,

More information

C++_ MARKS 40 MIN

C++_ MARKS 40 MIN C++_16.9.2018 40 MARKS 40 MIN https://tinyurl.com/ya62ayzs 1) Declaration of a pointer more than once may cause A. Error B. Abort C. Trap D. Null 2Whice is not a correct variable type in C++? A. float

More information

Exception Handling Pearson Education, Inc. All rights reserved.

Exception Handling Pearson Education, Inc. All rights reserved. 1 16 Exception Handling 2 16.1 Introduction Exceptions Indicate problems that occur during a program s execution Occur infrequently Exception handling Can resolve exceptions Allow a program to continue

More information

A <Basic> C++ Course

A <Basic> C++ Course A C++ Course 5 Constructors / destructors operator overloading Julien DeAntoni adapted from Jean-Paul Rigault courses 1 2 This Week A little reminder Constructor / destructor Operator overloading

More information

Object-Oriented Programming for Scientific Computing

Object-Oriented Programming for Scientific Computing Object-Oriented Programming for Scientific Computing Error Handling and Exceptions Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de Summer

More information

UEE1302 (1102) F10: Introduction to Computers and Programming

UEE1302 (1102) F10: Introduction to Computers and Programming Computational Intelligence on Automation Lab @ NCTU Learning Objectives UEE1302 (1102) F10: Introduction to Computers and Programming Programming Lecture 00 Programming by Example Introduction to C++ Origins,

More information

Get Unique study materials from

Get Unique study materials from Downloaded from www.rejinpaul.com VALLIAMMAI ENGNIEERING COLLEGE SRM Nagar, Kattankulathur 603203. DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Year & Semester : IV Section : EEE - 1 & 2 Subject Code

More information

6 Architecture of C++ programs

6 Architecture of C++ programs 6 Architecture of C++ programs 1 Preview managing memory and other resources "resource acquisition is initialization" (RAII) using std::auto_ptr and other smart pointers safe construction of an object

More information