7 TEMPLATES AND STL. 7.1 Function Templates

Size: px
Start display at page:

Download "7 TEMPLATES AND STL. 7.1 Function Templates"

Transcription

1 7 templates and STL:: Function Templates 7 TEMPLATES AND STL 7.1 Function Templates Support generic programming functions have parameterized types (can have other parameters as well) functions are instantiated by implicit instantiation (first function call of a given type) explicit instantiation (before function call) explicit specialization (overloading the template) Use function templates for similar functions, differing only by type information the same operator has to be defined for all types template <typename whatever> // can have more types type name(arguments including whatever type) { // code includes operations on whatever type // make sure operators used are overloaded for all potential types // for whatever type } older C++ used class in place of typename template <typename whatever> has to appear both in prototype and definition Example 7.1 swap function template (will work for all types for which assignment works). template <typename Any> void swap(any &a, Any &b) { Any t; t=a; a=b; b=t; } // in a program int x,y,z,w; swap(x,y); swap(z,w); double f,g; swap(f,g); // instantiate swap(int,int) and call it // no instantiation, just call it // instantiate swap(double,double) and call it cs2260@umsl 2005 Cezary Z. Janikow Page 81

2 7 templates and STL:: Function Templates Exercise 7.1 Function template with implicit (function calls) instantiations. Example 7.2 Template function for isbigger() returning 1 if the first arg is bigger, etc. template <typename Any> int isbigger(any &a, Any &b) { if (a>b) return 1; else if (a<b) return -1; else return 0; } // will only work for types for which < and > are overloaded Example 7.3 Function template implicit instantiations for Example 7.2. int x; x=isbigger(3,2); x=isbigger(5,8); x=isbigger(3.4,5.6); x=isbigger( hello, what? ); x=isbigger(john,adam); x=isbigger(3,2+2); // implicit instantiation // no instantiation // implicit instantiation // bump? // bump? assume Person adam, john; // bump? on function call, the compiler will look for exactly matching function look for matching template look for function that has best match with conversion Function templates can be overloaded same principles as for overloading ordinary functions Exercise 7.2 Two overloaded templates. explicitly instantiated Example 7.4 Implicit and explicit instantiation. // template for isbigger as before int i,x,y; i=isbigger(x,y); // implicit instiation for int template isbigger<char>(char,char); // explicit instantiation for char cs2260@umsl 2005 Cezary Z. Janikow Page 82

3 7 templates and STL:: Function Templates explicitly specialized explicit functions override function templates used if there are special cases for the overloaded functions ways to accomplish evolved over time Example 7.5 New style for explicit specialization. template <class Any> void isbigger(any &a, Any &b); // template template <> void isbigger<int>(int &a, int &b); // explicit specialization will override Avoid confusing explicit instantiation and explicit specialization Example 7.6 template <class Any> void swap(any &a, Any &b); template swap<int>(int&, int&); template <> swap<int>(int&, int&); template <> swap(int&, int&); // template // explicit instantiation // explicit specialization // equivalent form Exercise 7.3 Explicit template specializations. Exercise 7.4 Write a program with a template allowing computing the sum of either up to 3 integers or up to 3 floats (use only one template, with default arguments). For example, the program should handle calls such as cout << sum(2); cout << sum(2,3,4); cout << sum(2.3,4.5); Exercise 7.5 Write a function selecting the minimal entry in an array. Use a template, to be instantiated with a given type (only for type for which < is defined, such as numeric types). Test it in a program with an array of 5 integers, and then an array of 3 floats. cs2260@umsl 2005 Cezary Z. Janikow Page 83

4 7 templates and STL:: Class Templates 7.2 Class Templates Similar principles as for function templates template for a class is defined template can be implicitly or explicitly instantiated, specialized unfortunately implementation must be declared each method must be implemented as a template function template methods must be in the same header file for most linkers to properly instantiate the template inline methods are implicitly templates outside defined methods must be templates with class name with <types> Example 7.7 Class template notation. classname T attrs methods Example 7.8 Stack template (all in the header file). template <typename Any> class Stack { private: Any array[10]; int top; public: Stack(void) {top=-1;} Stack(int); // the rest of the class }; // array for 10 Any elements // implictly a template template <typename Any> Stack<Any>::Stack(int) { // whatever } // explicit template cs2260@umsl 2005 Cezary Z. Janikow Page 84

5 7 templates and STL:: Class Templates // later in an application program Stack<int> stint; // implicit instantiation of new class // and create object = stack of 10 int Stack<int> stint2; // no class instantiation, new object Stack<Person> stperson; // implicit instantiation of new class Example 7.9 Illustration for Example 7.8. T int classname Stack Stack Person attrs methods attrs methods attrs methods int int Person stint:stack stint2:stack stperson:stack Exercise 7.6 Program with a Stack of String (String from Exercise 6.5) Function-style Parameters Additional function-style arguments can be passed to instantiations and/or creation Example 7.10 Stack with an extra argument being the allocated size. template <typename Any, int n> class Stack { private: Any array[n]; // n is compilation template argument int size; // not a runtime argument // more }; template <typename Any, int n> Stack<Any,n>::Stack(void) { size=n; } // other members the same way cs2260@umsl 2005 Cezary Z. Janikow Page 85

6 7 templates and STL:: Class Templates // later in an application program Stack<int,12> stint; // implicit instantiation of new class // and new object Stack<int,5> stint2; // implicit instantiation of different // new class and new object Stack<Person,3> stperson; // implicit instantiation of new class // and new object More Generic Types Template may have more than one generic type Example 7.11 A template for a class Pair of generic elements. template <typename T1, typename T2> class Pair { private: T1 first; T2 second; // etc }; template <typename T1, typename T2> Pair<T1,T2> :: Pair(T1 x, T2 y) { first=x; second=y; } // other template methods // later in a program Pair<int,double> p1(3,3.14); Pair<int,double> p2(0,1); Pair<int,int> p3(0,0); // new class instantiated // not a new class // new class instantiated syntax and reason for explicit instantiation and specialization are the same as for function templates Exercise 7.7 Based on Example 7.11, create a program to operate on pairs of string and integer. Create an array of a few, initialized with constructors. Then, display. Use a template for Pair, instantiated for the desired pair. Use NTS strings. cs2260@umsl 2005 Cezary Z. Janikow Page 86

7 7 templates and STL:: Class Templates friends to Templates friend can be non-template class, member, or top-level function declaration as before Example 7.12 Non-template class functions/methods as friends to template class. void f(); class A { void fa(); }; template <typename T> class B { friend class A; // class A must be at least declared class A; friend void f(); friend void A::fA(); // class A must be defined }; friend can be to a template calls or function/method specifically instantiated at the same time for the same type (utility for my specific instantiation) so called bound friend all class/function/method names listed as friends must be followed with <types> needed for top-level operators << and >> overloaded to the template (because these must be templates now instantiated as needed) care must be taken to properly declare and define the elements see Exercise 7.8 for illustration Exercise 7.8 Stack template.(from the book, see all changes which either fix errors or improve standards). cs2260@umsl 2005 Cezary Z. Janikow Page 87

8 7 templates and STL:: STL 7.3 STL Library of templates and algorithms with three basic components Containers - collection storing and retrieval Algorithms - operations on containers Iterators - means of accessing elements of containers 7.4 Containers Intro Templates classes for storing collection of elements, with storing and retrieval capabilities Three kinds Sequence containers similar to arrays vector, deque, list Associate containers provide access by key set, multiset, map, multimap Adapters adapt interface stack, queue, priority_queue To use #include <container> instantiate container<type> Sizes are dynamically updated as needed Example 7.13 Container. #include <vector>... vector<person> vp; // vp is a vector of Person, like an array vp[0]=john; cs2260@umsl 2005 Cezary Z. Janikow Page 88

9 7 templates and STL:: Iterators 7.5 Iterators General method of accessing elements of sequential and associative containers Sequential and associative containers provide methods begin() and rbegin() end() and rend() all return iterator or const iterator as appropriate const iterator must be used to access const container and it may only be used to read-only Iterators can be used to specify a container (or subcontainer) [iterator,iterator) Example 7.14 Iterators and containers. rend() begin() rbegin() end() Container Similar to pointers in use and meaning iterator++ advances over the container arithmetics work for vector and deque *iterator gives container data pointed by the iterator Containers provide type for variable iterators container<type>::iterator container<type>::const_iterator container<type>::reverse_iterator container<type>::const_reverse_iterator Exercise 7.9 A vector of 3 characters, read in and then printed in reverse. cs2260@umsl 2005 Cezary Z. Janikow Page 89

10 7 templates and STL:: Some Sequence Container Operations 7.6 Some Sequence Container Operations Insertions container.push_back(element); appends at the end container.insert(iter, element) inserts element in front of iter position container.insert(iter,iter2,iter3) inserts the ranger [iter2,iter3) in front of iter position Deletions container.clear() erases all elements container.pop_back() erases the last element container.clear(iter1,iter2) erases [iter1,iter2) Assignment, swap(), size() methods are defined Searching find(iter1,iter2,element) returns iterator pointing to element in [iter1,iter2) or end() if not found Example 7.15 Basic sequence container operations. vector<int> vi; vector<int>:: iter; vi.push_back(1); vi.push_back(3); vi.push_back(4); iter=vi.begin()+1; vi.insert(vi.begin()+1,2); vector<int> vi2; vi2=vi; vi.pop_back(); vi.swap(vi2); Exercise 7.10 Example program with the list container Cezary Z. Janikow Page 90

11 7 templates and STL:: Association Containers 7.7 Association Containers set, multiset, map, multiset multi versions support multiple occurences set/multiset support insert() and find() as before map/multimap support insert and [] Example 7.16 Illustration of map. #include <map>... map<string,person> msp; Person john, susan; msp[ John ]=john; msp[ Susan ]=susan; 7.8 Adapters Built on top of sequential containers Adapt the interface to behave differently stack, queue, priority_queue (according to operator<) support standard methods for each adaptation stack supports push(), pop(), top() (non-destructive), empty() (boolean), size() queue/priority_queue supports empty() (bolean), size(), pop() (void, removes front), front() (returns but not removes front), back() (same on back), push() 2005 Cezary Z. Janikow Page 91

12 7 templates and STL:: Algorithms 7.9 Algorithms #include <algorithm> Apply to STL containers Implemented as template functions (not methods) Use iterators Sample algorithms: generate(iter1,iter2,function) initialize containter between [iter1,iter2) using function() which returns container type sort(iter1,iter2,comp) sort containter between [iter1,iter2) using comp() which returns integer indicating how two elements of the container compare if comp is missing then order using operator< on the container type for_each(iter1,iter2,function) apply function(), taking container element as an argument, between [iter1,iter2) replace_if(iter1,iter2,testfunction,element) replaces elements between [iter1,iter2) if testfunction() on the element returns true nth_element(iter1,iter2,iter3) reorders the container between [iter1,iter3) so that all elements smaller than *iter2 are placed before *iter2, and all greater are placed after random_shuffle(iter1,iter2) randomize positions of elements between [iter1,iter2) copy(iter1,iter2,iter3) copies [iter1,iter2) into container starting at iter Array as Container The standard array can be treated to all operations that vector can, including algorithms, using pointers as iterators 2005 Cezary Z. Janikow Page 92

Chapter 5. The Standard Template Library.

Chapter 5. The Standard Template Library. Object-oriented programming B, Lecture 11e. 1 Chapter 5. The Standard Template Library. 5.1. Overview of main STL components. The Standard Template Library (STL) has been developed by Alexander Stepanov,

More information

COEN244: Class & function templates

COEN244: Class & function templates COEN244: Class & function templates Aishy Amer Electrical & Computer Engineering Templates Function Templates Class Templates Outline Templates and inheritance Introduction to C++ Standard Template Library

More information

SFU CMPT Topic: Class Templates

SFU CMPT Topic: Class Templates SFU CMPT-212 2008-1 1 Topic: Class Templates SFU CMPT-212 2008-1 Topic: Class Templates Ján Maňuch E-mail: jmanuch@sfu.ca Monday 3 rd March, 2008 SFU CMPT-212 2008-1 2 Topic: Class Templates Class templates

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

by Pearson Education, Inc. All Rights Reserved. 2

by Pearson Education, Inc. All Rights Reserved. 2 An important part of every container is the type of iterator it supports. This determines which algorithms can be applied to the container. A vector supports random-access iterators i.e., all iterator

More information

Templates and Vectors

Templates and Vectors Templates and Vectors 1 Generic Programming function templates class templates 2 the STL vector class a vector of strings enumerating elements with an iterator inserting and erasing 3 Writing our own vector

More information

Function Templates. Consider the following function:

Function Templates. Consider the following function: Function Templates Consider the following function: void swap (int& a, int& b) { int tmp = a; a = b; b = tmp; Swapping integers. This function let's you swap the contents of two integer variables. But

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor. 3.Constructors and Destructors Develop cpp program to implement constructor and destructor. Constructors A constructor is a special member function whose task is to initialize the objects of its class.

More information

CS197c: Programming in C++

CS197c: Programming in C++ CS197c: Programming in C++ Lecture 2 Marc Cartright http://ciir.cs.umass.edu/~irmarc/cs197c/index.html Administration HW1 will be up this afternoon Written assignment Due in class next week See website

More information

Purpose of Review. Review some basic C++ Familiarize us with Weiss s style Introduce specific constructs useful for implementing data structures

Purpose of Review. Review some basic C++ Familiarize us with Weiss s style Introduce specific constructs useful for implementing data structures C++ Review 1 Purpose of Review Review some basic C++ Familiarize us with Weiss s style Introduce specific constructs useful for implementing data structures 2 Class The Class defines the data structure

More information

Outline. Variables Automatic type inference. Generic programming. Generic programming. Templates Template compilation

Outline. Variables Automatic type inference. Generic programming. Generic programming. Templates Template compilation Outline EDAF30 Programming in C++ 4. The standard library. Algorithms and containers. Sven Gestegård Robertz Computer Science, LTH 2018 1 Type inference 2 3 The standard library Algorithms Containers Sequences

More information

Unit 1: Preliminaries Part 4: Introduction to the Standard Template Library

Unit 1: Preliminaries Part 4: Introduction to the Standard Template Library Unit 1: Preliminaries Part 4: Introduction to the Standard Template Library Engineering 4892: Data Structures Faculty of Engineering & Applied Science Memorial University of Newfoundland May 6, 2010 ENGI

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

Polymorphism. Programming in C++ A problem of reuse. Swapping arguments. Session 4 - Genericity, Containers. Code that works for many types.

Polymorphism. Programming in C++ A problem of reuse. Swapping arguments. Session 4 - Genericity, Containers. Code that works for many types. Session 4 - Genericity, Containers Polymorphism Code that works for many types. Dr Christos Kloukinas City, UoL http://staff.city.ac.uk/c.kloukinas/cpp (slides originally produced by Dr Ross Paterson)

More information

Lecture-5. STL Containers & Iterators

Lecture-5. STL Containers & Iterators Lecture-5 STL Containers & Iterators Containers as a form of Aggregation Fixed aggregation An object is composed of a fixed set of component objects Variable aggregation An object is composed of a variable

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

1. The term STL stands for?

1. The term STL stands for? 1. The term STL stands for? a) Simple Template Library b) Static Template Library c) Single Type Based Library d) Standard Template Library Answer : d 2. Which of the following statements regarding the

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

List, Stack, and Queues

List, Stack, and Queues List, Stack, and Queues R. J. Renka Department of Computer Science & Engineering University of North Texas 02/24/2010 3.1 Abstract Data Type An Abstract Data Type (ADT) is a set of objects with a set of

More information

The Standard Template Library Classes

The Standard Template Library Classes The Standard Template Library Classes Lecture 33 Sections 9.7, 9.8 Robb T. Koether Hampden-Sydney College Wed, Apr 23, 2014 Robb T. Koether (Hampden-Sydney College) The Standard Template Library Classes

More information

CSE 100: C++ TEMPLATES AND ITERATORS

CSE 100: C++ TEMPLATES AND ITERATORS 1 CSE 100: C++ TEMPLATES AND ITERATORS 2 Announcements Look out for the extra weekend section More on git and C++ (iterators) Live demo by your friendly tutors Not mandatory but it will be fun Bring your

More information

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms AUTO POINTER (AUTO_PTR) //Example showing a bad situation with naked pointers void MyFunction()

More information

CMSC 202 Final May 19, Name: UserID: (Circle your section) Section: 101 Tuesday 11: Thursday 11:30

CMSC 202 Final May 19, Name: UserID: (Circle your section) Section: 101 Tuesday 11: Thursday 11:30 CMSC 202 Final May 19, 2005 Name: UserID: (Circle your section) Section: 101 Tuesday 11:30 102 Thursday 11:30 Directions 103 Tuesday 12:30 104 Thursday 12:30 105 Tuesday 1:30 106 Thursday 1:30 This is

More information

CS 247: Software Engineering Principles. C++ Templates. Reading: Eckel, Vol. 2 Ch. 5 Templates in Depth. U Waterloo CS247 (Spring 2017) p.

CS 247: Software Engineering Principles. C++ Templates. Reading: Eckel, Vol. 2 Ch. 5 Templates in Depth. U Waterloo CS247 (Spring 2017) p. CS 247: Software Engineering Principles C++ Templates Reading: Eckel, Vol. 2 Ch. 5 Templates in Depth U Waterloo CS247 (Spring 2017) p.1/16 Overloaded Functions Problem: Code in overloaded functions whose

More information

Software Development with C++ Templates

Software Development with C++ Templates Software Development with C++ Templates Lab Submission 1 Exercises should be solved in groups of two. However, with approval from the lecturer, exercises may also be solved alone or in groups of three.

More information

Lecture 8. Xiaoguang Wang. February 13th, 2014 STAT 598W. (STAT 598W) Lecture 8 1 / 47

Lecture 8. Xiaoguang Wang. February 13th, 2014 STAT 598W. (STAT 598W) Lecture 8 1 / 47 Lecture 8 Xiaoguang Wang STAT 598W February 13th, 2014 (STAT 598W) Lecture 8 1 / 47 Outline 1 Introduction: C++ 2 Containers 3 Classes (STAT 598W) Lecture 8 2 / 47 Outline 1 Introduction: C++ 2 Containers

More information

CS201 Some Important Definitions

CS201 Some Important Definitions CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data

More information

Dynamic Data Structures

Dynamic Data Structures Dynamic Data Structures We have seen that the STL containers vector, deque, list, set and map can grow and shrink dynamically. We now examine how some of these containers can be implemented in C++. To

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

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

Exceptions, Templates, and the STL

Exceptions, Templates, and the STL Exceptions, Templates, and the STL CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 16 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/

More information

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak! //Example showing a bad situation with naked pointers CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms void MyFunction() MyClass* ptr( new

More information

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a. Intro to OOP - Object and class - The sequence to define and use a class in a program - How/when to use scope resolution operator - How/when to the dot operator - Should be able to write the prototype

More information

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

! Search: find a given target item in an array, ! Linear Search: Very simple search method: ! Operators such as =, +, <, and others can be Operator Overloading and Templates Week 6 Gaddis: 8.1, 14.5, 16.2-16.4 CS 5301 Spring 2015 Jill Seaman Linear Search! Search: find a given target item in an array, return the index of the item, or -1 if

More information

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018 Pointer Basics Lecture 13 COP 3014 Spring 2018 March 28, 2018 What is a Pointer? A pointer is a variable that stores a memory address. Pointers are used to store the addresses of other variables or memory

More information

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC CMSC 341 Lecture 6 Templates, Stacks & Queues Based on slides by Shawn Lupoli & Katherine Gibson at UMBC Today s Topics Data types in C++ Overloading functions Templates How to implement them Possible

More information

Cpt S 122 Data Structures. Templates

Cpt S 122 Data Structures. Templates Cpt S 122 Data Structures Templates Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Introduction Function Template Function-template and function-template

More information

(8 1) Container Classes & Class Templates D & D Chapter 18. Instructor - Andrew S. O Fallon CptS 122 (October 8, 2018) Washington State University

(8 1) Container Classes & Class Templates D & D Chapter 18. Instructor - Andrew S. O Fallon CptS 122 (October 8, 2018) Washington State University (8 1) Container Classes & Class Templates D & D Chapter 18 Instructor - Andrew S. O Fallon CptS 122 (October 8, 2018) Washington State University Key Concepts Class and block scope Access and utility functions

More information

Standard Library Reference

Standard Library Reference Standard Library Reference This reference shows the most useful classes and functions in the standard library. Note that the syntax [start, end) refers to a half-open iterator range from start to end,

More information

III. Classes (Chap. 3)

III. Classes (Chap. 3) III. Classes III-1 III. Classes (Chap. 3) As we have seen, C++ data types can be classified as: Fundamental (or simple or scalar): A data object of one of these types is a single object. int, double, char,

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

POINTERS - Pointer is a variable that holds a memory address of another variable of same type. - It supports dynamic allocation routines. - It can improve the efficiency of certain routines. C++ Memory

More information

C++ (Non for C Programmer) (BT307) 40 Hours

C++ (Non for C Programmer) (BT307) 40 Hours C++ (Non for C Programmer) (BT307) 40 Hours Overview C++ is undoubtedly one of the most widely used programming language for implementing object-oriented systems. The C++ language is based on the popular

More information

CHAPTER 4 FUNCTIONS. 4.1 Introduction

CHAPTER 4 FUNCTIONS. 4.1 Introduction CHAPTER 4 FUNCTIONS 4.1 Introduction Functions are the building blocks of C++ programs. Functions are also the executable segments in a program. The starting point for the execution of a program is main

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College November 22, 2017 Outline Outline 1 Chapter 12: C++ Templates Outline Chapter 12: C++ Templates 1 Chapter 12: C++ Templates

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

When we program, we have to deal with errors. Our most basic aim is correctness, but we must

When we program, we have to deal with errors. Our most basic aim is correctness, but we must Chapter 5 Errors When we program, we have to deal with errors. Our most basic aim is correctness, but we must deal with incomplete problem specifications, incomplete programs, and our own errors. When

More information

Lesson 13 - Vectors Dynamic Data Storage

Lesson 13 - Vectors Dynamic Data Storage Lesson 13 - Vectors Dynamic Data Storage Summary In this lesson we introduce the Standard Template Library by demonstrating the use of Vectors to provide dynamic storage of data elements. New Concepts

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

CSE 100: C++ TEMPLATES AND ITERATORS

CSE 100: C++ TEMPLATES AND ITERATORS CSE 100: C++ TEMPLATES AND ITERATORS Announcements Gradesource and clickers: We ll be making one more pass for unregistered clickers tonight, but after that you ll be on your own How is Assignment 1 going?

More information

C++ Addendum: Inheritance of Special Member Functions. Constructors Destructor Construction and Destruction Order Assignment Operator

C++ Addendum: Inheritance of Special Member Functions. Constructors Destructor Construction and Destruction Order Assignment Operator C++ Addendum: Inheritance of Special Member Functions Constructors Destructor Construction and Destruction Order Assignment Operator What s s Not Inherited? The following methods are not inherited: Constructors

More information

STL Quick Reference for CS 241

STL Quick Reference for CS 241 STL Quick Reference for CS 241 Spring 2018 The purpose of this document is to provide basic information on those elements of the C++14 standard library we think are most likely to be needed in CS 241.

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

Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS

Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS Contents Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS 1.1. INTRODUCTION TO COMPUTERS... 1 1.2. HISTORY OF C & C++... 3 1.3. DESIGN, DEVELOPMENT AND EXECUTION OF A PROGRAM... 3 1.4 TESTING OF PROGRAMS...

More information

Before we dive in. Preprocessing Compilation Linkage

Before we dive in. Preprocessing Compilation Linkage Templates Before we dive in Preprocessing Compilation Linkage 2 Motivation A useful routine to have is void swap( int& a, int &b ) int tmp = a; a = b; b = tmp; 3 Example What happens if we want to swap

More information

C++FA 6.1 PRACTICE FINAL EXAM

C++FA 6.1 PRACTICE FINAL EXAM C++FA 6.1 PRACTICE FINAL EXAM This practice final exam covers sections C++FA 2.1 through C++FA 4.1 of C++ with Financial Applications by Ben Van Vliet, available at www.benvanvliet.net. 1.) A T is a/an:

More information

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

THE STANDARD TEMPLATE LIBRARY (STL) Week 6 BITE 1513 Computer Game Programming THE STANDARD TEMPLATE LIBRARY (STL) Week 6 BITE 1513 Computer Game Programming What the heck is STL???? Another hard to understand and lazy to implement stuff? Standard Template Library The standard template

More information

Introduction to C++ Friends, Nesting, Static Members, and Templates Topic #7

Introduction to C++ Friends, Nesting, Static Members, and Templates Topic #7 Introduction to C++ Friends, Nesting, Static Members, and Templates Topic #7 CS202 7-1 Relationship of Objects Friends, Nesting Static Members Template Functions and Classes Reusing Code Template Specializations

More information

19.1 The Standard Template Library

19.1 The Standard Template Library Chapter 19: The Template Library From a review of Effective STL : 50 Specific Ways to Improve Your Use of the Standard Template Library by ScottMeyers: It s hard to overestimate the importance of the Standard

More information

10. Functions (Part 2)

10. Functions (Part 2) 10.1 Overloaded functions 10. Functions (Part 2) In C++, two different functions can have the same name if their parameters are different; either because they have a different number of parameters, or

More information

G52CPP C++ Programming Lecture 18

G52CPP C++ Programming Lecture 18 G52CPP C++ Programming Lecture 18 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Welcome Back 2 Last lecture Operator Overloading Strings and streams 3 Operator overloading - what to know

More information

Sets and MultiSets. Contents. Steven J. Zeil. July 19, Overview of Sets and Maps 4

Sets and MultiSets. Contents. Steven J. Zeil. July 19, Overview of Sets and Maps 4 Steven J. Zeil July 19, 2013 Contents 1 Overview of Sets and Maps 4 1 2 The Set ADT 6 2.1 The template header................................. 14 2.2 Internal type names.................................

More information

CSE100. Advanced Data Structures. Lecture 4. (Based on Paul Kube course materials)

CSE100. Advanced Data Structures. Lecture 4. (Based on Paul Kube course materials) CSE100 Advanced Data Structures Lecture 4 (Based on Paul Kube course materials) Lecture 4 Binary search trees Toward a binary search tree implementation using C++ templates Reading: Weiss Ch 4, sections

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

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings 19/10/2017 CE221 Part 2 1 Variables and References 1 In Java a variable of primitive type is associated with a memory location

More information

G52CPP C++ Programming Lecture 13

G52CPP C++ Programming Lecture 13 G52CPP C++ Programming Lecture 13 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture Function pointers Arrays of function pointers Virtual and non-virtual functions vtable and

More information

Unit 4 Basic Collections

Unit 4 Basic Collections Unit 4 Basic Collections General Concepts Templates Exceptions Iterators Collection (or Container) Classes Vectors (or Arrays) Sets Lists Maps or Tables C++ Standard Template Library (STL Overview A program

More information

! An exception is a condition that occurs at execution time and makes normal continuation of the program impossible.

! An exception is a condition that occurs at execution time and makes normal continuation of the program impossible. Exceptions! Exceptions are used to signal error or unexpected events that occur while a program is running.! An exception is a condition that occurs at execution time and makes normal continuation of the

More information

CPSC 427a: Object-Oriented Programming

CPSC 427a: Object-Oriented Programming CPSC 427a: Object-Oriented Programming Michael J. Fischer Lecture 17 November 1, 2011 CPSC 427a, Lecture 17 1/21 CPSC 427a, Lecture 17 2/21 CPSC 427a, Lecture 17 3/21 A bit of history C++ standardization.

More information

G52CPP C++ Programming Lecture 18. Dr Jason Atkin

G52CPP C++ Programming Lecture 18. Dr Jason Atkin G52CPP C++ Programming Lecture 18 Dr Jason Atkin 1 Last lecture Operator Overloading Strings and streams 2 Operator overloading - what to know Know that you can change the meaning of operators Know that

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

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe OBJECT ORIENTED PROGRAMMING USING C++ CSCI 5448- Object Oriented Analysis and Design By Manali Torpe Fundamentals of OOP Class Object Encapsulation Abstraction Inheritance Polymorphism Reusability C++

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

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst Department of Computer Science Why C? Low-level Direct access to memory WYSIWYG (more or less) Effectively

More information

Instantiation of Template class

Instantiation of Template class Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double

More information

Polymorphism and Type Inference

Polymorphism and Type Inference Polymorphism and Type Inference Volker Stolz stolz@ifi.uio.no Department of Informatics University of Oslo Initially by Gerardo Schneider. Based on John C. Mitchell s slides (Stanford U.) Compile-time

More information

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive) Final Exam Exercises Chapters 1-7 + 11 Write C++ code to: l Determine if a number is odd or even CS 2308 Fall 2016 Jill Seaman l Determine if a number/character is in a range - 1 to 10 (inclusive) - between

More information

Exercise 6.2 A generic container class

Exercise 6.2 A generic container class Exercise 6.2 A generic container class The goal of this exercise is to write a class Array that mimics the behavior of a C++ array, but provides more intelligent memory management a) Start with the input

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

CS304 Object Oriented Programming

CS304 Object Oriented Programming 1 CS304 Object Oriented Programming 1. Which of the following is the way to extract common behaviour and attributes from the given classes and make a separate class of those common behaviours and attributes?

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 20 November 14, 2016 CPSC 427, Lecture 20 1/19 Templates Casts and Conversions CPSC 427, Lecture 20 2/19 Templates CPSC 427, Lecture 20

More information

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE? 1. Describe History of C++? The C++ programming language has a history going back to 1979, when Bjarne Stroustrup was doing work for his Ph.D. thesis. One of the languages Stroustrup had the opportunity

More information

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

Distributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes Distributed Real-Time Control Systems Lecture 17 C++ Programming Intro to C++ Objects and Classes 1 Bibliography Classical References Covers C++ 11 2 What is C++? A computer language with object oriented

More information

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT).

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT). UNITII Classes Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT). It s a User Defined Data-type. The Data declared in a Class are called Data- Members

More information

class Polynomial { public: Polynomial(const string& N = "no name", const vector<int>& C = vector<int>());... };

class Polynomial { public: Polynomial(const string& N = no name, const vector<int>& C = vector<int>());... }; Default Arguments 1 When declaring a C++ function, you may optionally specify a default value for function parameters by listing initializations for them in the declaration: class Polynomial { public:

More information

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING 1. Object Oriented Programming Paradigms 2. Comparison of Programming Paradigms 3. Basic Object Oriented Programming

More information

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++ No. of Printed Pages : 3 I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination 05723. June, 2015 BCS-031 : PROGRAMMING IN C ++ Time : 3 hours Maximum Marks : 100 (Weightage 75%)

More information

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

Operator Overloading and Templates. Linear Search. Linear Search in C++ second attempt. Linear Search in C++ first attempt Operator Overloading and Templates Week 6 Gaddis: 8.1, 14.5, 16.2-16.4 CS 5301 Fall 2015 Jill Seaman Linear Search! Search: find a given target item in an array, return the index of the item, or -1 if

More information

Programming in C++ using STL. Rex Jaeschke

Programming in C++ using STL. Rex Jaeschke Programming in C++ using STL Rex Jaeschke Programming in C++ using STL 1997, 1999, 2002, 2007, 2009 Rex Jaeschke. All rights reserved. Edition: 2.0 All rights reserved. No part of this publication may

More information

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

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1 Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1 Inheritance Consider a new type Square. Following how we declarations for the Rectangle and Circle classes we could declare it as follows:

More information

Data Structures and Algorithms

Data Structures and Algorithms Data Structures and Algorithms Alice E. Fischer Lecture 6: Stacks 2018 Alice E. Fischer Data Structures L5, Stacks... 1/29 Lecture 6: Stacks 2018 1 / 29 Outline 1 Stacks C++ Template Class Functions 2

More information

Standard Template Library

Standard Template Library Standard Template Library Wednesday, October 10, 2007 10:09 AM 9.3 "Quick Peek" STL history 1990s Alex Stepanov & Meng Lee of HP Labs 1994 ANSI/IS0 standard Components Container class templates Iterators

More information

Object Oriented Programming. Solved MCQs - Part 2

Object Oriented Programming. Solved MCQs - Part 2 Object Oriented Programming Solved MCQs - Part 2 Object Oriented Programming Solved MCQs - Part 2 It is possible to declare as a friend A member function A global function A class All of the above What

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

Chapter 11. Abstract Data Types and Encapsulation Concepts

Chapter 11. Abstract Data Types and Encapsulation Concepts Chapter 11 Abstract Data Types and Encapsulation Concepts The Concept of Abstraction An abstraction is a view or representation of an entity that includes only the most significant attributes The concept

More information

CSE 100: C++ TEMPLATES AND ITERATORS

CSE 100: C++ TEMPLATES AND ITERATORS CSE 100: C++ TEMPLATES AND ITERATORS Announcements iclickers: Please register at ted.ucsd.edu. Start ASAP!! For PA1 (Due next week). 10/6 grading and 10/8 regrading How is Assignment 1 going? A. I haven

More information

Object Oriented Design

Object Oriented Design Object Oriented Design Chapter 9 Initializing a non-static data member in the class definition is a syntax error 1 9.2 Time Class Case Study In Fig. 9.1, the class definition is enclosed in the following

More information

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Quiz Start Time: 09:34 PM Time Left 82 sec(s) Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information