Mobility Research Lab mobility.ceng.metu.edu.tr Applied Innovative Interdisciplinary (AI2) Research Lab www.ai2lab.org Short Course on Programming in C/C++

Slides:



Advertisements
Similar presentations
Lecture 9. 2 Exception  An exception is a unusual, often unpredictable event, detectable by software or hardware, that requires special processing occurring.
Advertisements

Exception Handling The purpose of exception handling is to permit the program to catch and handle errors rather than letting the error occur and suffer.
1 Chapter 17-2 Templates and Exceptions Dale/Weems.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 23 - Exception Handling Outline 23.1Introduction 23.2When Exception Handling Should Be Used 23.3Other.
Dale Roberts Exception Handling Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and Information Science,
CMSC 2021 C++ I/O and Other Topics. CMSC 2022 Using C++ Stream I/O Default input stream is called cin Default output stream is called cout Use the extraction.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0.
17 File Processing. OBJECTIVES In this chapter you will learn:  To create, read, write and update files.  Sequential file processing.  Random-access.
Basic Elements of C++ Chapter 2.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Introduction to C++ Templates and Exceptions l C++ Function Templates l C++ Class Templates l Exception and Exception Handler.
CSCI 1730 January 17 th, 2012 © by Pearson Education, Inc. All Rights Reserved.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to Classes and Objects Outline Introduction Classes, Objects, Member Functions and Data.
Dale Roberts Exception Handling Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and Information Science,
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 13 - Exception Handling Outline 13.1Introduction 13.2When Exception Handling Should Be Used.
C++ Exceptions STL Vector. Example int Quotient (int numer, int denom} { if (denom != 0) return (numer/denom); else //What to do?? }
1 CSC241: Object Oriented Programming Lecture No 27.
Chapter 13. Binary Files In binary files we do not need to format data File streams include two member functions specifically designed to input and output.
Darbas su failais Arnas Terekas IT 1gr. Vilniaus universitetas Matematikos ir informatikos fakultetas.
Working with Strings Lecture 2 Hartmut Kaiser
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 3: Requirements Specification, C++ Basics.
Operator Overloading & Exception Handling TCP1201 OOPDS 1 Lecture 5 1.
3. The Nuts and Bolts of C++ Computer Programming 3. The Nuts and Bolts of C++ 1 Learning the C++ language 3. The Nuts and Bolts of C++
Week 1 Algorithmization and Programming Languages.
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.
Programming Principles II Lecture Notes 7 Files Andreas Savva.
STL List // constructing lists #include int main () { // constructors used in the same order as described above: std::list first; // empty list of ints.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Fall 2012 Lecture 8: File I/O; Introduction to classes.
Introduction to C++ Version 1.1. Topics C++ Structure Primitive Data Types I/O Casting Strings Control Flow.
Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba.
Chapter 3 Templates Saurav Karmakar Spring Objective In Chapter 3, we will discuss: The concept of a template Function templates Class templates.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
Exceptions and Program Correctness based on the original work by Dr. Roger deBry Version 1.1.
Exception Handling Outline 23.1 Introduction
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
1 Chapter 17 Templates and Exceptions Dale/Weems.
Chapter 3 Templates. Objective In Chapter 3, we will discuss: The concept of a template Function templates Class templates vector and matrix classes Fancy.
Input/Output CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell, 2011
1 Advanced Topics in Functions Lecture Unitary Scope Resolution Operator Unary scope resolution operator ( :: )  Access global variable if.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.15Functions with Empty Parameter Lists 3.16Inline Functions 3.17References.
GE 211 Programming in C ++ Dr. Ahmed Telba Room :Ac -134
Lecture 14 Arguments, Classes and Files. Arguments.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Files To read a file – We must know its name – We must open it (for reading) – Then we can read – Then we must close it That is typically done implicitly.
File I/O in C++. Using Input/Output Files A computer file  is stored on a secondary storage device (e.g., disk);  is permanent;  can be used to provide.
C++ Namespaces, Exceptions CSci 588: Data Structures, Algorithms and Software Design All material not from online sources copyright © Travis Desell, 2011.
Exception Handling How to handle the runtime errors.
 2003 Prentice Hall, Inc. All rights reserved Basics of a Typical C++ Environment C++ systems –Program-development environment –Language –C++
EE4E. C++ Programming Lecture 6 Advanced Topics. Contents Introduction Introduction Exception handling in C++ Exception handling in C++  An object oriented.
Introduction to C++ Templates and Exceptions C++ Function Templates C++ Class Templates Exception and Exception Handler.
Ms N Nashandi Dr SH Nggada 2016/01/03Ms N Nashandi and Dr SH Nggada1 Week 6 -File input and output in C++
Basic file operations in C++ Dr. Ahmed Telba 1. 2 Learning Objectives §C++ I/O streams. §Reading and writing sequential files. §Reading and writing random.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Asif Nawaz University Institute of Information Technology, PMAS-AAUR Lecture 05: Object Oriented Programming:2014 Object-Oriented Programming in C++ Exception.
IS 0020 Program Design and Software Tools
Andy Wang Object Oriented Programming in C++ COP 3330
Introduction to C++ Systems Programming.
Why exception handling in C++?
What is a File? A file is a collection on information, usually stored on a computer’s disk. Information can be saved to files and then later reused.
Part IX Fundamentals of C and C++ Programming Exception Handling
FILE INPUT OUTPUT Skill Area 315 Part B Materials Prepared by
Andy Wang Object Oriented Programming in C++ COP 3330
Chapter 17 Templates and Exceptions Part 2
Department of Computer and Information Science, School of Science, IUPUI Exception Handling Dale Roberts, Lecturer Computer Science, IUPUI
Chapter 1 c++ structure C++ Input / Output
Lecture 9.
Presentation transcript:

Mobility Research Lab mobility.ceng.metu.edu.tr Applied Innovative Interdisciplinary (AI2) Research Lab Short Course on Programming in C/C++ Organized by Onur Pekcan Contributor Selim Temizer Instructor Hasan Yılmaz

Week 3 – Lecture1 Today We will cover; Advanced Concepts In C++  Templates  Namespaces  Exceptions  Type Casting C++ Standar Library  Input / Output with Files in C++ 2

Templates The template allows us to write routines that work for arbitrary types without having to know what these types will be. – Similar to typedef but more powerful Two types: – Function templates – Class templates 3

Function Templates A function template is not an actual function; instead it is a design (or pattern) for a function. This design is expanded (like a preprocessor macro) as needed to provide an actual routine. 4 // swap function template. // Object: must have copy constructor and operator = template void swap( Object &lhs, Object &rhs ) { Object tmp = lhs; lhs = rhs; rhs = tmp; } The swap function template

Using a template Instantiation of a template with a particular type, logically creates a new function. Only one instantiation is created for each parameter-type combination. 5 int main() {int x = 5, y = 7; double a = 2, b = 4; swap(x,y); swap(x,y); //uses the same instantiation swap(a,b); cout << x << “ “ << y << endl; cout << a << “ “ << b << endl; //swap(x, b); // Illegal: no match return 0; }

Class templates Class templates are used to define more complicated data abstractions. – e.g. it may be possible to use a class that defines several operations on a collection of integers to manipulate a collection of real numbers. 6 // Form of a template interface template class class-name { public: // list of public members... private: // private members... }; Interpretation: Class class-name is a template class with parameter T. T is a placeholder for a built- in or user-defined data type.

Implementation Each member function must be declared as a template. // Typical member implementation. template ReturnType class-name ::MemberName( Parameter List ) /* const*/ { // Member body } 7

Object declarations using template classes Form: class-name an-object; Interpretation: – Type may be any defined data type. Class-name is the name of a template class. The object an-object is created when the arguments specified between replace their corresponding parameters in the template class. 8

Example 1 // Memory cell interface template class MemoryCell { public: MemoryCell( const Object & initVal = Object() ); const Object & read( ) const; void write( const Object & x); private: Object storedValue; }; 9

Class template implementation // Implementation of class members. #include “MemoryCell.h” template MemoryCell ::MemoryCell(const Object & initVal) : storedValue( initVal){ } template const Object & MemoryCell :: read() const { return storedValue; } template void MemoryCell ::write( const Object & x ) { storedValue = x; } 10

A simple test routine int main() { MemoryCell m; m. write(5); cout << “Cell content: ” << m.read() << endl; return 0; } 11

Namespaces Namespaces allow to group entities like classes, objects and functions under a name. This way the global scope can be divided in "sub-scopes", each one with its own name. The format of namespaces is: namespace identifier { entities } 12

Namespaces Where identifier is any valid identifier and entities is the set of classes, objects and functions that are included within the namespace. For example: namespace myNamespace{ int a, b; } In order to access these variables from outside the myNamespace namespace we have to use the scope operator :: For example, to access the previous variables from outside myNamespace we can write myNamespace::a myNamespace::b 13

Example 2 The functionality of namespaces is especially useful in the case that there is a possibility that a global object or function uses the same identifier as another one, causing redefinition errors. For example: // namespaces #include using namespace std; namespace first { int var = 5; } namespace second { double var = ; } int main () { cout << first::var << endl; cout << second::var << endl; return 0; } 14

Exceptions C++ Exception Handling: try, throw, catch A function can throw an exception object if it detects an error – Object typically a character string (error message) or class object – If exception handler exists, exception caught and handled – Otherwise, program terminates 15

Exceptions Format – enclose code that may have an error in try block – follow with one or more catch blocks each catch block has an exception handler – if exception occurs and matches parameter in catch block, code in catch block executed – if no exception thrown, exception handlers skipped and control resumes after catch blocks – throw point - place where exception occurred control cannot return to throw point 16

17 1// Fig. 23.1: fig23_01.cpp 2// A simple exception handling example. 3// Checking for a divide-by-zero exception. 4#include 5 6using std::cout; 7using std::cin; 8using std::endl; 9 10// Class DivideByZeroException to be used in exception 11// handling for throwing an exception on a division by zero. 12class DivideByZeroException { 13public: 14 DivideByZeroException() 15 : message( "attempted to divide by zero" ) { } 16 const char *what() const { return message; } 17private: 18 const char *message; 19}; 20 21// Definition of function quotient. Demonstrates throwing 22// an exception when a divide-by-zero exception is encountered. 23double quotient( int numerator, int denominator ) 24{ 25 if ( denominator == 0 ) 26 throw DivideByZeroException(); return static_cast ( numerator ) / denominator; 29} EXAMPLE Class definition Function definition

CENG 213 Data Structures // Driver program 32int main() 33{ 34 int number1, number2; 35 double result; cout << "Enter two integers (end-of-file to end): "; while ( cin >> number1 >> number2 ) { // the try block wraps the code that may throw an 42 // exception and the code that should not execute 43 // if an exception occurs 44 try { 45 result = quotient( number1, number2 ); 46 cout << "The quotient is: " << result << endl; 47 } 48 catch ( DivideByZeroException ex ) { // exception handler 49 cout << "Exception occurred: " << ex.what() << '\n'; 50 } cout << "\nEnter two integers (end-of-file to end): "; 53 } cout << endl; 56 return 0; // terminate normally 57} Initialize variables Input data try and catch blocks Function call Output result

Example of a try-catch Statement try { // Statements that process personnel data and may throw // exceptions of type int, string, and SalaryError } catch ( int ) { // Statements to handle an int exception } catch ( string s ) { cout << s << endl; // Prints "Invalid customer age" // More statements to handle an age error } catch ( SalaryError ) { // Statements to handle a salary error }

Type Casting Converting an expression of a given type into another type is known as type-casting. We have already seen some ways to type cast:  Implicit Conversion  Explicit Conversion 20

Type Casting Implicit Conversion Implicit conversions do not require any operator. They are automatically performed when a value is copied to a compatible type. For example: Here, the value of a has been promoted from short to int and we have not had to specify any type-casting operator. This is known as a standard conversion 21 short a=2000; int b; b=a;

Type Casting Implicit Conversion Implicit conversions also include constructor or operator conversions, which affect classes that include specific constructors or operator functions to perform conversions. For example: Here, a implicit conversion happened between objects of class A and class B, because B has a constructor that takes an object of class A as parameter. Therefore implicit conversions from A to B are allowed. 22 class A {}; class B { public: B (A a) {} }; A a; B b=a;

Type Casting Explicit Conversion C++ is a strong-typed language. Many conversions, specially those that imply a different interpretation of the value, require an explicit conversion. Two notations for explicit type conversion: functional and c-like casting: The functionality of these explicit conversion operators is enough for most needs with fundamental data types. However, these operators can be applied indiscriminately on classes and pointers to classes, which can lead to code that while being syntactically correct can cause runtime errors. 23 short a=2000; int b; b = (int) a; // c-like cast notation b = int (a); // functional notation

Example 3 This code is syntactically correct Traditional explicit type-casting allows to convert any pointer into any other pointer type, independently of the types they point to. The subsequent call to member result will produce either a run-time error or a unexpected result // class type-casting #include using namespace std; class CDummy { float i,j; }; class CAddition { int x,y; public: CAddition (int a, int b) { x=a; y=b; } int result() { return x+y;} }; int main () { CDummy d; CAddition * padd; padd = (CAddition*) &d; cout result(); return 0; } 24

C++ Standar Library Input / Output with Files in C++ 25

I/O with Files C++ provides the following classes to perform output and input of characters to/from files  ofstream: Stream class to write on files  ifstream: Stream class to read from files  fstream: Stream class to both read and write from/to files. 26

Example 4 // basic file operations #include using namespace std; int main () { ofstream myfile; myfile.open ("example.txt"); myfile << "Writing this to a file.\n"; myfile.close(); return 0; } 27 Output: [file example.txt] Writing this to a file. This code creates a file called example.txt and inserts a sentence into it in the same way we are used to do with cout, but using the file stream myfile instead.

Opening and Closing a File open (filename, mode); ofstream myfile; myfile.open ("example.bin", ios::out | ios::app | ios::binary); if (myfile.is_open()) { /* ok, proceed with output */ } myfile.close(); 28 classdefault mode parameter ofstreamios::out ifstreamios::in fstreamios::in | ios::out

Example 5 // writing on a text file #include using namespace std; int main () { ofstream myfile ("example.txt"); if (myfile.is_open()) { myfile << "This is a line.\n"; myfile << "This is another line.\n"; myfile.close(); } else cout << "Unable to open file"; return 0; } 29 Output: [file example.txt] This is a line. This is another line.

Example 6 // reading a text file #include using namespace std; int main () { string line; ifstream myfile ("example.txt"); if (myfile.is_open()) { while ( myfile.good() ) { getline (myfile,line); cout << line << endl; } myfile.close(); } else cout << "Unable to open file"; return 0; } 30 Output: This is a line. This is another line.