Lesson 25 Miscellaneous Topics

Slides:



Advertisements
Similar presentations
Brown Bag #2 Advanced C++. Topics  Templates  Standard Template Library (STL)  Pointers and Smart Pointers  Exceptions  Lambda Expressions  Tips.
Advertisements

Chapter 8 Scope, Lifetime and More on Functions. Definitions Scope –The region of program code where it is legal to reference (use) an identifier Three.
Lecture 3 Feb 4 summary of last week’s topics and review questions (handout) Today’s goals: Chapter 1 overview (sections 1.4 to 1.6) c++ classes constructors,
CSE 332: C++ Classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
CMSC 202 Lesson 23 Templates II. Warmup Write the templated Swap function _______________________________ void Swap( ________ a, ________ b ) { _______________.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Learners Support Publications Classes and Objects.
C++ Programming Part 2 Michael Griffiths Corporate Information and Computing Services The University of Sheffield
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
1 Lecture 14 Functions Functions with Empty Parameter Lists Empty parameter lists  void or leave parameter list empty  Indicates function takes.
Introduction to C Programming Lecture 6. Functions – Call by value – Call by reference Arrays Today's Lecture Includes.
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Programming II Array of objects. this Using the this Pointer this Objects use the this pointer implicitly or explicitly. – this is – this is used implicitly.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.15Functions with Empty Parameter Lists 3.16Inline Functions 3.17References.
CMSC 202 Lesson 6 Functions II. Warmup Correctly implement a swap function such that the following code will work: int a = 7; int b = 8; Swap(a, b); cout.
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
Current Assignments Project 3 has been posted, due next Tuesday. Write a contact manager. Homework 6 will be posted this afternoon and will be due Friday.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
1 Another Example: Complex Class #ifndef _Complex_H #define _Complex_H class Complex { float re, im; // by default private public: Complex(float x = 0,
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
CMSC 202 Lesson 26 Miscellaneous Topics. Warmup Decide which of the following are legal statements: int a = 7; const int b = 6; int * const p1 = & a;
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Templates Linked Lists.
CMSC 202 Lesson 9 Classes III. Warmup Using the following part of a class, implement the Sharpen() method, it removes 1 from the length: class Pencil.
Chapter 15 - C++ As A "Better C"
Motivation for Generic Programming in C++
Pointer to an Object Can define a pointer to an object:
Procedural and Object-Oriented Programming
Programming with ANSI C ++
Chapter 6 CS 3370 – C++ Functions.
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
CS 215 Final Review Ismail abumuhfouz Fall 2014.
C++ Templates.
Lecture 7-2 : STL Iterators
Introduction to C++ Systems Programming.
Review: Two Programming Paradigms
Introduction to Classes
Chapter 5 Classes.
CS Computer Science IB: Object Oriented Programming
CS212: Object Oriented Analysis and Design
Templates II CMSC 202.
Tuesday, February 20, 2018 Announcements… For Today… 4+ For Next Time…
– Introduction to Object Technology
Prof. Michael Neary Lecture 7: The STL Prof. Michael Neary
Lecture 4-7 Classes and Objects
(5 - 1) Object-Oriented Programming (OOP) and C++
Lecture 7-2 : STL Iterators
ADT Implementations: Templates and Standard Containers
Introduction to Classes
Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.
Constructors and Other Tools
Dr. Bhargavi Dept of CS CHRIST
Classes and Objects.
Lesson 26 Miscellaneous Topics
Namespaces How Shall I Name Thee?.
(5 - 1) Object-Oriented Programming (OOP) and C++
Lists - I The List ADT.
Lists - I The List ADT.
Iterators and STL Containers
7 Arrays.
Lecture 8-2 : STL Iterators and Algorithms
Arrays Arrays A few types Structures of related data items
Submitted By : Veenu Saini Lecturer (IT)
C++ Templates CSE 333 Autumn 2018
CMSC 202 Lesson 6 Functions II.
C++ Templates CSE 333 Winter 2019
Templates CMSC 202, Version 4/02.
C++ Templates L04 - Iterator 10 – Iterator.
Presentation transcript:

Lesson 25 Miscellaneous Topics CMSC 202 Lesson 25 Miscellaneous Topics

Warmup User iterators to print each item in a vector: ____________________________________________________________ for ( ______________________________________________________ ) cout << ________________ << endl; vector<int> integers; // assume we initialize this… vector<int>::iterator iter; iter = integers.begin(); iter != integers.end(); ++iter *iter

Inline Functions Problem Solution Drawbacks? Calling a 1-line function is inefficient Solution Inline functions Compiler replaces function call with function body Drawbacks? Mix definition and implementation Make executables bigger (ack!)

Writing Inline Functions 2 ways Put the function body in the class definition class A { public: int GetData() { return data; } private: int data; }; Put keyword ‘inline’ before the signature line inline void foobar() /* some code */ }

Friend Classes Problem: Solution: Drawbacks: Class A relies heavily on Class b Tightly coupled – lots of interconnectivity Both classes required to represent 1 data structure Inefficient to use methods to access data Solution: Declare Class A as a friend of Class B State that Class A has access to private data of Class B Drawbacks: “Break” Encapsulation and Information Hiding

Friend Classes template < class T > class List<T>; // a "forward declaration" template< class T > class Node { private: Node( ); Node* m_next; int m_data; friend class List<T>; }; template < class T > class List { public: List( ); // other public stuff private: Node<T> *m_header; };

Nested Classes Same Problem – tightly coupled classes Solution: Class defined INSIDE of another class If private? Entirely hidden from everyone else If public? Accessible THROUGH the outer-class

Nested Classes Node is “nested” inside of List class template< class T > class List { public: List( ) { m_header = NULL; } // other public stuff private: template < class T1 > class Node Node( ); Node<T1>* m_next; int m_data; }; Node<T> *m_header; Node is “nested” inside of List class If it were public, the Node’s classname (and type!) would be: List<T>::Node<T> The node is scoped INSIDE the List class…

Namespaces Problem: Solution: Your class-names, function-names, or variable-names clash with existing names Example: You want your own ‘cout’ object You want to define your own ‘vector’ class Solution: Namespaces Groups of classes, functions, or variables Allow you to specify exactly which version Kind of like overloading…

Namespaces Assume ‘Fred’ is a namespace… There are different ways to use Fred… Using everything from a namespace using namespace Fred; Use only ‘f’ from Fred using Fred::f; Qualify each use of something from Fred Fred::f() Instead of just f() Example: using namespace std; using std::string; std::string myString = “Hello World!”; std::cout << myString << std::endl;

Creating a Namespace Really simple… Example: namespace <name> { /* functions, classes, or variables */ } Example: namespace CMSC202

Constants and Pointers Problem: What happens with the following? const int age = 42; int *pAge = &age; *pAge = 57; Solution: Pointers to Constants int age2 = 37; const int *pAge = &age; // OK! *pAge = 57; // compiler error! pAge = & age2; // OK!

Const Pointers Problem: Solution Want to define a pointer that cannot be changed i.e. it cannot point to a different object! Solution Const Pointers int width = 56; int length = 42; int *const pLength = & length; // initialized, unchangeable *pLength = 86; // ok - length is not const pLength = &height; // error - pLength is const

Const Pointer, Const Object Problem: Can we make an unmovable pointer that points to an unchangeable object? Solution: Const Pointer to a Const Object…(ack!) int size = 43; // non-const int const int weight = 89; // const int const int *const pWeight = &weight; // const pointer to a const int *pWeight = 88; // compiler error pWeight = &size; // compiler error cout << *pWeight << endl; // ok - just //dereferencing

Consts and Pointers… 4 different ways: int *pInt; const int *pInt; int *const pInt; const int *const pInt; What do each of these mean??? Hint: read from the “inside” to the “outside… Pointer to integer Pointer to constant integer Constant pointer to integer Constant pointer to constant integer

STL Algorithms STL provides many algorithms for use with container classes #include <algorithm> Some are: for_each() – performs a function on each item Pass by reference if you want to change the item transform() – performs for_each, but stores result in another container fill() – fills every item with a supplied value replace() – replaces a subset of the items with value sort() – uses Quicksort to sort items based on some comparison function

Examples Assume appropriate containers exist… Square, print, and GreaterThan are user-defined functions (i.e. you must write them!) for_each( myList.begin(), myList.end(), square ); for_each( myList.begin(), myList.end(), print ); transform( v1.begin(), v1.end(), v2.begin(), square); fill( vString.begin() + 1, vString.begin() + 3, "tommy"); replace( vString.begin(), vString.end(), string("steve"), string("bill")); sort( v1.begin(), v1.end()); // default, uses operator< sort( v1.begin(), v1.end(), GreaterThan);

Function Objects Problem: Solution: Can we dynamically build functions at runtime? Solution: Function Objects Classes (objects) that behave like functions Overloading the operator( ) I told you it was possible!

Function Objects Why? Functions that have more properties than just the operator() Can store a state Separate copies, each with own state Can be initialized in constructor

Code in lecture notes used ‘set’ instead of ‘vector’. Function Objects Code in lecture notes used ‘set’ instead of ‘vector’. Why won’t that work? int main ( ) { vector<int> iVector; // insert some data for (int i = 1; i < 10; i++) iVector.push_back( int(i) ); // print elements // 1 2 3 4 5 6 7 8 9 // create a function adds 42 to parameter Add add42( 42 ); // add 42 to each element of the set for_each( iVector.begin(), iVector.end(), add42); // print the elements // 43 44 45 46 47 48 49 50 51 iVector.end(), print); }; class Add { public: // const Add (int value) : m_value( value ) { }; void operator( ) (int& n ) const n += m_value; } private: int m_value; // value to add }; void print(const int& i) cout << i << endl;

Function Objects Key understanding: Create functions on the fly! Often used in Artifical Intelligence applications! class RNG // Random Number Generator { public: RNG (unsigned int seed = 1) : m_lastValue( seed ), m_seed( seed ) { srand(seed); } unsigned int operator( ) () // modify last Value for new value m_lastValue += rand() % m_seed; return m_lastValue; } private: unsigned int m_lastValue; unsigned int m_seed; }; int main ( ) { RNG rng ( 42 ); for (int i = 0; i < 10; i++) cout << rng() << endl; }

Practice Which of the following is legal? Assume that illegal statements are skipped… BeachBall a(7.0); BeachBall b(6.0); const BeachBall c(5.0); const BeachBall* p = &a; BeachBall* const q = &b; p->SetRadius(1.0); // 1 q->SetRadius(2.0); // 2 p = &c; // 3 q = &c; // 4 p->SetRadius(1.0); // 5 q->SetRadius(2.0); // 6

Challenge Use a Function Object to create a function that computes the polynomial of its parameter n2, n3, n4, … Exponent is parameter in constructor Use for_each to compute the square and cube of each float in a vector