Templates (again) Professor Hugh C. Lauer CS-2303, System Programming Concepts

Size: px
Start display at page:

Download "Templates (again) Professor Hugh C. Lauer CS-2303, System Programming Concepts"

Transcription

1 Templates (again) 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 Savitch, The C++ Programming Language, Special Edition, by Bjarne Stroustrup, and from C: How to Program, 5 th and 6 th editions, by Deitel and Deitel) 1

2 Outline Function templates and related (overloaded) functions Distinguishing between function templates and function-template specializations Class templates to create a group of related types Distinguishing between class templates and classtemplate specializations Overloading function templates Relationships among templates, inheritance, friends, and static members 2

3 Review Function Templates Written by programmer once Defines a whole family of overloaded functions Begins with the template keyword Contains template parameter list of formal types Week 5, Miscellaneous C++ topics 16.1 of Absolute C++ Formal type parameters Enclosed in angle brackets (<>) Preceded by keyword typename or keyword class Placeholders for fundamental or user-defined types Similar to macros in C, but with full type checking 3

4 Software Engineering Note Most C++ compilers require complete definition of template in client source-code using the template Templates often defined in header files Included via #include into the appropriate client files For class templates, member functions must also be defined in header file 4

5 Function Template Example Forms template<typename T> f() { } template<class ElementType> g(){ } template<typename BorderType, typename Filltype> h() { } 5

6 Common Programming Error If template is invoked with user-defined type, and if template uses functions or operators (e.g., ==, +, <=) with objects of class type, then those functions and operators must be overloaded for the user-defined type Forgetting to overload such operators causes compilation errors 6

7 Definition: Worcester Polytechnic Carnegie Institute Mellon Function Template Specialization Specialization: the automatic generation of a new overloaded function from the template as needed I.e., whenever a function template is called with a particular type Example for function template max with type parameter T called with int arguments Compiler detects a max invocation in the program code. int is substituted for T throughout the template definition. This produces function-template specialization max<int> 7

8 Overloading Function Templates Other function templates that specify the same name but different parameters Non-template functions that specify the same name but different parameters The compiler chooses best function or specialization to match the function call A non-template function is chosen over a template specialization in case of a tie Otherwise, multiple matches results in a compilation error (the compiler considers the function call to be an ambiguous function call ) 8

9 Questions about Function Templates? 9

10 Class Templates Also known as Parameterized Types Class-template definitions are preceded by a header Such as template< typename T > Type parameter T can be used as data type in members functions and data Multiple type parameters can be specified using comma-separated list e.g., template< typename T1, typename T2 > 10

11 Class Templates (continued) Class templates encourage software reusability by enabling type-specific versions of generic classes to be instantiated 11

12 Example 1 // Fig. 26.2: Stack.h 2 // Stack class template. 3 #ifndef STACK_H 4 #define STACK_H 5 6 template< typename T > 7 class Stack 8 { 9 public: 10 Stack( int = 10 ); // default constructor (Stack size 10) // destructor 13 ~Stack() 14 { 15 delete [] stackptr; // deallocate internal space for Stack 16 } // end ~Stack destructor bool push( const T& ); // push an element onto the Stack 19 bool pop( T& ); // pop an element off the Stack // determine whether Stack is empty 22 bool isempty() const 23 { 24 return top == -1; 25 } // end function isempty Create class template Stack with type parameter T Worcester Polytechnic Carnegie Institute Mellon Stack.h (1 of 3) Member functions with type parameter T in parameter lists 12

13 Example (continued) // determine whether Stack is full 28 bool isfull() const 29 { 30 return top == size - 1; 31 } // end function isfull private: 34 int size; // # of elements in the Stack 35 int top; // location of the top element (-1 means empty) 36 T *stackptr; // pointer to internal representation of the Stack 37 }; // end class template Stack // constructor template 40 template< typename T > 41 Stack< T >::Stack( int s ) 42 : size( s > 0? s : 10 ), // validate size 43 top( -1 ), // Stack initially empty 44 stackptr( new T[ size ] ) // allocate memory for elements 45 { 46 // empty body 47 } // end Stack constructor template Worcester Polytechnic Carnegie Institute Mellon Data member stackptr is pointer to T Stack.h (2 of 3) Member-function template definitions appearing outside class-template definition begin with template header 13

14 48 49 // push element onto Stack; 50 // if successful, return true; otherwise, return false 51 template< typename T > 52 bool Stack< T >::push( const T &pushvalue ) 53 { 54 if (!isfull() ) 55 { 56 stackptr[ ++top ] = pushvalue; // place item on Stack 57 return true; // push successful 58 } // end if return false; // push unsuccessful 61 } // end function template push // pop element off Stack; 64 // if successful, return true; otherwise, return false 65 template< typename T > 66 bool Stack< T >::pop( T &popvalue ) 67 { 68 if (!isempty() ) 69 { 70 popvalue = stackptr[ top-- ]; // remove item from Stack 71 return true; // pop successful 72 } // end if return false; // pop unsuccessful 75 } // end function template pop #endif Worcester Polytechnic Carnegie Institute Mellon Stack.h (3 of 3) Note: function bodies are spelled out in class header file! 14

15 48 49 // push element onto Stack; 50 // if successful, return true; otherwise, return false 51 template< typename T > 52 bool Stack< T >::push( const T &pushvalue ) 53 { 54 if (!isfull() ) 55 { 56 stackptr[ ++top ] = pushvalue; // place item on Stack 57 return true; // push successful 58 } // end if return false; // push unsuccessful 61 } // end function template push // pop element off Stack; 64 // if successful, return true; otherwise, return false 65 template< typename T > 66 bool Stack< T >::pop( T &popvalue ) 67 { 68 if (!isempty() ) 69 { 70 popvalue = stackptr[ top-- ]; // remove item from Stack 71 return true; // pop successful 72 } // end if return false; // pop unsuccessful 75 } // end function template pop #endif Worcester Polytechnic Carnegie Institute Mellon Stack.h (3ʹ of 3) T might have to overload operator = Why? Digression: What if T is an abstract class with subclasses? 15

16 1 // Fig. 26.3: fig26_03.cpp 2 // Stack class template test program. 3 #include <iostream> 4 using std::cout; 5 using std::endl; 6 7 #include "Stack.h" // Stack class template definition 8 9 int main() 10 { 11 Stack< double > doublestack( 5 ); // size 5 12 double doublevalue = 1.1; cout << "Pushing elements onto doublestack\n"; // push 5 doubles onto doublestack 17 while ( doublestack.push( doublevalue ) ) 18 { 19 cout << doublevalue << ' '; 20 doublevalue += 1.1; 21 } // end while cout << "\nstack is full. Cannot push " << doublevalue 24 << "\n\npopping elements from doublestack\n"; // pop elements from doublestack 27 while ( doublestack.pop( doublevalue ) ) 28 cout << doublevalue << ' '; Worcester Polytechnic Carnegie Institute Mellon Example.cpp (1 of 2) Create specialization Stack< double > 16

17 29 30 cout << "\nstack is empty. Cannot pop\n"; Stack< int > intstack; // default size int intvalue = 1; 34 cout << "\npushing elements onto intstack\n"; // push 10 integers onto intstack 37 while ( intstack.push( intvalue ) ) 38 { 39 cout << intvalue << ' '; 40 intvalue++; 41 } // end while cout << "\nstack is full. Cannot push " << intvalue 44 << "\n\npopping elements from intstack\n"; // pop elements from intstack 47 while ( intstack.pop( intvalue ) ) 48 cout << intvalue << ' '; cout << "\nstack is empty. Cannot pop" << endl; 51 return 0; 52 } // end main Worcester Polytechnic Carnegie Institute Mellon Example.cpp (2 of 2) Create specialization Stack< int > 17

18 1 // Fig. 26.4: fig26_04.cpp 2 // Stack class template test program. Function main uses a 3 // function template to manipulate objects of type Stack< T >. 4 #include <iostream> 5 using std::cout; 6 using std::endl; 7 8 #include <string> 9 using std::string; #include "Stack.h" // Stack class template definition // function template to manipulate Stack< T > 14 template< typename T > 15 void teststack( 16 Stack< T > &thestack, // reference to Stack< T > 17 T value, // initial value to push 18 T increment, // increment for subsequent values 19 const string stackname ) // name of the Stack< T > object 20 { 21 cout << "\npushing elements onto " << stackname << '\n'; // push element onto Stack 24 while ( thestack.push( value ) ) 25 { 26 cout << value << ' '; 27 value += increment; 28 } // end while Worcester Polytechnic Carnegie Institute Mellon Test.cpp (1 of 2) Use a function template to process Stack class-template specializations 18

19 29 30 cout << "\nstack is full. Cannot push " << value 31 << "\n\npopping elements from " << stackname << '\n'; // pop elements from Stack 34 while ( thestack.pop( value ) ) 35 cout << value << ' '; cout << "\nstack is empty. Cannot pop" << endl; 38 } // end function template teststack int main() 41 { 42 Stack< double > doublestack( 5 ); // size 5 43 Stack< int > intstack; // default size teststack( doublestack, 1.1, 1.1, "doublestack" ); 46 teststack( intstack, 1, 1, "intstack" ); return 0; 49 } // end main Worcester Polytechnic Carnegie Institute Mellon Test.cpp (2 of 2) 19

20 Questions? 20

21 Non-type Parameters and Default Types for Class Templates Nontype template parameters Can have default arguments Are treated as const Example Template header: template<typename T, int elements>... Declaration: Stack< double, 100 > salesfigures; Type parameters can have default arguments example: Template header: template< typename T = string >... Declaration: Stack<> jobdescriptions; 21

22 Templates and Inheritance A class template can be derived from a classtemplate specialization A class template can be derived from a nontemplate class A class-template specialization can be derived from a class-template specialization A non-template class can be derived from a classtemplate specialization 23

23 Templates and Friends Assume: template<typename T> class X A function can be a friend of every class-template specialization instantiated from a class template friend void f1(); f1 is a friend of X<double>, X<string>, etc. A function can be the friend of only a classtemplate specialization with the same type argument friend void f2( X<T> & ); f2( X<float> & ) is a friend of X<float> but not a friend of X<string> 24

24 Templates and Friends (continued) A member function of another class can be a friend of every class-template specialization instantiated from a class template friend void A::f3(); f3 of class A is a friend of X< double >, X< string >, etc. A member function of another class can be a friend of only a class-template specialization with the same type argument friend void C<T>::f4( X<T> & ); C<float>::f4( X<float> & ) is a friend of X<float> but not a friend of X<string> 25

25 Templates and Friends (continued) Another class can be a friend of every classtemplate specialization instantiated from a class template friend class Y; Every member function of class Y is a friend of X<double>, X<string>, etc. A class-template specialization can be the friend of only a class-template specialization with the same type parameter friend class Z< T >; Class-template specialization Z<float> is a friend of X<float>, Z<string> is a friend of X<string>, etc. 26

26 Templates and static members Each class-template specialization has own copy of each static data member All objects of that specialization share that one static data member static data members must be defined and, if necessary, initialized at file scope Each class-template specialization gets its own copy of the class template s static member functions 27

27 Questions about Class Templates? 28

28 Templates in the C++ Standard Library Strings <basic_string> is the template class string is typedef basic_string<char> There are lots of other kinds of strings Japanese, Chinese, w_char, etc. Vector Generalization of one-dimensional array Includes (stack operations, etc.) vector<bool> is a specialization for one bit per bool item List Ditto 29

29 Templates in the C++ Standard Library (continued) ValArray bitset Iterators Bitwise operations on bits For sequencing through collections of objects 30

30 Questions? 31

31 32

Chapter 12 - Templates

Chapter 12 - Templates Chapter 12 - Templates O utline 12.1 Introd uction 12.2 Function Te m plate s 12.3 Ove rload ing Te m plate Functions 12.4 Class Te m p late s 12.5 Class Te m plate s and Non-type Param e te rs 12.6 Te

More information

C++ Templates. David Camp

C++ Templates. David Camp C++ Templates David Camp C Marcos #define () #define min(i, j) (((i) < (j))? (i) : (j)) #define max(i, j) (((i) > (j))? (i) : (j)) #define RADTODEG(x)

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

Laboratorio di Tecnologie dell'informazione

Laboratorio di Tecnologie dell'informazione Laboratorio di Tecnologie dell'informazione Ing. Marco Bertini marco.bertini@unifi.it http://www.micc.unifi.it/bertini/ Generic programming What is generic programming? Generic programming is a style of

More information

Laboratorio di Tecnologie dell'informazione. Ing. Marco Bertini

Laboratorio di Tecnologie dell'informazione. Ing. Marco Bertini Laboratorio di Tecnologie dell'informazione Ing. Marco Bertini bertini@dsi.unifi.it http://www.dsi.unifi.it/~bertini/ Generic programming What is generic programming? Generic programming is a style of

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 IS 0020 Program Design and Software Tools Templates Lecture 10 March 23, 2004 Introduction 2 Templates Function templates Specify entire range of related (overloaded) functions Function-template specializations

More information

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

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

More information

Containers and the Standard Template Library (STL)

Containers and the Standard Template Library (STL) Containers and the Standard Template Library (STL) Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and

More information

Classes, Constructors, etc., in C++

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

More information

Exception Handling in C++

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

More information

Derived Classes in C++

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

More information

A Deeper Look at Classes

A Deeper Look at Classes A Deeper Look at Classes Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by

More information

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

Programming C++ Lecture 5. Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor

Programming 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 information

Your first C and C++ programs

Your first C and C++ programs Your first C and C++ programs 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++,

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

Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü

Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü 1 C LECTURE 12 ++ Data Structures 2 Data Structures 17.1

More information

Programmazione. Prof. Marco Bertini

Programmazione. Prof. Marco Bertini Programmazione Prof. Marco Bertini marco.bertini@unifi.it http://www.micc.unifi.it/bertini/ Generic programming What is generic programming? Static type checking means that type checking occurs at compile

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

Functions and Recursion

Functions and Recursion Functions and Recursion 1 Storage Classes Scope Rules Functions with Empty Parameter Lists Inline Functions References and Reference Parameters Default Arguments Unary Scope Resolution Operator Function

More information

Object Oriented Design

Object Oriented Design Object Oriented Design Chapter 6 Example Activity Diagram 1 Outline Chapter 6 Topics 6.6 C++ Standard Library Header Files 6.14 Inline Functions 6.16 Default Arguments 6.17 Unary Scope Resolution Operator

More information

Dynamic Memory Allocation (and Multi-Dimensional Arrays)

Dynamic Memory Allocation (and Multi-Dimensional Arrays) Dynamic Memory Allocation (and Multi-Dimensional Arrays) Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan

More information

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

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

More information

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

CE221 Programming in C++ Part 1 Introduction

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

More information

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

Computer Programming C++ Classes and Objects 6 th Lecture

Computer Programming C++ Classes and Objects 6 th Lecture Computer Programming C++ Classes and Objects 6 th Lecture 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University Copyrights 2015 Eom, Hyeonsang All Rights Reserved Outline

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Multiple Inheritance July 26, 2004 22.9 Multiple Inheritance 2 Multiple inheritance Derived class has several base classes Powerful,

More information

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

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

More information

Cpt S 122 Data Structures. Templatized Stack

Cpt S 122 Data Structures. Templatized Stack Cpt S 122 Data Structures Templatized Stack Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Test # 2 Jia XU (Lab Section 3) Xiaoyu Zhang (Lab Section 3) Anh

More information

Operator Overloading in C++ Systems Programming

Operator Overloading in C++ Systems Programming Operator Overloading in C++ Systems Programming Operator Overloading Fundamentals of Operator Overloading Restrictions on Operator Overloading Operator Functions as Class Members vs. Global Functions Overloading

More information

September 19,

September 19, September 19, 2013 1 Problems with previous examples Changes to the implementation will require recompilation & relinking of clients Extensions will require access to the source code Solutions Combine

More information

C++ Programming Fundamentals

C++ 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 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

Intermediate Programming, Spring 2017*

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

More information

Lab 2: ADT Design & Implementation

Lab 2: ADT Design & Implementation Lab 2: ADT Design & Implementation By Dr. Yingwu Zhu, Seattle University 1. Goals In this lab, you are required to use a dynamic array to design and implement an ADT SortedList that maintains a sorted

More information

Class and Function Templates

Class and Function Templates Class and Function 1 Motivation for One Way to Look at... Example: Queue of some type Foo C++ What can a parameter be used for? Instantiating a Template Usage of Compiler view of templates... Implementing

More information

Motivation for Templates. Class and Function Templates. One Way to Look at Templates...

Motivation for Templates. Class and Function Templates. One Way to Look at Templates... Class and Function 1 Motivation for 2 Motivation for One Way to Look at... Example: Queue of some type Foo C++ What can a parameter be used for? Instantiating a Template Usage of Compiler view of templates...

More information

Cpt S 122 Data Structures. Introduction to C++ Part II

Cpt 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 information

CS

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

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1. COMP6771 Advanced C++ Programming Week 6 Part Three: 2016 www.cse.unsw.edu.au/ cs6771 2. Why? In C++, class names cannot be overloaded. Thus: 1 class IntStack { 2 public: 3 void push(int&); 4 void pop();

More information

How to engineer a class to separate its interface from its implementation and encourage reuse.

How to engineer a class to separate its interface from its implementation and encourage reuse. 1 3 Introduction to Classes and Objects 2 OBJECTIVES In this chapter you ll learn: What classes, objects, member functions and data members are. How to define a class and use it to create an object. How

More information

Function Overloading

Function Overloading Function Overloading C++ supports writing more than one function with the same name but different argument lists How does the compiler know which one the programmer is calling? They have different signatures

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1. COMP6771 Advanced C++ Programming Week 7 Part One: Member Templates and 2016 www.cse.unsw.edu.au/ cs6771 2. Member Templates Consider this STL code: 1 #include 2 #include 3 #include

More information

And Even More and More C++ Fundamentals of Computer Science

And 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 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

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

Object-Oriented Design (OOD) and C++

Object-Oriented Design (OOD) and C++ Chapter 2 Object-Oriented Design (OOD) and C++ At a Glance Instructor s Manual Table of Contents Chapter Overview Chapter Objectives Instructor Notes Quick Quizzes Discussion Questions Projects to Assign

More information

Programming Assignment #4 Binary Trees in C++

Programming Assignment #4 Binary Trees in C++ Programming Assignment #4 Binary Trees in C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie,

More information

CS3215. Outline: 1. Introduction 2. C++ language features 3. C++ program organization

CS3215. Outline: 1. Introduction 2. C++ language features 3. C++ program organization CS3215 C++ briefing Outline: 1. Introduction 2. C++ language features 3. C++ program organization CS3215 C++ briefing 1 C++ versus Java Java is safer and simpler than C++ C++ is faster, more powerful than

More information

C++ Exception Handling 1

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

More information

CS201 Latest Solved MCQs

CS201 Latest Solved MCQs 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

Iterators. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Iterators. Professor Hugh C. Lauer CS-2303, System Programming Concepts Iterators 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 Savitch,

More information

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 1 OPERATOR OVERLOADING KOM3191 Object-Oriented Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 2 Dynamic Memory Management

More information

Introduction to C++ Introduction to C++ 1

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

More information

Ch02. True/False Indicate whether the statement is true or false.

Ch02. True/False Indicate whether the statement is true or false. Ch02 True/False Indicate whether the statement is true or false. 1. The base class inherits all its properties from the derived class. 2. Inheritance is an is-a relationship. 3. In single inheritance,

More information

Object-Oriented Programming

Object-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 information

Chapter 18 - C++ Operator Overloading

Chapter 18 - C++ Operator Overloading Chapter 18 - C++ Operator Overloading Outline 18.1 Introduction 18.2 Fundamentals of Operator Overloading 18.3 Restrictions on Operator Overloading 18.4 Operator Functions as Class Members vs. as friend

More information

CSE 303: Concepts and Tools for Software Development

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

More information

Motivation for Templates

Motivation 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 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

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED Outline - Function Definitions - Function Prototypes - Data

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

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

AN OVERVIEW OF C++ 1

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

More information

CSCE 110 PROGRAMMING FUNDAMENTALS

CSCE 110 PROGRAMMING FUNDAMENTALS CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class Prof. amr Goneid, AUC 1 Dictionaries(1): A Key Table Class Prof. Amr Goneid, AUC 2 A Key Table

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

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year Object Oriented Programming Assistant Lecture Omar Al Khayat 2 nd Year Syllabus Overview of C++ Program Principles of object oriented programming including classes Introduction to Object-Oriented Paradigm:Structures

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

Object Oriented Design

Object Oriented Design Object Oriented Design Lecture 3: Introduction to C++ (Continue) Examples using declarations that eliminate the need to repeat the std:: prefix 1 Examples using namespace std; enables a program to use

More information

Chapter 7: Stacks. Exercises 7.2

Chapter 7: Stacks. Exercises 7.2 hapter 7: Stacks Exercises 7.2 1. mytop == 0; myrray contains 3 elements: 10, 22, 37,?,? but note that only element 10 is considered to be in the stack. 2. mytop == 1; myrray contains 3 elements: 10, 9,

More information

Linked Lists in C and C++

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

More information

Lecture 5. Function Pointers

Lecture 5. Function Pointers Lecture 5 Pointers to functions Complicated declarations Allocating and deallocating memory Classes const member functions Constructors and destructor this pointer static members Templates Lec 5 Programming

More information

Lecture 18 Tao Wang 1

Lecture 18 Tao Wang 1 Lecture 18 Tao Wang 1 Abstract Data Types in C++ (Classes) A procedural program consists of one or more algorithms that have been written in computerreadable language Input and display of program output

More information

Object Oriented Programming COP3330 / CGS5409

Object Oriented Programming COP3330 / CGS5409 Object Oriented Programming COP3330 / CGS5409 Intro to Data Structures Vectors Linked Lists Queues Stacks C++ has some built-in methods of storing compound data in useful ways, like arrays and structs.

More information

Generic Programming: Overloading and Templates

Generic Programming: Overloading and Templates H.O. #9 Fall 2015 Gary Chan Generic Programming: Overloading and Templates N:9; D:6,11,14 Outline Function overloading Operator overloading and copy constructor An example on string Function templates

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

Computer Programming with C++ (21)

Computer Programming with C++ (21) Computer Programming with C++ (21) Zhang, Xinyu Department of Computer Science and Engineering, Ewha Womans University, Seoul, Korea zhangxy@ewha.ac.kr Classes (III) Chapter 9.7 Chapter 10 Outline Destructors

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

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

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

More information

Chapter 16. Templates. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Chapter 16. Templates. Copyright 2010 Pearson Addison-Wesley. All rights reserved Chapter 16 Templates Copyright 2010 Pearson Addison-Wesley. All rights reserved Learning Objectives Function Templates Syntax, defining Compiler complications Class Templates Syntax Example: array template

More information

First Examination. CS 225 Data Structures and Software Principles Spring p-9p, Tuesday, February 19

First Examination. CS 225 Data Structures and Software Principles Spring p-9p, Tuesday, February 19 Department of Computer Science First Examination CS 225 Data Structures and Software Principles Spring 2008 7p-9p, Tuesday, February 19 Name: NetID: Lab Section (Day/Time): This is a closed book and closed

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

Introduction to Programming session 24

Introduction to Programming session 24 Introduction to Programming session 24 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2010 These slides are created using Deitel sslides Sharif Universityof Technology Outlines Introduction

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

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination University of Illinois at Urbana-Champaign Department of Computer Science First Examination CS 225 Data Structures and Software Principles Spring 2007 7p-9p, Thursday, March 1 Name: NetID: Lab Section

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

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

More information

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

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

Fast Introduction to Object Oriented Programming and C++

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

More information

Chapter 1: Object-Oriented Programming Using C++

Chapter 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 information

Operator overloading

Operator overloading 1 Introduction 2 The copy constructor 3 Operator Overloading 4 Eg 1: Adding two vectors 5 The -> operator 6 The this pointer 7 Overloading = 8 Unary operators 9 Overloading for the matrix class 10 The

More information

Interview Questions of C++

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

More information

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

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination University of Illinois at Urbana-Champaign Department of Computer Science First Examination CS 225 Data Structures and Software Principles Spring 2007 7p-9p, Thursday, March 1 Name: NetID: Lab Section

More information

eingebetteter Systeme

eingebetteter Systeme Praktikum: Entwicklung interaktiver eingebetteter Systeme C++-Tutorial (falk@cs.fau.de) 1 Agenda Classes Pointers and References Functions and Methods Function and Operator Overloading Template Classes

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II Introduction to C++ Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 20, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February

More information

C and C++ 7. Exceptions Templates. Alan Mycroft

C and C++ 7. Exceptions Templates. Alan Mycroft C and C++ 7. Exceptions Templates Alan Mycroft University of Cambridge (heavily based on previous years notes thanks to Alastair Beresford and Andrew Moore) Michaelmas Term 2013 2014 1 / 20 Exceptions

More information