COEN244: Class & function templates
|
|
- Elizabeth Reynolds
- 5 years ago
- Views:
Transcription
1 COEN244: Class & function templates Aishy Amer Electrical & Computer Engineering Templates Function Templates Class Templates Outline Templates and inheritance Introduction to C++ Standard Template Library (STL) c A. Amer Class templates 1
2 Templates With templates, you can write functions and classes that work for any appropriate built-in or programmer-defined types Object-Oriented Philosophy Data Encapsulation Classes Software Reuse Inheritance, Composition Software Extensibility Polymorphism Software Reuse & Generic Code Templates Generic (genericity = "class templates"); General (generality = solutions which are not specific) c A. Amer Class templates 2
3 Templates: introduction / / A f u n c t i o n t h a t swaps i t s two i n t e g e r arguments : void swap ( i n t& x, i n t& y ) { / / f o r c e s the func. to work only with i n t i n t tmp = x ; x = y ; y = tmp ; } Assume you want to swap floats, longs, Strings, Rectangles, etc. void swap ( f l o a t& x, f l o a t& y ) { / / f o r c e s the func. to work only with f l o a t f l o a t tmp = x ; x = y ; y = tmp ; } Repetition of code... c A. Amer Class templates 3
4 Templates: introduction / / An Array class class Array { public : Array ( i n t len =10) : len_ ( len ), data_ (new i n t [ len ] ) { } Array ( const Array & ) ; ~Array ( ) ; i n t len ( ) const { return len_ ; } const i n t& operator [ ] private : i n t len_ ; i n t data_ ; / / f o r c e s the array to hold only i n t... } ; Assume you want an array of float, char, string,... Repeating the above over and over for float, char, string,.. tedious c A. Amer Class templates 4
5 Templates A template is a "type generator": a way to fabricate many similar classes or functions from one piece of code Templates support generic programming by obviating the need for explicit statements to deal with various data types "A template is a cookie-cutter that specifies how to cut cookies that all look pretty much the same (although the cookies can be made of various kinds of dough, they ll all have the same basic shape)." A template can be a Function Template or a Class Template c A. Amer Class templates 5
6 Function Templates A function template is the declaration of a function using templates The compiler will create a function version for every type (replacing the template) that calls the function A template function is the various instantiations of the function that the compiler creates Function Templates can be seen as an automatic way to overloading functions c A. Amer Class templates 6
7 Function Templates: an example / / A f u n c t i o n t h a t swaps i t s two i n t e g e r arguments : void swap ( i n t& x, i n t& y ) { i n t tmp = x ; x = y ; y = tmp ; } Assume you want to swap floats, longs, Strings, Rectangles, etc. You would have to write the same code lines except for the type Repetitions... an ideal job for a computer c A. Amer Class templates 7
8 Function Templates: Example template <class AType> / / scope of AType i s to the end of the f u n c t i o n void swap ( T& x, T& y ) { AType tmp = x ; x = y ; y = tmp ; } / / end scope of AType Every time swap(..) is called with a given pair of types, the compiler will go to the above definition and will create yet another "template function" as an instantiation of the above c A. Amer Class templates 8
9 Function Templates: Example i n t main ( ) { i n t i, j ; /... / swap ( i, j ) ; / / I n s t a n t i a t e s a swap f o r i n t f l o a t a, b ; /... / swap ( a, b ) ; / / I n s t a n t i a t e s a swap f o r f l o a t char c, d ; /... / swap ( c, d ) ; / / I n s t a n t i a t e s a swap f o r char s t r i n g s, t ; /... / swap ( s, t ) ; / / I n s t a n t i a t e s a swap f o r s t r i n g Rectangle r, q ; /... / swap ( r, q ) ; / / I n s t a n t i a t e s a swap f o r Rectangle... } Note: A "template function" is the instantiation of a "function template" A function template describes how to build a family of similar looking functions c A. Amer Class templates 9
10 Function Templates: special cases When a function template is called, the compiler tries to deduce the template type Most of the time it can do that successfully, but there are cases where you need to help the compiler deduce the right type For example, a function template that doesn t have any parameters of its template argument types template <class AType> void f ( ) {... } / / To c a l l t h i s f u n c t i o n with T being an i n t or a s t r i n g : void sample ( ) { f <int > ( ) ; / / type T w i l l be i n t i n t h i s c a l l f < s t r i n g > ( ) ; / / type T w i l l be s t r i n g i n t h i s c a l l } c A. Amer Class templates 10
11 Outline Templates Function Templates Class Templates Templates and inheritance Introduction to C++ Standard Template Library (STL) c A. Amer Class templates 11
12 Class Templates A class template is the declaration of a class using templates The compiler will create a class version for every type (replacing the template) that uses the class A template class is the various instantiations of the class that the compiler creates A class template is a class fabrication source for a description of how to build a family of classes that all look basically the same Class templates are often used to build type-safe containers define a container that may contain a set of integers, a set of float or any other object A template class can use other templates as its data members c A. Amer Class templates 12
13 Template syntax template < class T > template < typename T > / / The Standard C++ keyword typename i s interchangeable / / with the keyword class i n the template header template < class T1, class T2 > template < class T, i n t I > / / T : Type parameter ; I : Nontype parameter A template parameter can be Type parameter: the special notation typename T or class T means T is a type parameter that can be given any type as a value Nontype parameter: normal function or class style parameters, such as int i specify nontype parameters c A. Amer Class templates 13
14 Template = Parametrized type The term "parametrized type" is used sometime instead of "class templates" A parametrized type is a type that is parametrized over another type or some value List<int> is a type (List) parametrized over another type (int) c A. Amer Class templates 14
15 Container class "int Array" Consider a container class Array that acts like an array of integers: class Array { public : Array ( i n t len =10) : len_ ( len ), data_ (new i n t [ len ] ) { } Array ( const Array & ) ; ~Array ( ) { delete [ ] data_ ; } i n t len ( ) const { return len_ ; } i n t& operator [ ] ( i n t i ) { return data_ [ check ( i ) ] ; } Array& operator= ( const Array & ) ; private : i n t len_ ; i n t data_ ; i n t check ( i n t i ) const { i f ( i <0 i >= len_ ) { cout << " Bound v i o l a t i o n " ; e x i t ( 0 ) ; } return i ; } } ; Repeating the above over and over for Array of float, Student,.. is tedious c A. Amer Class templates 15
16 Container class "template Array" / / D e c l a r a t i o n and implementation go i n t o a header f i l e such as " Array. h " template <class AType> class Array { public : Array ( i n t len =10) : len_ ( len ), data_ (new AType [ len ] ) { } Array ( const Array <AType >&); ~Array ( ) { delete [ ] data_ ; } i n t len ( ) const { return len_ ; } AType& operator [ ] ( i n t i ) { return data_ [ check ( i ) ] ; } Array <AType>& operator= ( const Array <AType >&); private : i n t len_ ; AType data_ ; i n t check ( i n t i ) const { i f ( i <0 i >= len_ ) { cout << " Bound v i o l a t i o n " ; e x i t ( 0 ) ; } return i ; } } ; / /... implementation c A. Amer Class templates 16
17 Container class "template Array" i n t main ( ) { Array <int > a i ; / / array of i n t Array < f l o a t > af ; / / array of f l o a t Array <char > ac ; Array < s t r i n g > as ; Array < Array <int > > aai ; / / array of an array of i n t / / Note the space between the two > s i n the l a s t example / / Without t h i s space, the compiler would see a >> ( r i g h t s h i f t operator )... } Note: unlike template functions, template classes (instantiations of class templates) need to be explicit about the parameters over which they are instantiating c A. Amer Class templates 17
18 Templates definition and declaration In one header file: Template classes must be declared and defined in a header file and included together in the driver program Why? If a class definition is implemented in a separate.cpp file, then it is compiled into a separate object code file (.o) The problem arises when the various class objects are to be created in a driver Since the class was already compiled it is too late to create the automatically created overloaded classes Solution? Nothing standardized yet c A. Amer Class templates 18
19 Templates definition and declaration In one header file: simplified rules A template is not a class or a function A template is a "pattern" that the compiler uses to generate a family of classes or functions In order for the compiler to generate the code, it must see both the template definition (not just declaration) and the specific types/whatever used to "fill in" the template For example, if you re trying to use a Foo<int>, the compiler must see both the Foo template and the fact that you re trying to make a specific Foo<int> In most cases, the compiler options are such that a compiler doesn t remember the details of one.cpp file while it is compiling another.cpp file c A. Amer Class templates 19
20 Class Templates: important notes template <class AType> class Array { public : Array ( i n t l =10) : len ( l ), data_ (new AType [ l ] ) { }... private : AType data_ ; s t a t i c i n t count ;... } ; For every template class that has been created, a unique class implementation is created for that template This means that all member functions and member data (including static) are created for each template class c A. Amer Class templates 20
21 Class Templates: important notes You should place class declaration and class implementation in the same file *.h Wherever you reference a class object, you should include the template statement template <class Tp> double TPoint <Tp > : : getslope ( const TPoint <Tp> &p o i n t ) ; ^^^ ^^^ c A. Amer Class templates 21
22 Class Templates: complete example / / This would go i n t o a header f i l e such as " Array. h " template < class AType > class Array { public : Array ( i n t size = 10 ) ; Array ( const Array& ) ; ~Array ( ) ; i n t getsize ( ) const { return size ; } const Array& operator =( const Array& ) ; bool operator ==( const A r r a y& ) const ; AType& operator [ ] ( i n t index ) ; private : i n t size ; AType a r r a y P t r ; } ; c A. Amer Class templates 22
23 Class Templates: complete example template < class AType > Array < AType > : : Array ( i n t arraysize ) { size = ( arraysize >0? arraysize : 0 ) ; a r r a y P t r = new AType [ size ] ; } template < class AType > Array < AType > : : Array ( const Array& A ) { size = A. size ; a r r a y P t r = new AType [ A. size ] ; for ( i n t i = 0; i < size ; i ++ ) a r r a y P t r [ i ] = A. a r r a y P t r [ i ] ; } c A. Amer Class templates 23
24 Class Templates: complete example template < class AType > Array < AType >::~ Array ( ) { delete [ ] a r r a y P t r ; } template < class AType > const Array& Array < AType > : : operator =( const Array& A) { i f ( &A!= this ) { / / avoid s e l f assignment i f ( size!= A. size ) { delete [ ] a r r a y P t r ; size = A. size ; a r r a y P t r = new AType [ size ] ; } for ( i n t i = 0; i < size ; i ++ ) a r r a y P t r [ i ] = A. a r r a y P t r [ i ] ; } c A. Amer Class templates 24
25 Class Templates: complete example template < class AType > bool Array < AType > : : operator ==( const Array& A) const { i f ( size!= A. size ) { return false ; } for ( i n t i = 0; i < size ; i ++ ) i f ( a r r a y P t r [ i ]!= A. a r r a y P t r [ i ] ) return false ; return true ; } template < class AType > AType& Array < AType > : : operator [ ] ( i n t index ) { return a r r a y P t r [ index ] ; } c A. Amer Class templates 25
26 Class Templates: complete example / / This i s d r i v e r program #include " Array. h " i n t main ( ) { Array < i n t > i n t A r r a y ( 5 ) ; Array < char > alphabet ( 26 ) ; Array < double > double_pointer_array ( 30 ) ; Array < Student > studentarray ( 100 ) ; Array < Employee > emparray ( 50 ) ;... for ( i n t i =0; i <5; i ++) i n t A r r a y [ i ] = 0;... } return 0; c A. Amer Class templates 26
27 Nontype Parameters template < class T, i n t size > class Array { public : Array ( ) ; Array ( const Array& ) ; i n t getsize ( ) const { return size ; } const Array& operator =( const Array& ) ; bool operator ==( const A r r a y& ) const ; T& operator [ ] ( i n t index ) ; private : T a r r a y P t r [ size ] ; } ; void main ( ) { Array < int, 10 > i n t A r r a y ; Array < String, 200 > Two100Strings ; } Nontype template arguments must be constant c A. Amer Class templates 27
28 Outline Templates Function Templates Class Templates Templates and inheritance Introduction to C++ Standard Template Library (STL) c A. Amer Class templates 28
29 Templates and Inheritance A class template can be derived from a template class template < class T > class Base { public : T Bdata ; } ; template < class X > class Derived : public Base< i n t > { public : X Ddata ; } ; c A. Amer Class templates 29
30 Templates and Inheritance A class template can be derived from a non-template class class Base { public : i n t Bdata ; } ; template < class X > class Derived : public Base { public : X Ddata ; } ; c A. Amer Class templates 30
31 Templates and Inheritance A class template can be derived from a class template template < class T > class Base { public : T Bdata ; } ; template < class X, class Y > class Derived : public Base< Y > { public : X Ddata ; } ; c A. Amer Class templates 31
32 Templates and Inheritance A non-template class can be derived from a class template template < class T > class Base { public : T Bdata ; } ; template < class X > class Derived : public Base< X > { public : i n t Ddata ; } ; c A. Amer Class templates 32
33 Templates: comments Templates make programs larger, slower, and harder to understand Programmers design template classes or functions in exceptional cases You need, however, to understand templates to use Standard Templates Library Make sure you understand the important notes on the related slides 20 and 21 c A. Amer Class templates 33
34 Outline Templates Function Templates Class Templates Templates and inheritance Introduction to C++ Standard Template Library (STL) c A. Amer Class templates 34
35 Introduction to STL C++ provides many standard libraries such as <iostream>, <cmath>, <complex>, <vector> These standard libraries are NOT part of the language but are very convenient and useful The Standard Template Library are implemented using templates The STL save time and effort in software development The STL ensures compatibility The STL includes three key components: Containers Iterators Algorithms c A. Amer Class templates 35
36 STL: Containers A container is an object whose main purpose is to hold other objects that can be accessed by iterators and processed using algorithms such as sort or search Example: a vector is a container that holds objects of any type that can be inserted and removed from it Containers are defined in the namespace std and are defined as template classes in different header files Containers are template data structures c A. Amer Class templates 36
37 STL: Containers The standard containers and their basic operations are designed to be very similar For example: to get the number of elements in a container, use the member function size Containers are categorized as: Sequence containers Associative containers Container adapters c A. Amer Class templates 37
38 STL: Sequence Containers Type Description Header vector<t> a variable-sized 1D array rapid insertion and deletion at back direct access to any element list<t> a doubly linked list rapid insertion and deletion anywhere deque<t> a double-ended queue rapid insertion and deletion at front and back direct access to any element <vector> <list> <deque> c A. Amer Class templates 38
39 STL: Associative containers Type Description Header set<t> a set <set> multiset<t> a set: a value can occur many times <set> map<key,val> an associative array <map> multimap<key,val> a map: a value can occur many times <map> c A. Amer Class templates 39
40 STL: Container Adapters Type Description Header stack<t> a stack <stack> queue<t> a queue <queue> priority-queue<t> a queue: sorted by value <queue> c A. Amer Class templates 40
41 STL: Common Member Functions default constructor: Provide default initialization of the container copy constructor: Create a new container, initialize using another container destructor: Clean up the container empty: Returns true if no elements exist in the container max size: Returns max number of elements for the container size: Returns number of elements in the container operators (=,<,>,<=,>=, ==): Relational operator overloads swap: Swaps the elements of two containers c A. Amer Class templates 41
42 STL: Iterators Every container provides iterators to traverse along its elements An iterator is an object of some type and is used to refer to elements in a sequence Iterators are like pointers to a container s elements De-referencing an iterator gives access to the container s element Using ++ on an iterator move the iterator to the next element in the container c A. Amer Class templates 42
43 STL: Iterator Categories input: Used to read an element from a container Can move only in the forward direction output: Used to write an element to a container Can move only in the forward direction forward: Combines the capabilities of the input and output iterators and retains position in the container bidirectional: Combines the capabilities of the bidirectional iterator with the ability to directly access any element random access: bidirectional combines the capabilities of the forward iterator with the ability to move backwards c A. Amer Class templates 43
44 STL: Iterator Hierarchy input output forward bidirectional stronger iterator random access When a supported iterator may work on a container, then a weaker iterator will also work c A. Amer Class templates 44
45 STL: Supported Iterators Container vector list deque stack queue priority_queue set multiset map multimap Type of Iterator random access bidirectional random access none none none bidirectional bidirectional bidirectional bidirectional c A. Amer Class templates 45
46 STL: Algorithms Algorithms are the functions that may be used on a container to process its elements: insert, delete, search for, sort a container, count, etc. Algorithms use iterators to process through containers Container member function begin() returns an iterator to the first element in the container Container member function end() returns an iterator to the first position past the last element of the container c A. Amer Class templates 46
47 STL: Types of Algorithms Mutating-sequence algorithms: modify container Non-mutating-sequence algorithms: does not modify container Numerical algorithms: perform calculations on an entire container (found in header file <numeric>) c A. Amer Class templates 47
48 STL: Mutating-sequence Algorithms copy() copy backward() fill() fill n() rotate copy() rotate() generate() generate n() swap() random shuffle() transform() partition() remove() reverse copy() remove copy() remove copy if() remove if() stable partition() replace() replace copy if() replace if() reverse() unique() unique copy() c A. Amer Class templates 48
49 STL: Non-Mutating-sequence Algorithms adjacent find() count() count if() equal() mismatch() search() find() find each() find end() find first of() find if() search n() c A. Amer Class templates 49
50 STL: Numeric Algorithms accumulate() inner product() partial sum() adjacent difference() c A. Amer Class templates 50
51 Outline Templates Function Templates Class Templates Templates and inheritance Introduction to C++ Standard Template Library (STL) c A. Amer Class templates 51
Object-Oriented Programming
s iuliana@cs.ubbcluj.ro Babes-Bolyai University 2018 1 / 21 Overview s 1 s 2 2 / 21 s s Generic programming - algorithms are written with generic types, that are going to be specified later. Generic programming
More informationSTL: C++ Standard Library
STL: C++ Standard Library Encapsulates complex data structures and algorithms CSC 330 OO Software Design 1 We ve emphasized the importance of software reuse. Recognizing that many data structures and algorithms
More informationCMSC 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(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 informationAnd Even More and More C++ Fundamentals of Computer Science
And Even More and More C++ Fundamentals of Computer Science Outline C++ Classes Special Members Friendship Classes are an expanded version of data structures (structs) Like structs, the hold data members
More informationCS197c: 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 informationUnit 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 informationSTL components. STL: C++ Standard Library Standard Template Library (STL) Main Ideas. Components. Encapsulates complex data structures and algorithms
STL: C++ Standard Library Standard Template Library (STL) Encapsulates complex data structures and algorithms is a library of generic container classes which are both efficient and functional C++ STL developed
More information1. 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 informationFast 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 informationCMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am
CMSC 202 Section 010x Spring 2007 Computer Science II Final Exam Name: Username: Score Max Section: (check one) 0101 - Justin Martineau, Tuesday 11:30am 0102 - Sandeep Balijepalli, Thursday 11:30am 0103
More informationToday. andyoucanalsoconsultchapters6amd7inthetextbook. cis15-fall2007-parsons-lectvii.1 2
TEMPLATES Today This lecture looks at techniques for generic programming: Generic pointers Templates The standard template library Thebestreferenceis: http://www.cppreference.com/index.html andyoucanalsoconsultchapters6amd7inthetextbook.
More informationCpt 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 information7 TEMPLATES AND STL. 7.1 Function Templates
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
More informationIntroduction 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 informationWhen 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 informationPurpose 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 informationCE221 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 informationExercise 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 informationAN 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 informationChapter 1: Object-Oriented Programming Using C++
Chapter 1: Object-Oriented Programming Using C++ Objectives Looking ahead in this chapter, we ll consider: Abstract Data Types Encapsulation Inheritance Pointers Polymorphism Data Structures and Algorithms
More informationLecture-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 informationAgenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures
The main body and cout Agenda 1 Fundamental data types Declarations and definitions Control structures References, pass-by-value vs pass-by-references The main body and cout 2 C++ IS AN OO EXTENSION OF
More informationProgramming C++ Lecture 5. Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor
Programming C++ Lecture 5 Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor Jennifer.sartor@elis.ugent.be S Templates S Function and class templates you specify with a single code segment an entire
More informationpointers & references
pointers & references 1-22-2013 Inline Functions References & Pointers Arrays & Vectors HW#1 posted due: today Quiz Thursday, 1/24 // point.h #ifndef POINT_H_ #define POINT_H_ #include using
More informationLecture 21 Standard Template Library. A simple, but very limited, view of STL is the generality that using template functions provides.
Lecture 21 Standard Template Library STL: At a C++ standards meeting in 1994, the committee voted to adopt a proposal by Alex Stepanov of Hewlett-Packard Laboratories to include, as part of the standard
More informationIntroduction 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 informationIntroduction 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 informationCS 162, Lecture 25: Exam II Review. 30 May 2018
CS 162, Lecture 25: Exam II Review 30 May 2018 True or False Pointers to a base class may be assigned the address of a derived class object. In C++ polymorphism is very difficult to achieve unless you
More informationInstantiation 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 informationCMSC 341 Lecture 6 STL, Stacks, & Queues. Based on slides by Lupoli, Dixon & Gibson at UMBC
CMSC 341 Lecture 6 STL, Stacks, & Queues Based on slides by Lupoli, Dixon & Gibson at UMBC Templates 2 Common Uses for Templates Some common algorithms that easily lend themselves to templates: Swap what
More informationCpt 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 informationCPSC 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 informationAbsolute 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 informationOutline. 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 informationLesson 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 informationuse 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 informationChapter 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 informationChapter 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 informationObject-Oriented Programming
- oriented - iuliana@cs.ubbcluj.ro Babes-Bolyai University 2018 1 / 56 Overview - oriented 1 2 -oriented 3 4 5 6 7 8 Static and friend elements 9 Summary 2 / 56 I - oriented was initially created by Bjarne
More informationFunction 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 informationMore C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com
More C++ : Vectors, Classes, Inheritance, Templates with content from cplusplus.com, codeguru.com 2 Vectors vectors in C++ basically arrays with enhancements indexed similarly contiguous memory some changes
More information3.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 informationPolymorphism. 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 information19.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 informationDynamic 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 informationShort 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 informationPaytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value
Paytm Programming Sample paper: 1) A copy constructor is called a. when an object is returned by value b. when an object is passed by value as an argument c. when compiler generates a temporary object
More informationC++_ 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 informationCS201 - 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 informationC++ (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 informationAdvanced Systems Programming
Advanced Systems Programming Introduction to C++ Martin Küttler September 19, 2017 1 / 18 About this presentation This presentation is not about learning programming or every C++ feature. It is a short
More informationReview. Outline. Array Pointer Object-Oriented Programming. Fall 2017 CISC2200 Yanjun Li 1. Fall 2017 CISC2200 Yanjun Li 2
Review Fall 2017 CISC2200 Yanjun Li 1 Outline Array Pointer Object-Oriented Programming Fall 2017 CISC2200 Yanjun Li 2 1 Computer Fall 2017 CISC2200 Yanjun Li 3 Array Arrays are data structures containing
More informationCSI33 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 informationIntroduction to Programming using C++
Introduction to Programming using C++ Lecture One: Getting Started Carl Gwilliam gwilliam@hep.ph.liv.ac.uk http://hep.ph.liv.ac.uk/~gwilliam/cppcourse Course Prerequisites What you should already know
More informationObject Oriented Design Final Exam (From 3:30 pm to 4:45 pm) Name:
Object Oriented Design Final Exam (From 3:30 pm to 4:45 pm) Name: Section 1 Multiple Choice Questions (40 pts total, 2 pts each): Q1: Employee is a base class and HourlyWorker is a derived class, with
More informationCS 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 informationMore C++ : Vectors, Classes, Inheritance, Templates
Vectors More C++ : Vectors,, Inheritance, Templates vectors in C++ basically arrays with enhancements indexed similarly contiguous memory some changes defined differently can be resized without explicit
More informationTokens, Expressions and Control Structures
3 Tokens, Expressions and Control Structures Tokens Keywords Identifiers Data types User-defined types Derived types Symbolic constants Declaration of variables Initialization Reference variables Type
More informationC++ Programming Fundamentals
C++ Programming Fundamentals 269 Elvis C. Foster Lecture 11: Templates One of the contemporary sophistries of C++ programming is defining and manipulating templates. This lecture focuses on this topic.
More informationModern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi
Modern C++ for Computer Vision and Image Processing Igor Bogoslavskyi Outline Move semantics Classes Operator overloading Making your class copyable Making your class movable Rule of all or nothing Inheritance
More informationIntroduction 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 informationby 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 information1/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 informationTemplating functions. Comp Sci 1570 Introduction to C++ Administrative notes. Review. Templates. Compiler processing. Functions Overloading
s s in Templating functions Comp Sci 1570 Introduction to Outline s s in 1 2 3 s s in 4 Test 1 grade distribution grade on y, each student on x, sorted by y s s in 50 or below should talk to me. Outline
More informationExceptions, 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 informationl 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 informationCPSC 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 informationC++ (classes) Hwansoo Han
C++ (classes) Hwansoo Han Inheritance Relation among classes shape, rectangle, triangle, circle, shape rectangle triangle circle 2 Base Class: shape Members of a class Methods : rotate(), move(), Shape(),
More informationIS0020 Program Design and Software Tools Summer, 2004 August 2, 2004 in Class
IS0020 Program Design and Software Tools Summer, 2004 August 2, 2004 in Class Name: A. Fill in the blanks in each of the following statements [Score: 20]: 1. A base class s members can be accessed only
More informationPolymorphism Part 1 1
Polymorphism Part 1 1 What is Polymorphism? Polymorphism refers to a programming language s ability to process objects differently depending on their data type or class. Number person real complex kid
More informationVALLIAMMAI 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 informationThe Standard Template Library. An introduction
1 The Standard Template Library An introduction 2 Standard Template Library (STL) Objective: Reuse common code Common constructs: Generic containers and algorithms STL Part of the C++ Standard Library
More informationReview. Outline. Array Pointer Object-Oriented Programming. Fall 2013 CISC2200 Yanjun Li 1. Fall 2013 CISC2200 Yanjun Li 2
Review Fall 2013 CISC2200 Yanjun Li 1 Outline Array Pointer Object-Oriented Programming Fall 2013 CISC2200 Yanjun Li 2 1 Array Arrays are data structures containing related data items of same type. An
More informationMARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012
MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012 Instructor: K. S. Booth Time: 70 minutes (one hour ten minutes)
More informationInheritance, and Polymorphism.
Inheritance and Polymorphism by Yukong Zhang Object-oriented programming languages are the most widely used modern programming languages. They model programming based on objects which are very close to
More informationMotivation for Templates
Motivation for You want both: a list of Location objects a list of MazeMonster objects 1 How can you accomplish this by writing one LinkedList class? state all the ways you can think of doing this state
More information1. 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 informationCS304- Object Oriented Programming LATEST SOLVED MCQS FROM FINALTERM PAPERS. MC
CS304- Object Oriented Programming LATEST SOLVED MCQS FROM FINALTERM PAPERS JAN 28,2011 MC100401285 Moaaz.pk@gmail.com Mc100401285@gmail.com PSMD01 FINALTERM EXAMINATION 14 Feb, 2011 CS304- Object Oriented
More informationObject 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 informationCpt S 122 Data Structures. Introduction to C++ Part II
Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function
More informationInterview 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 informationCS201 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 informationArrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors
Arrays Returning arrays Pointers Dynamic arrays Smart pointers Vectors To declare an array specify the type, its name, and its size in []s int arr1[10]; //or int arr2[] = {1,2,3,4,5,6,7,8}; arr2 has 8
More informationCS304 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 informationReview for Test 1 (Chapter 1-5)
Review for Test 1 (Chapter 1-5) 1. Software development 1. Pre-conditions and Post-conditions 2. Running time analysis Big O Timing loops and nested loops 1) Write the simplest big-o expression to describe
More informationObject Oriented Programming with c++ Question Bank
Object Oriented Programming with c++ Question Bank UNIT-1: Introduction to C++ 1. Describe the following characteristics of OOP. i Encapsulation ii Polymorphism, iii Inheritance 2. Discuss function prototyping,
More informationChapter 10 Introduction to Classes
C++ for Engineers and Scientists Third Edition Chapter 10 Introduction to Classes CSc 10200! Introduction to Computing Lecture 20-21 Edgardo Molina Fall 2013 City College of New York 2 Objectives In this
More informationI 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 informationCHAPTER 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 informationProgramming, numerics and optimization
Programming, numerics and optimization Lecture A-4: Object-oriented programming Łukasz Jankowski ljank@ippt.pan.pl Institute of Fundamental Technological Research Room 4.32, Phone +22.8261281 ext. 428
More informationG52CPP C++ Programming Lecture 15
G52CPP C++ Programming Lecture 15 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 IMPORTANT No optional demo lecture at 2pm this week Please instead use the time to do your coursework I
More informationPROGRAMMING IN C++ (Regulation 2008) Answer ALL questions PART A (10 2 = 20 Marks) PART B (5 16 = 80 Marks) function? (8)
B.E./B.Tech. DEGREE EXAMINATION, NOVEMBER/DECEMBER 2009 EC 2202 DATA STRUCTURES AND OBJECT ORIENTED Time: Three hours PROGRAMMING IN C++ Answer ALL questions Maximum: 100 Marks 1. When do we declare a
More informationDiscussion 1E. Jie(Jay) Wang Week 10 Dec.2
Discussion 1E Jie(Jay) Wang Week 10 Dec.2 Outline Dynamic memory allocation Class Final Review Dynamic Allocation of Memory Recall int len = 100; double arr[len]; // error! What if I need to compute the
More informationThe Ada Standard Generic Library (SGL)
The Ada Standard Generic Library (SGL) Alexander V. Konstantinou Computer Science Graduate Seminar 4/24/96 1 Presentation Overview Introduction (S{T G}L) The C++ Standard Template Library (STL) Ada 95
More informationC++ 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 informationObject Oriented Paradigm
Object Oriented Paradigm History Simula 67 A Simulation Language 1967 (Algol 60 based) Smalltalk OO Language 1972 (1 st version) 1980 (standard) Background Ideas Record + code OBJECT (attributes + methods)
More informationAdvanced C++ STL. Tony Wong
Tony Wong 2017-03-25 C++ Standard Template Library Algorithms Sorting Searching... Data structures Dynamically-sized array Queues... The implementation is abstracted away from the users The implementation
More informationWelcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:
Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams
More informationProblem 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