CAAM 420 Fall 2012 Lecture 29. Duncan Eddy

Similar documents
Object Oriented Design

G52CPP C++ Programming Lecture 18

CSI33 Data Structures

Lecture 23: Pointer Arithmetic

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

Understanding main() function Input/Output Streams

pointers + memory double x; string a; int x; main overhead int y; main overhead

Use the dot operator to access a member of a specific object.

Object-Oriented Programming in C++

l Operators such as =, +, <, can be defined to l The function names are operator followed by the l Otherwise they are like normal member functions:

Module Operator Overloading and Type Conversion. Table of Contents

Overloading Operators in C++

C++_ MARKS 40 MIN

! Operators such as =, +, <, can be defined to. ! The function names are operator followed by the. ! Otherwise they are like normal member functions:

CSc Introduc/on to Compu/ng. Lecture 8 Edgardo Molina Fall 2011 City College of New York

G52CPP C++ Programming Lecture 18. Dr Jason Atkin

Operator overloading: extra examples

W3101: Programming Languages C++ Ramana Isukapalli

LECTURE 02 INTRODUCTION TO C++

Flow Control. CSC215 Lecture

Topics. bool and string types input/output library functions comments memory allocation templates classes

Introduction to Programming using C++

Outline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor

Operator Overloading and Templates. Linear Search. Linear Search in C++ second attempt. Linear Search in C++ first attempt

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

! Search: find a given target item in an array, ! Linear Search: Very simple search method: ! Operators such as =, +, <, and others can be

C++ Programming Fundamentals

Do not turn to the next page until the start of the exam.

CS 247: Software Engineering Principles. ADT Design

Intermediate Programming, Spring 2017*

Introduction to C++ Systems Programming

struct Buffer { Buffer(int s) { buf = new char[s]; } ~Buffer() { delete [] buf; } char *buf; };

Object Oriented Design

CSc Introduction to Computing

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

Global & Local Identifiers

Introduction to Programming

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Function Overloading

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

CS201- Introduction to Programming Current Quizzes

Integer Data Types. Data Type. Data Types. int, short int, long int

Name Section: M/W or T/TH. True or False (14 Points)

CS2141 Software Development using C/C++ C++ Basics

Intermediate Programming, Spring 2017*

CPSC 427: Object-Oriented Programming

Chapter 2: Introduction to C++

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Functions and Recursion

A brief introduction to C++

Lecture 3 ADT and C++ Classes (II)

Review: C++ Basic Concepts. Dr. Yingwu Zhu

UEE1302 (1102) F10: Introduction to Computers and Programming

CHAPTER 3 BASIC INSTRUCTION OF C++

CSC1322 Object-Oriented Programming Concepts

CSCE Practice Midterm. Data Types

This examination has 11 pages. Check that you have a complete paper.

Lab Instructor : Jean Lai

Comp151. Generic Programming: Container Classes

Pointers, Dynamic Data, and Reference Types

COMP322 - Introduction to C++ Lecture 01 - Introduction

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Suppose we find the following function in a file: int Abc::xyz(int z) { return 2 * z + 1; }

ECE 461 Fall 2011, Final Exam

Module 9. Templates & STL

Operator overloading

C++ For Science and Engineering Lecture 12

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A.

More Functions. Pass by Value. Example: Exchange two numbers. Storage Classes. Passing Parameters by Reference. Pass by value and by reference

Programming in C++: Assignment Week 8

Lecture on pointers, references, and arrays and vectors

pointers & references

Distributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes

This chapter introduces the notion of namespace. We also describe how to manage input and output with C++ commands via the terminal or files.

Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

CE221 Programming in C++ Part 1 Introduction

FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each):

5. Assuming gooddata is a Boolean variable, the following two tests are logically equivalent. if (gooddata == false) if (!

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

BITG 1113: Function (Part 2) LECTURE 5

boost::enable_if Deep Down Boostimagical Fun Christian Bay and Kasper A Andersen Department of Computer Science University of Copenhagen

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

Computer Science II Lecture 1 Introduction and Background

Financial computing with C++

Inheritance and Polymorphism

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words.

2 nd Week Lecture Notes

Recharge (int, int, int); //constructor declared void disply();

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

Reference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that

CSC 211 Intermediate Programming. Arrays & Pointers

THE STANDARD TEMPLATE LIBRARY (STL) Week 6 BITE 1513 Computer Game Programming

CS304 Object Oriented Programming Final Term

Fast Introduction to Object Oriented Programming and C++

TEMPLATE IN C++ Function Templates

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

True or False (12 Points)

The format for declaring function templates with type parameters

Transcription:

CAAM 420 Fall 2012 Lecture 29 Duncan Eddy November 7, 2012

Table of Contents 1 Templating in C++ 3 1.1 Motivation.............................................. 3 1.2 Templating Functions........................................ 3 1.3 Templating Classes.......................................... 4 2 Ternary Operators in C++ 6 2.1 Basic Syntax............................................. 6

1. Templating in C++ 1.1 Motivation A common annoyance in programming is the need to duplicate a common function structure for multiple variable types (e.g. int, float, etc.). A way of working around this is through the use of templated functions. Where the template acts as a wild card in the code until the code is compiled. When compiled, the compiler parses the templated function, and substitutes in the necessary variable type. 1.2 Templating Functions The traditional way of creating overloaded functions for multiple variable types is shown below (see Section 2 for use of ternary conditional operator): double mymax ( double a, double b){ float mymax ( float a, float b){ int mymax ( int a, int b){ With templating we can create one function that will perform all of the same functionality for all all possible variable types, including user defined types. To do this we define a templated version of the function. We first need to define the templated variables, whose type is left purposefully undefined until the code is compiled. See below for example: template < typename T > T mymax (T a, T b){ Now we will invoke this function in the same way that we are used to. // using mymax for variable type double double a = 2, b = 4; double c; c = mymax (a,b); // using mymax for variable type int int a = 4, b = 1; int c; c = myamx (a,b); As we can see, templating is a powerful tool for reducing duplication of similar functions of different variable types in code. Templating can be extended to template using programmer-defined classes instead of the standard variable typenames to template on: template < class T > T mymax (T a, T b){ To learn more about templating and its extendibility see [1]. The use of non-type parameters is worthy of note. 3

1.3 Templating Classes A more useful feature of templating is that it can be used when definite classes. By so doing it is possible to write one class definition that can be implemented for various variable types without any extra effort. Below is an example of implementing our vector class with templating: # include < iostream > using namespace std ; template < class T, int lowest_ index > class vector { public : T * data ; int length ; vector ( int L){ length = L; data = new T[ length ]; vector ( const vector & other ){ length = other. length ; data = new T[ length ]; for ( int n =1;n <= length ;++ n){ operator ()(n) = other (n); ~ vector (){ if( data ){ delete [] data ; data = NULL ; T & operator () ( int n){ // 1- indexed return data [n- lowest_ index ]; T operator () ( int n) const { // 1- indexed return data [n- lowest_ index ]; // fingers crossed friend ostream & operator << ( ostream & os, vector <T, lowest_index > v){ ; for ( int n =1;n <=v. length ;++ n){ os << v( n) << endl ; return os; 4

Use of the templated class is done in much the same way. Only that now, when construction an instance of the class, one needs to explicitly declare the class type and any non-type parameters included in the class definition: main () { vector < int, 1 > iv (10) ; iv (4) = 6; cout << " iv =" << iv << endl ; 5

2. Ternary Operators in C++ 2.1 Basic Syntax With this lecture comes the introduction of the ternary operator in C++. The ternary operator is a syntax reduction, where a logical statement is first evaluated, then depending on the evaluation one of two outputs is returned, The implementation of a function that evaluates the maximum of two arguments would be implemented as follows: double mymax ( double a, double b){ // Evaluates logical statement a > b. // If TRUE returns a // If FALSE returns b When using the ternary operator first place the logical statement to be tested between the parentheses (). Next, identify the statement as a ternary conditional statement though the use of?. Finally, supply the two returns for each logical outcome. The return if true should be place before the return if false. Both returns need to be separated by a colon. For more information on the use of the ternary operator see [2]. 6

Bibliography [1] C++ templates. http://www.cplusplus.com/doc/tutorial/templates/. [2] How to use the conditional (ternary) operator. http://www.cplusplus.com/forum/articles/14631/. 7