G52CPP C++ Programming Lecture 18. Dr Jason Atkin
|
|
- Milton Strickland
- 6 years ago
- Views:
Transcription
1 G52CPP C++ Programming Lecture 18 Dr Jason Atkin 1
2 Last lecture Operator Overloading Strings and streams 2
3 Operator overloading - what to know Know that you can change the meaning of operators Know that operator overloading is available as both a member function version and a global (non-member) function version Be able to provide the code for the overloading of an operator Parameter types, const? Return type Simple implementations 3
4 Questions to ask yourself Define as a member or as a global? If global then does it need to be a friend? What should the parameter types be? References? Make them const if you can What should the return type be? Should it return *this? Does it need to return a copy of the object? e.g. post-increment must return a copy Should the function be const? 4
5 My string comparison operator bool operator==( const std::string& s1, const std::string& s2) return 0 == strcmp( s1.c_str(), s2.c_str() ); } Get the string as a char array int main () string str1( "Same" ); string str2( "Same" ); string str3( "Diff" ); printf( "str1 and str2 are %s\n", (str1 == str2)? "Same" : "Diff" ); printf( "str1 and str3 are %s\n", (str1 == str3)? "Same" : "Diff" ); printf( "str2 and str3 are %s\n", (str2 == str3)? "Same" : "Diff" ); } 5
6 streams for input/output C++ input/output classes use streams Three standard stream objects exist already istream cin; (matches stdin) ostream cout; (matches stdout) ostream cerr; (matches stderr) Header file includes the declarations: #include <iostream> They are in std namespace Use std::cin, std::cout, etc >> and << operators are overloaded for input and output endl sent to a stream will output \n and flush 6
7 Example of output #include <iostream> using namespace std; Look in std namespace for the names which follow int main() e.g. cin, cout, cerr const char* str = "Test string"; int i = 1; Overloaded operator - input cin >> i; cout << str << " " << i << endl; cerr << str << endl; Header file for input AND output Overloaded operator - output } return 0; 7
8 This lecture Template functions Template Classes Slicing Problem 8
9 Function Overloading We can use function overloading to have multiple versions of the same function Consider the following functions: int mymax( int a, int b ) return a > b? a : b; } float mymax( float a, float b ) return a > b? a : b; } char mymax( char a, char b ) return a > b? a : b; } It would be nice to create just the one 9
10 Template version int mymax( int a, int b ) return a > b? a : b; } float mymax( float a, float b ) return a > b? a : b; } char mymax( char a, char b ) return a > b? a : b; } template < typename T > T mymax( T a, T b ) return a > b? a : b; } 10
11 Template functions Templates specify how to create functions of a certain format, if they are ever needed, e.g.: template < typename T > T mymax( T a, T b ) return a > b? a : b; } Note: you can use keyword class or typename : i.e. template < class T > Type placeholders are used, and are replaced implicitly Could use it as any type, e.g.: int i1 = 4, i2 = 14; int i3 = mymax( i1, i2 ); 11
12 What templates do The compiler will actually generate the functions which are needed, according to the parameters i.e. at compile time, new functions are created If there are any problems, it will not compile e.g. if new template class needs a function or operator which is not supported by the type This is NOT something done at runtime 12
13 Example for mymax #include <iostream> using namespace std; template < typename T > T mymax( T a, T b ) return a > b? a : b; } So that compiler knows what cout is when we use it later (and what endl is) int main() int i1 = 4, i2 = 14; int i3 = mymax( i1, i2 ); cout << "mymax(" << i1 << "," << 12 << ") = " << i3 << endl; } 13
14 Compiler generates a function #include <iostream> using namespace std; template < typename T > T mymax( T a, T b ) return a > b? a : b; } int mymax( int a, int b ) int main() return a > b? a : b; } int i1 = 4, i2 = 14; int i3 = mymax( i1, i2 ); cout << "mymax(" << i1 << "," << 12 << ") = " << i3 << endl; 14 }
15 How to create template functions The easy way to create these template functions: First manually generate a function for specific types Next replace all copies of the types by an identifier Then add the keyword template at the beginning and put the type(s) in the <> with keyword typename (or class) For example, an addition with casting function: int addcast( int a, float b ) return a + static_cast<int>(b); } Becomes: template <typename T1, typename T2> T1 addcast( T1 a, T2 b ) return a + static_cast<t1>(b); } And can be used as: int val = addcast( 12, 4.65 ); 15
16 Example of addcast<t1,t2> #include <iostream> // cout using namespace std; template <typename T1, typename T2> T1 addcast( T1 a, T2 b ) return a + static_cast<t1>(b); } Creates a version which changes the float to an int and adds them int main() int val = addcast( 12, 4.65 ); cout << 12 << "+" << 4.65 << "=" << val << endl; } return 0; 16
17 Question: Will this compile? #include <iostream> using namespace std; template <typename T1, typename T2> T1 addcast( T1 a, T2 b ) return a + static_cast<t1>(b); } class MyFloat public: MyFloat( float f ) : f(f) } float f; }; Code in main: MyFloat f1(1.1); float f2 = 2.2; MyFloat f3 = addcast(f1,f2); cout << f3.f << endl; 17
18 The compilation error template <typename T1, typename T2> T1 addcast( T1 a, T2 b ) return a + static_cast<t1>(b); } class MyFloat public: MyFloat( float f ) : f(f) } MyFloat f1(1.1); float f2 = 2.2; MyFloat f3 = addcast(f1,f2); cout << f3.f << endl; template1.cpp: In function T1 addcast(t1, T2) float f; [with T1 = MyFloat, T2 = float] : }; template1.cpp:32:28: instantiated from here template1.cpp:7:31: error: no match for operator+ in a + MyFloat(b) 18
19 Add an operator+ template <typename T1, typename T2> T1 addcast( T1 a, T2 b ) return a + static_cast<t1>(b); } class MyFloat public: MyFloat( float f ) : f(f) } MyFloat f1(1.1); float f2 = 2.2; MyFloat f3 = addcast(f1,f2); cout << f3.f << endl; MyFloat float operator+( f; const MyFloat& f1, const MyFloat& f2) }; MyFloat f( f1.f + f2.f ); return f; } 19
20 Template classes 20
21 Template class You can make template forms of entire classes as well as individual functions Again the typename placeholder name (e.g. T) is replaced throughout the class You need to use it in both the class declaration and the member function implementations To alter class definition: Add template <typename T> at the start, as for template functions Then replace the templated type throughout the code 21
22 Template class : linked list class MyLinkedList struct Entry struct Entry* pnext; int idata; }; Entry* _phead; public: MyLinkedList() : _phead(null) } void InsertHead( int idata ); template < typename T > class MyLinkedList struct Entry struct Entry* pnext; T tdata; }; Entry* _phead; public: MyLinkedList() : _phead(null) } void InsertHead( T tdata ); }; void List(); }; void List(); 22
23 How to alter member functions Add prior to each member function definition: template <typename T> Add the <T> to the end of the class name in the member function implementation/definition: Example member function implementation: template <typename T> void MyLinkedList<T>::Store(T tdata) } Find each occurrence of the templated type and replace it by the templated type name e.g. replace int with T in the example Note: typename can be replaced by class 23
24 The member functions void MyLinkedList:: InsertHead(int idata) Entry* pnewentry = new Entry(); pnewentry->idata = idata; pnewentry->pnext = _phead; _phead = pnewentry; } void MyLinkedList::List() Entry* pentry = _phead; while( pentry!= NULL ) cout << pentry->idata << endl; pentry = pentry->pnext; } } template <typename T> void MyLinkedList<T>:: InsertHead(T tdata) Entry* pnewentry = new Entry(); pnewentry->tdata = tdata; pnewentry->pnext = _phead; _phead = pnewentry; } template <typename T> void MyLinkedList<T>::List() Entry* pentry = _phead; while( pentry!= NULL ) cout << pentry->tdata << endl; pentry = pentry->pnext; } } 24
25 Using the template class int test1() MyLinkedList<float> olist; olist.inserthead( 1.1 ); olist.inserthead( 2.2 ); olist.inserthead( 3.3 ); olist.inserthead( 4.4 ); olist.inserthead( 5.5 ); olist.inserthead( 6.6 ); olist.list(); } int test2() MyLinkedList<string> olist; olist.inserthead( "Adam" ); olist.inserthead( "Brian" ); olist.inserthead( "Carl" ); olist.inserthead( "Dave" ); olist.inserthead( "Eric" ); olist.inserthead( "Fred" ); // Following line would not compile: //olist.inserthead( 1.2 ); olist.list(); } The class name is qualified with a type in angled brackets. Once specified, the type is fixed. Instantiations of the class are generated by the compiler as needed. 25
26 Exam: do I need to know all of this? Template functions Be able to recognise them Know what they do Be able to convert from a normal function to a template version Know the difference between a template function and a macro (#define) And the dangers of using #define Template classes Recognise them Be able to understand code which uses them Understand code using STL classes 26
27 ReminderL STL container classes vector string map list set stack queue deque multimap multiset In std namespace Know that Standard Template Library exists If you go for C++ job interview, learn basics These are template classes e.g. vector<int> for vector of ints Also have iterators Track position/index in a container e.g. to iterate through a container And algorithms (over 70 of them) Apply to containers e.g. min(), max(), sort(), search() 27
28 Dangers of arrays And of STL containers Same problems apply 28
29 Example of using vector #include <iostream> #include <string> #include <vector> using namespace std; int main() vector<char> v(10); // 10 elements int size = v.size(); cout << "Size " << size << endl; } // Set each value for( int i=0 ; i < size ; i++ ) v[i] = i; // Iterate through vector vector<char>::iterator p = v.begin(); for( ; p!= v.end() ; p++ ) *p += 97; // Output the contents for( int i=0 ; i < size ; i++ ) cout << v[i] << endl; return 0; 29
30 Arrays of pointers #include <iostream> using namespace std; class Base public: Base() : i(1) } virtual void out() cout <<"Base" <<i <<endl; } int i; }; class Sub : public Base public: Sub() i = 2; } void out() cout <<"Sub" <<i <<endl; } }; Lec18a.cpp int main() Sub* arrayp1[3] = new Sub, new Sub, new Sub }; Base* arrayp2[3] = new Base, new Base, new Base }; // Output Array 1 for ( int i = 0 ; i < 3 ; i++ ) arrayp1[i]->out(); // Output Array 2 for ( int i = 0 ; i < 3 ; i++ ) arrayp2[i]->out(); // Copy Array 1 elements to 2 for ( int i = 0 ; i < 3 ; i++ ) arrayp2[i] = arrayp1[i]; // Output Array 2 for ( int i = 0 ; i < 3 ; i++ ) arrayp2[i]->out(); } 30
31 Arrays of pointers #include <iostream> using namespace std; class Base public: Base() : i(1) } virtual void out() cout <<"Base" <<i <<endl; } int i; }; class Sub : public Base public: Sub() i = 2; } void out() cout <<"Sub" <<i <<endl; } }; Lec18a.cpp int main() Sub* arrayp1[3] = new Sub, new Sub, new Sub }; Base* arrayp2[3] = new Base, new Base, new Base }; // Output Array 1 for ( int i = 0 ; i < 3 ; i++ ) Call out() on each object in arrayp1 arrayp1[i]->out(); // Output Array 2 for ( int i = 0 ; i < 3 ; i++ ) Call out() on each object in arrayp2 arrayp2[i]->out(); // Copy Array 1 elements to 2 for ( int i = 0 ; i < 3 ; i++ ) Copy subclass pointers to Base* array arrayp2[i] = arrayp1[i]; // Output Array 2 for ( int i = 0 ; i < 3 ; i++ ) Call out() on each object in arrayp2 i.e. the arrayp2[i]->out(); Base* array, with Sub* objects } 31
32 Objects are not pointers #include <iostream> using namespace std; class Base public: Base() : i(1) } virtual void out() cout <<"Base" <<i <<endl; } int i; }; class Sub : public Base public: Sub() i = 2; } void out() cout <<"Sub" <<i <<endl; } }; Lec18b.cpp int main() Sub array1[3]; Base array2[3]; // Output Array 1 Arrays of objects for ( int i = 0 ; i < 3 ; i++ ) array1[i].out(); // Output Array 2 for ( int i = 0 ; i < 3 ; i++ ) array2[i].out(); // Copy array 1 to 2 for ( int i = 0 ; i < 3 ; i++ ) array2[i] = array1[i]; // Output Array 2 for ( int i = 0 ; i < 3 ; i++ ) array2[i].out(); } 32
33 Objects are not pointers #include <iostream> using namespace std; class Base public: Base() : i(1) } virtual void out() cout <<"Base" <<i <<endl; } int i; }; class Sub : public Base public: Sub() i = 2; } void out() cout <<"Sub" <<i <<endl; } }; Lec18b.cpp int main() Sub array1[3]; Base array2[3]; // Output Array 1 for ( int i = 0 ; i < 3 ; i++ ) array1[i].out(); // Output Array 2 for ( int i = 0 ; i < 3 ; i++ ) array2[i].out(); // Copy array 1 to 2 for ( int i = 0 ; i < 3 ; i++ ) array2[i] = array1[i]; Arrays of objects Call out() on each object in arrayp1 Call out() on each object in arrayp2 Copy subclass OBJECTS to Base array // Output Array 2 for Call ( out() int on i = each 0 ; object i < 3 in ; array2 i++ ) i.e. array2[i].out(); the Base array, after Sub copy } 33
34 The slicing problem In that example, we stored base class objects So when we tried to assign sub-class objects only the base class part was stored We sliced off the sub-class part This may be obvious, but things can get worse 34
35 What is the slicing problem? Passing an object type parameter by value uses the copy constructor i.e. copies it Assigning an object to another object copies the values, using the assignment operator If the thing you are copying to is a base class object (or thinks it is!) the base class assignment operator is used Neither the default copy constructor nor assignment operator are virtual The base class version gets used!!! Just making them virtual would not help anyway see lecture 20 The slicing problem occurs when you treat a sub-class as the base class for a copy/assignment Only the base class parts get copied i.e. the sub-class parts are sliced off 35
36 How can it happen? By using references or pointers, e.g.: class BaseClass int main() public: SubClass s1, s2; int MyParam; }; BaseClass& rs1 = s1; BaseClass& rs2 = s2; class SubClass rs1 = rs2; : public BaseClass BaseClass* ps1 = &s1; public: BaseClass* ps2 = &s2; int MySubClassParam; *ps1 = *ps2; }; } The sub-class part will not be copied 36
37 Why? The slicing problem occurs when you treat a sub-class as the base class for a copy/assignment Only the base class parts get copied i.e. the sub-class parts are sliced off A function like this was created and used: Base& operator=(const Base& rhs ) } this->myparam = rhs.myparam; return *this; Rather than using the sub-class version: SubClass& operator=(const SubClass& rhs ) this->mysubclassparam = rhs.mysubclassparam; } this->myparam = rhs.myparam; return *this; 37
38 This week and beyond Tuesday 9am, some templates, operator overloads, etc Plus any questions, coursework or otherwise? Friday 28 th March, Lecture 19 When is a duck an instrument? (Multiple Inheritance) And the SET/SEM assessment for last 1/3 of lecture Monday 31 st March: Lecture 20 (last content lecture) Wrapping up (slicing problem, smart pointers) Tuesday 1 st April, 9am demo lecture is replaced by lab time to work on coursework : I will go to the A32 lab to answer questions Friday (4 th April): Revision Lecture and exam strategy On the following week I will go to the A32 lab for the Monday (7 th 5pm) and Tuesday (8 th 9am) lecture slots Coursework deadline: 4pm Tuesday 8 th April 38
G52CPP C++ Programming Lecture 18
G52CPP C++ Programming Lecture 18 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Welcome Back 2 Last lecture Operator Overloading Strings and streams 3 Operator overloading - what to know
More informationG52CPP C++ Programming Lecture 20
G52CPP C++ Programming Lecture 20 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Wrapping up Slicing Problem Smart pointers More C++ things Exams 2 The slicing problem 3 Objects are not
More informationG52CPP C++ Programming Lecture 17
G52CPP C++ Programming Lecture 17 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last Lecture Exceptions How to throw (return) different error values as exceptions And catch the exceptions
More informationG52CPP C++ Programming Lecture 14. Dr Jason Atkin
G52CPP C++ Programming Lecture 14 Dr Jason Atkin 1 Last Lecture Automatically created methods: A default constructor so that objects can be created without defining a constructor A copy constructor used
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 informationTHE STANDARD TEMPLATE LIBRARY (STL) Week 6 BITE 1513 Computer Game Programming
THE STANDARD TEMPLATE LIBRARY (STL) Week 6 BITE 1513 Computer Game Programming What the heck is STL???? Another hard to understand and lazy to implement stuff? Standard Template Library The standard template
More 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 informationIntroduction to C++ (Extensions to C)
Introduction to C++ (Extensions to C) C is purely procedural, with no objects, classes or inheritance. C++ is a hybrid of C with OOP! The most significant extensions to C are: much stronger type checking.
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 informationCSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington
CSE 333 Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington Administrivia New exercise posted yesterday afternoon, due Monday morning - Read a directory
More informationG52CPP C++ Programming Lecture 13
G52CPP C++ Programming Lecture 13 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture Function pointers Arrays of function pointers Virtual and non-virtual functions vtable and
More informationTopics. bool and string types input/output library functions comments memory allocation templates classes
C++ Primer C++ is a major extension of c. It is similar to Java. The lectures in this course use pseudo-code (not C++). The textbook contains C++. The labs involve C++ programming. This lecture covers
More informationCAAM 420 Fall 2012 Lecture 29. Duncan Eddy
CAAM 420 Fall 2012 Lecture 29 Duncan Eddy November 7, 2012 Table of Contents 1 Templating in C++ 3 1.1 Motivation.............................................. 3 1.2 Templating Functions........................................
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 informationG52CPP C++ Programming Lecture 9
G52CPP C++ Programming Lecture 9 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture const Constants, including pointers The C pre-processor And macros Compiling and linking And
More informationCS3157: Advanced Programming. Outline
CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching
More informationC++ basics Getting started with, and Data Types.
C++ basics Getting started with, and Data Types pm_jat@daiict.ac.in Recap Last Lecture We talked about Variables - Variables, their binding to type, storage etc., Categorization based on storage binding
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 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 informationType Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works
Type Aliases A name may be defined as a synonym for an existing type name. Traditionally, typedef is used for this purpose. In the new standard, an alias declaration can also be used C++11.Thetwoformsareequivalent.
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 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 informationThis is a CLOSED-BOOK-CLOSED-NOTES exam consisting of five (5) questions. Write your answer in the answer booklet provided. 1. OO concepts (5 points)
COMP152H Object Oriented Programming and Data Structures Spring Semester 2011 Midterm Exam March 22, 2011, 9:00-10:20am in Room 3598 Instructor: Chi Keung Tang This is a CLOSED-BOOK-CLOSED-NOTES exam consisting
More informationThe University of Nottingham
The University of Nottingham SCHOOL OF COMPUTER SCIENCE A LEVEL 2 MODULE, AUTUMN SEMESTER 2009-2010 C/C++ for Java Programmers Time allowed TWO hours Candidates may complete the front cover of their answer
More informationG52CPP C++ Programming Lecture 16
G52CPP C++ Programming Lecture 16 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last Lecture Casting static cast dynamic cast const cast reinterpret cast Implicit type conversion 2 How
More informationModule 9. Templates & STL
Module 9 Templates & STL Objectives In this module Learn about templates Construct function templates and class templates STL 2 Introduction Templates: enable you to write generic code for related functions
More informationEL2310 Scientific Programming
Lecture 14: Object Oriented Programming in C++ (fpokorny@kth.se) Overview Overview Lecture 14: Object Oriented Programming in C++ Wrap Up Introduction to Object Oriented Paradigm Classes More on Classes
More informationCSE 333 Lecture 9 - intro to C++
CSE 333 Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington Administrivia & Agenda Main topic: Intro to C++ But first: Some hints on HW2 Labs: The
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 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 informationCSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 19 Introduction to C++ C++ C++ is an enormous language: All of C Classes and objects (kind of like Java, some crucial differences) Many
More informationLambda functions. Zoltán Porkoláb: C++11/14 1
Lambda functions Terminology How it is compiled Capture by value and reference Mutable lambdas Use of this Init capture and generalized lambdas in C++14 Constexpr lambda and capture *this and C++17 Zoltán
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 informationCSE 333 Lecture smart pointers
CSE 333 Lecture 14 -- smart pointers Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington Administrivia New exercise out today, due Wednesday morning Exam Friday
More informationG52CPP C++ Programming Lecture 12
G52CPP C++ Programming Lecture 12 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture this and static members References Act like pointers Look like values More const And mutable
More informationW3101: Programming Languages C++ Ramana Isukapalli
Lecture-6 Operator overloading Namespaces Standard template library vector List Map Set Casting in C++ Operator Overloading Operator overloading On two objects of the same class, can we perform typical
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 informationstruct Buffer { Buffer(int s) { buf = new char[s]; } ~Buffer() { delete [] buf; } char *buf; };
struct Buffer { Buffer(int s) { buf = new char[s]; ~Buffer() { delete [] buf; char *buf; ; struct FBuffer : public Buffer { FBuffer(int s) : Buffer(s) { f = fopen("file", "w"); ~FBuffer() { fclose(f);
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 informationMore on Templates. Shahram Rahatlou. Corso di Programmazione++
More on Templates Standard Template Library Shahram Rahatlou http://www.roma1.infn.it/people/rahatlou/programmazione++/ it/ / h tl / i / Corso di Programmazione++ Roma, 19 May 2008 More on Template Inheritance
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 informationCSE 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 informationCSE 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 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 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 informationCOEN244: 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 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 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 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 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 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 information(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University
(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University Key Concepts 2 Object-Oriented Design Object-Oriented Programming
More informationLogistics. Templates. Plan for today. Logistics. A quick intro to Templates. A quick intro to Templates. Project. Questions? Introduction to Templates
Logistics Templates Project Part 1 (clock and design) due Sunday, Sept 25 th Start thinking about partners for Parts 2-3 Questions? Logistics Important date: THURSDAY is Exam 1 Will cover: C++ environment
More informationReview Questions for Final Exam
CS 102 / ECE 206 Spring 11 Review Questions for Final Exam The following review questions are similar to the kinds of questions you will be expected to answer on the Final Exam, which will cover LCR, chs.
More informationProgramming in C++: Assignment Week 8
Programming in C++: Assignment Week 8 Total Marks : 20 September 9, 2017 Question 1 Consider the following code segment. Mark 2 void myfunction(int test) { try { if (test) throw test; else throw "Value
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 informationComputer Science II Lecture 2 Strings, Vectors and Recursion
1 Overview of Lecture 2 Computer Science II Lecture 2 Strings, Vectors and Recursion The following topics will be covered quickly strings vectors as smart arrays Basic recursion Mostly, these are assumed
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 informationLecture 8. Xiaoguang Wang. February 13th, 2014 STAT 598W. (STAT 598W) Lecture 8 1 / 47
Lecture 8 Xiaoguang Wang STAT 598W February 13th, 2014 (STAT 598W) Lecture 8 1 / 47 Outline 1 Introduction: C++ 2 Containers 3 Classes (STAT 598W) Lecture 8 2 / 47 Outline 1 Introduction: C++ 2 Containers
More 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 informationCours de C++ Introduction
Cours de C++ Introduction Cécile Braunstein cecile.braunstein@lip6.fr Cours de C++ 1 / 20 Généralité Notes Interros cours 1/3 Contrôle TP 1/3 Mini-projet 1/3 Bonus (Note de Participation) jusqu à 2 points
More informationIII. 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 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 informationLab 6. Out: Wednesday 9 March 2005
CS034 Intro to Systems Programming Doeppner & Van Hentenryck What you ll learn. Lab 6 Out: Wednesday 9 March 2005 Modern C++ comes with a powerful template library, the Standard Template Library, or STL.
More informationFile I/O Christian Schumacher, Info1 D-MAVT 2013
File I/O Christian Schumacher, chschuma@inf.ethz.ch Info1 D-MAVT 2013 Input and Output in C++ Stream objects Formatted output Writing and reading files References General Remarks I/O operations are essential
More informationC++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay
C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming
More informationG52CPP C++ Programming Lecture 10. Dr Jason Atkin
G52CPP C++ Programming Lecture 10 Dr Jason Atkin 1 Last lecture Constructors Default constructor needs no parameters Default parameters Inline functions Like safe macros in some ways Function definitions
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 informationAnnouncements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy
CSCI 334: Principles of Programming Languages Lecture 18: C/C++ Homework help session will be tomorrow from 7-9pm in Schow 030A instead of on Thursday. Instructor: Dan Barowy HW6 and HW7 solutions We only
More informationCS
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 informationLecture 14: more class, C++ streams
CIS 330: / / / / (_) / / / / _/_/ / / / / / \/ / /_/ / `/ \/ / / / _/_// / / / / /_ / /_/ / / / / /> < / /_/ / / / / /_/ / / / /_/ / / / / / \ /_/ /_/_/_/ _ \,_/_/ /_/\,_/ \ /_/ \ //_/ /_/ Lecture 14:
More informationCOMP322 - Introduction to C++
COMP322 - Introduction to C++ Lecture 05 - I/O using the standard library, stl containers, stl algorithms Dan Pomerantz School of Computer Science 5 February 2013 Basic I/O in C++ Recall that in C, we
More informationCOMP322 - Introduction to C++ Lecture 01 - Introduction
COMP322 - Introduction to C++ Lecture 01 - Introduction Robert D. Vincent School of Computer Science 6 January 2010 What this course is Crash course in C++ Only 14 lectures Single-credit course What this
More informationDue Date: See Blackboard
Source File: ~/2315/45/lab45.(C CPP cpp c++ cc cxx cp) Input: under control of main function Output: under control of main function Value: 4 Integer data is usually represented in a single word on a computer.
More informationEL2310 Scientific Programming
(pronobis@kth.se) Overview Overview Wrap Up Introduction to Object Oriented Paradigm More on and Members Operator Overloading Last time Intro to C++ Differences between C and C++ Intro to OOP Today Object
More informationIntroduction 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 informationObject 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 informationStandard Library. Lecture 27. Containers. STL Containers. Standard Library
Standard Library Lecture 27 Containers (templates) Streams (I/O facilities) Standard Library Portable, type-safe, efficient Try to use as much as possible Heavy use of templates Streams: #include
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 informationWhat will happen if we try to compile, link and run this program? Do you have any comments to the code?
1 # include < iostream > 2 3 int main () 4 { 5 std :: cout
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 informationTemplates and Vectors
Templates and Vectors 1 Generic Programming function templates class templates 2 the STL vector class a vector of strings enumerating elements with an iterator inserting and erasing 3 Writing our own vector
More 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 informationCSE 333 Lecture smart pointers
CSE 333 Lecture 14 -- smart pointers Hal Perkins Department of Computer Science & Engineering University of Washington Administrivia Midterm Friday - Review in sections this week - Closed book; topic list
More informationList, Stack, and Queues
List, Stack, and Queues R. J. Renka Department of Computer Science & Engineering University of North Texas 02/24/2010 3.1 Abstract Data Type An Abstract Data Type (ADT) is a set of objects with a set of
More informationThe University of Nottingham
The University of Nottingham SCHOOL OF COMPUTER SCIENCE A LEVEL 2 MODULE, AUTUMN SEMESTER 2008 2009 C/C++ for Java Programmers Time allowed TWO hours Candidates may complete the front cover of their answer
More informationCOMP322 - Introduction to C++
COMP322 - Introduction to C++ Winter 2011 Lecture 05 - I/O using the standard library & Introduction to Classes Milena Scaccia School of Computer Science McGill University February 1, 2011 Final note on
More informationPHY4321 Summary Notes
PHY4321 Summary Notes The next few pages contain some helpful notes that summarize some of the more useful material from the lecture notes. Be aware, though, that this is not a complete set and doesn t
More informationSpring 2003 Instructor: Dr. Shahadat Hossain. Administrative Matters Course Information Introduction to Programming Techniques
1 CPSC2620 Advanced Programming Spring 2003 Instructor: Dr. Shahadat Hossain 2 Today s Agenda Administrative Matters Course Information Introduction to Programming Techniques 3 Course Assessment Lectures:
More informationCS11 Advanced C++ Spring 2018 Lecture 1
CS11 Advanced C++ Spring 2018 Lecture 1 Welcome to CS11 Advanced C++! A deeper dive into C++ programming language topics Prerequisites: CS11 Intro C++ track is strongly recommended (obvious) You should
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 informationOperator 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 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 informationDocumentation. Programming / Documentation Slide 42
Documentation http://www.math.upb.de/~robsy/lehre/programmierkurs2008/ Programming / Documentation Slide 42 Memory Management (I) There are several types of memory which a program can access: Stack Every
More information1c) (iv) and (v) OR (v) only (hindsight showed that the question was more ambiguous than intended)
Answers to 2008/2009 G52CFJ exam Below are the answers to last year s exam, so that you can check how you did. In many cases I have given an example answer and an idea of what elements we would look for.
More informationWhere do we go from here?
Lecture 16: C++ Where do we go from here? C++ classes and objects, with all the moving parts visible operator overloading templates, STL, standards, Java Go components, collections, generics language and
More informationPOLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE
Abstract Base Classes POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors class B { // base class virtual void m( ) =0; // pure virtual function class D1 : public
More informationPOLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors
POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors CSC 330 OO Software Design 1 Abstract Base Classes class B { // base class virtual void m( ) =0; // pure virtual
More informationCSS 342 Data Structures, Algorithms, and Discrete Mathematics I. Lecture 2. Yusuf Pisan
CSS 342 Data Structures, Algorithms, and Discrete Mathematics I Lecture 2 Yusuf Pisan Compiled helloworld yet? Overview C++ fundamentals Assignment-1 CSS Linux Cluster - submitting assignment Call by Value,
More informationStructuur van Computerprogramma s 2
Structuur van Computerprogramma s 2 dr. Dirk Deridder Dirk.Deridder@vub.ac.be http://soft.vub.ac.be/ Vrije Universiteit Brussel - Faculty of Science and Bio-Engineering Sciences - Computer Science Department
More information