OOP Etgar 2008 – Recitation 51 Object Oriented Programming Etgar 2008 Recitation 5.

Slides:



Advertisements
Similar presentations
C Language.
Advertisements

The C ++ Language BY Shery khan. The C++ Language Bjarne Stroupstrup, the language’s creator C++ was designed to provide Simula’s facilities for program.
Template. 2 Using templates, it is possible to create generic functions and classes. In a generic function or class, the type of data upon which the function.
Templates in C++. Generic Programming Programming/developing algorithms with the abstraction of types The uses of the abstract type define the necessary.
Review What is a virtual function? What can be achieved with virtual functions? How to define a pure virtual function? What is an abstract class? Can a.
Chapter 17 Templates. Generic Algorithms Algorithms in which the actions or steps are defined, but the data types of the items being manipulated are not.
Templated Functions. Overloading vs Templating  Overloaded functions allow multiple functions with the same name.
Review for Final Exam Dilshad M. NYU. In this review Arrays Pointers Structures Java - some basic information.
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
1 Pointers & functions Pointers allow us to simulate pass by reference. void swap(int &a, int &b) { int temp = a; a = b; b = temp; } int main () { int.
. Templates. Example… A useful routine to have is void Swap( int& a, int &b ) { int tmp = a; a = b; b = tmp; }
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Introduction to C Programming CE
Pointers. Topics Pointers Pointer Arithmetic Pointers and Arrays.
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
OOP Spring 2007 – Recitation 21 Object Oriented Programming Spring 2007 Recitation 2.
OOP Spring 2007 – Recitation 81 Object Oriented Programming Spring 2007 Recitation 8.
OOP Spring 2006 – Recitation 31 Object Oriented Programming Spring 2006 Recitation 3.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
Templates. Example… A useful routine to have is void swap(int &a, int &b){ int tmp = a; a = b; b = tmp; }
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
Intro to Generic Programming Templates and Vectors.
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
LECTURE LECTURE 17 More on Templates 20 An abstract recipe for producing concrete code.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Pointers CS362. Pointers A Pointer is a variable that can hold a memory address Pointers can be used to: Indirectly reference existing variables (sometimes.
CSE 332: C++ Type Programming: Associated Types, Typedefs and Traits A General Look at Type Programming in C++ Associated types (the idea) –Let you associate.
CSC241 Object-Oriented Programming (OOP) Lecture No. 6.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Object Oriented Programming Elhanan Borenstein Lecture #10 copyrights © Elhanan Borenstein.
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.
The Cn Language over view The Cn language strongly on ANSI C. So if you are familiar with ANCI it is not so tough to deal with Cn language. Basic Data.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department.
Object Management. Constructors –Compiler-generated –The Initializer List –Copy Constructors –Single-arg (conversion ctors) The Assignment Operator.
Overview of C++ Templates
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
ENEE150 – 0102 ANDREW GOFFIN Project 4 & Function Pointers.
Functions Sujana Jyothi C++ Workshop Day 2. Functions 3 Parameter transmission modes pass by value (default) pass by reference (&) pass by const reference.
+ Pointers. + Content Address of operator (&) Pointers Pointers and array.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Templates Where the TYPE is generic. Templates for functions Used when the you want to perform the same operation on different data types. The definition.
Cop3530sp12. Parameter passing call by value- appropriate for small objects that should not be altered by the function call by constant reference- appropriate.
Introduction to Computers and Programming Class 24 Structures (structs) Professor Avi Rosenfeld.
1 Parameter passing Call by value The caller evaluates the actual parameters and passes copies of their values to the called function. Changes to the copies.
Object Oriented Programming in C++ Chapter 7 Dynamic Binding.
Programming in C Arrays, Structs and Strings. 7/28/092 Arrays An array is a collection of individual data elements that is:An array is a collection of.
OOP Basics Classes & Methods (c) IDMS/SQL News
CS 31 Discussion, Week 7 Faisal Alquaddoomi, Office Hours: BH 2432, W 4:30-6:30pm, F 12:30-1:30pm.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Copyright © Curt Hill Generic Functions Separating Data Type from Logic.
C++ REVIEW – TEMPLATES. GENERIC PROGRAMMING Programming/developing algorithms with the abstraction of types Algorithms/data is expressed “without type”
Motivation for Generic Programming in C++
User-Written Functions
Pointers and Pointer-Based Strings
Student Book An Introduction
Templates.
Object Oriented Programming COP3330 / CGS5409
CS2011 Introduction to Programming I Methods (II)
Pointers and Pointer-Based Strings
Java Programming Language
Lab4 problems More about templates Some STL
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Presentation transcript:

OOP Etgar 2008 – Recitation 51 Object Oriented Programming Etgar 2008 Recitation 5

OOP Etgar 2008 – Recitation 52 Function Pointers A good tutorial is at

OOP Etgar 2008 – Recitation 53 Can We Increase Grades? Assume we have a list of all student grades for the OOP course, and we would like to increase each and every one of them. The list is in the GradesList data structure that is accessed by GradesList::get(ID) and GradesList::set(ID, grade). Calling get() / set() for each student is tedious. How can we tell the GradesList to apply some function to each of its members?

OOP Etgar 2008 – Recitation 54 The Solution If GradesList had a function GradesList::ApplyToAll() we’d be done – but what if we don’t know in advance what function to apply? A function pointer is what we need – a way to tell GradesList::ApplyToAll() which function to use.

OOP Etgar 2008 – Recitation 55 Function Pointers – Possible? We can think of a function name as a pointer to where its code begins. Thus func is a memory address of where the code of func() begins. But since a function has arguments and return value, the type of the pointer must specify them.

OOP Etgar 2008 – Recitation 56 Function Pointers A pointer to a function with no arguments and returning an int is declared as int (*p)(); Read it inside out – p is a pointer (the * ) to a function (the right-hand () ) taking nothing (these parenthesis are empty) and returning an int. The parenthesis around *p are needed to ensure that * is “applied” before ().

OOP Etgar 2008 – Recitation 57 The Syntax If idler() is defined as int idler(); we can write p = idler; p now points to the beginning of the code of idler(). To run that code using p, type (*p)(); or in short p();

OOP Etgar 2008 – Recitation 58 More Complex Syntax The list of arguments is specified in the right- hand parenthesis. If pow() is defined as double pow(double b, double p); the correct pointer is double (*pow_p)(double, double); The calling syntax is the same: pow_p = pow; pow_p(1.2, 2.3);

OOP Etgar 2008 – Recitation 59 Typedef Function pointer syntax is complex, especially when the function itself returns a function pointer. Use typedef s to simplify: typedef double (*func_p)(double, double); func_p is a type of a pointer to a function taking two double s and returning an int. Variable declaration now is more readable: func_p p = pow; p(1.2, 2.3);

OOP Etgar 2008 – Recitation 510 Back to the Beginning Now the grades can be increased: int ten_percent(int grade) { return grade*1.1; } void GradesList::ApplyToAll( int (*f)(int) ); grades.ApplyToAll(ten_percent);

OOP Etgar 2008 – Recitation 511 (Extremely) Complex Example Define a variable of type “array of N pointers to functions returning pointers to functions returning pointers to char”. Huh? The straightforward (and unreadable) solution: char *(*(*a[N])())();

OOP Etgar 2008 – Recitation 512 Solution with Typedefs typedef char *pc; /* pointer to char */ typedef pc fpc(); /* function returning pointer to char */ typedef fpc *pfpc; /* pointer to above */ typedef pfpc fpfpc(); /* function returning... */ typedef fpfpc *pfpfpc; /* pointer to... */ pfpfpc a[N]; /* array of... */ From “C FAQs” by Steve Summit.

OOP Etgar 2008 – Recitation 513 Pointers to Members

OOP Etgar 2008 – Recitation 514 Non-Static Member Functions Just as we can declare a pointer to a function, we can declare a pointer to a non-static member function. The syntax is different, since non-static member function takes an implicit this parameter. The type of a pointer to non-static member function must include class specification, and the method invocation must be done on an object.

OOP Etgar 2008 – Recitation 515 Example struct C { void func();// (1) void func() const;// (2) void func(int);// (3) }; … C temp;// temp is an object of class C void (C::* p1)();// pointers to members of C void (C::* p2)() const;// … void (C::* p3)(int);// … p1 = C::func; p2 = C::func; p3 = C::func; (temp.*p1)();// invocation of (1) (temp.*p2)();// invocation of (2) (temp.*p3)(3);// invocation of (3)

OOP Etgar 2008 – Recitation 516 Notes As always, typedef s will simplify reading: typedef void (C::* Cptr)(); Cptr cp = C::func; Pointers to static member functions are regular function pointers.

OOP Etgar 2008 – Recitation 517 Pointers to Data Members Pointers to class data members should be specified with a class name. struct C { int i; }; … C temp;// object of type C int C::* p;// pointer to C's int data // member p = &C::i;// p points to i cout << temp.*p;// prints temp.I

OOP Etgar 2008 – Recitation 518 Templates Generic Programming

OOP Etgar 2008 – Recitation 519 Why? Often we meet algorithms, data structures or classes that are independent of the concrete type used in them. QuickSort can sort anything (if it can be compared). List can store anything. But how can we write generic algorithms and data structures?

OOP Etgar 2008 – Recitation 520 Bad Solutions Using void* pointers: –Type-unsafe. –Error-prone. –Very unfriendly. Deriving all classes from one superclass: –Type-unsafe. –Demands specific interface from all classes. Both solutions disallow homogenous containers.

OOP Etgar 2008 – Recitation 521 Templates A template allows passing a type as a parameter to a class or a function. This means that we can write classes and functions that are independent of the types they work with. Actually, a template is a recipe for creating families of classes and functions.

OOP Etgar 2008 – Recitation 522 Swap() Consider the function swap() – the code is identical if it swaps two int s, two Rational s or two string s. void swap(int& a, int& b) { int temp = a; a = b; b = temp; }

OOP Etgar 2008 – Recitation 523 Function Templates We can say that to the compiler by defining a function template: template void swap(T& a, T& b) { T temp = a; a = b; b = temp; } Within the template, T is another type, just like int or double.

OOP Etgar 2008 – Recitation 524 Template Instantiation The compiler will use this template to instantiate swap() for types it needs: –When it needs to swap int s, it will generate a version for int s. –If it needs to swap string s, it will generate a new version for string s. The versions it generates will have no connection to one another (apart from similar name).

OOP Etgar 2008 – Recitation 525 Lack of Conversions The compiler decides which version to instantiate based on the parameters types. –This is called template argument deduction. Conversions are not considered for this. –I.e., these calls will not compile: int i; short s; double d; swap(i, d);// no version for int and a double swap(i, s);// no version for int and a short The only conversions used are –conversion to const pointer or reference, –array and function to pointer.

OOP Etgar 2008 – Recitation 526 Class Templates What about classes? Obviously, the code for ListOComplex will work for Rational s, int s or string s, if we didn’t hardwire the type into it. We can define a class template for a List, and List users will specify the concrete type when creating List objects. –The compiler will create instantiated classes as needed.

OOP Etgar 2008 – Recitation 527 Class List template class List { public: List(const List&); bool push_front(const T&); T pop_front(); … }; Within List ’s methods, T is another type, just like int or double.

OOP Etgar 2008 – Recitation 528 Instantiated Classes With class templates we need to specify the type parameter to create an object: List listOcomplex; List listOint; The compiler creates an instance of class List for Complex es and an instance for int s. They have nothing to do with one another. Note that copy c’tor in List has a parameter of type List, not List. –Both forms can be used – but the former only within the template itself.

OOP Etgar 2008 – Recitation 529 Notes Templates can be complicated: –Referring to base class template from within a derived class template requires the use of this->, using or ::. –Care should be taken for templates within templates – the >> in List > is interpreted as operator>>(). But templates allow generic programming. In fact, templates themselves form a complete programming language.