Reusing Code in C++ Has-a relationship Classes with member objects(containment) The valarray template class Private & protected inheritance Multiple inheritance.

Slides:



Advertisements
Similar presentations
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
Advertisements

C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
Stacks and Queues & Inheritance 2014 Spring CS32 Discussion Jungseock Joo.
Reusing Code Private or Protected inheritance. A cool class for array valarray class deals with numeric values, and it supports operation such as summing.
 2006 Pearson Education, Inc. All rights reserved Templates.
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
 2006 Pearson Education, Inc. All rights reserved. Templates (again)CS-2303, C-Term Templates (again) CS-2303 System Programming Concepts (Slides.
Inheritance, Polymorphism, and Virtual Functions
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
Templates CS-240 Dick Steflik & DJ. Foreman. Reuse Templates allow us to get more mileage out of the classes we create by allowing the user to supply.
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.
Templates CS212 & CS-240. Reuse Templates allow extending our classes Allows the user to supply certain attributes at compile time. Attributes specified.
Chapter 4 Inheritance Bernard Chen Spring Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism.
Chapter 12: Adding Functionality to Your Classes.
LECTURE LECTURE 17 More on Templates 20 An abstract recipe for producing concrete code.
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
Polymorphism. Introduction ‘one name multiple forms’ Implemented using overloaded functions and operators Early binding or static binding or static linking.
Chapter 11: Inheritance and Composition. Objectives In this chapter, you will: – Learn about inheritance – Learn about derived and base classes – Redefine.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Templates Zhen Jiang West Chester University
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved. Note: C How to Program, Chapter 22 is a copy of C++ How to Program Chapter.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
Recap, Test 1 prep, Composition and Inheritance. Dates Test 1 – 12 th of March Assignment 1 – 20 th of March.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Copyright  Hannu Laine C++-programming Part 3 Hannu Laine.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Copyright © Curt Hill Generic Classes Template Classes or Container Classes.
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 8: Class Relationships Data Abstraction & Problem Solving.
Inheritance, Polymorphism, And Virtual Functions Chapter 15.
Introduction to Generics
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
C++ How to Program, 9/e © by Pearson Education, Inc. All Rights Reserved.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
What Is Inheritance? Provides a way to create a new class from an existing class New class can replace or extend functionality of existing class Can be.
Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
Templates Class Templates Used to specify generic class types where class members data types can be specified as parameters, e.g. here is a generic List.
Overview of C++ Templates
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Effective C++, 2nd Ed. By Scott Myers. Constructors, Destructors, and Assignment Operators 11.Define a copy constructor and an assignment operator for.
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
1 Object-Oriented Programming -- Using C++ Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology
Chapter 11: Inheritance and Composition. Introduction Two common ways to relate two classes in a meaningful way are: – Inheritance (“is-a” relationship)
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Object Oriented Programming in C++ Chapter 7 Dynamic Binding.
Class Inheritance Inheritance as an is-a relationship Public derive one class from another Protected access Initializer lists in constructor Upcasting.
Chapter 17 – Templates. Function Templates u Express general form for a function u Example: template for adding two numbers Lesson 17.1 template Type.
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
©Copyrights 2016 Eom, Hyeonsang All Rights Reserved Computer Programming Object Oriented Programming & C++ 1 st Lecture 엄현상 (Eom, Hyeonsang) Department.
CS 342: C++ Overloading Copyright © 2004 Dept. of Computer Science and Engineering, Washington University Overview of C++ Overloading Overloading occurs.
 Virtual Function Concepts: Abstract Classes & Pure Virtual Functions, Virtual Base classes, Friend functions, Static Functions, Assignment & copy initialization,
 2006 Pearson Education, Inc. All rights reserved Templates.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
A First Book of C++ Chapter 12 Extending Your Classes.
Abstract classes only used as base class from which other classes can be inherit cannot be used to instantiate any objects are incomplete Classes that.
Part -1 © by Pearson Education, Inc. All Rights Reserved.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Programming with ANSI C ++
CS 215 Final Review Ismail abumuhfouz Fall 2014.
CS212: Object Oriented Analysis and Design
Inheritance, Polymorphism, and Virtual Functions
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Presentation transcript:

Reusing Code in C++ Has-a relationship Classes with member objects(containment) The valarray template class Private & protected inheritance Multiple inheritance Virtual base class Template class Template specializations

Classes with object members A student class –A name (string class) –A set of quiz scores –A fixed-size array? dynamic memory allocation? –An array-of-double

The valarray class

The Student class design Containment (composition, layering) is a has-a relationship Program studentc.h, studentc.cpp, use_stuc.cpp

Private inheritance With private inheritance, public and protected members of the base class become private members of the derived class Program studenti.h, studenti.cpp, use_studi.cpp

Containment or private inheritance Has-a relationship can be generated by containment or private inheritance In general, it is easy to use containment to build up a “has-a” relationship Private inheritance provides some privileges, such as accessing protected member, or redefining virtual function, which can not be implemented by containment

Containment or private inheritance We should use containment to model a has-a relationship Use private inheritance if the new class needs to access protected members in the original class or if it needs to redefine virtual functions

Varieties of inheritance

Redefining access with using Public members of a base class become protected or private when one uses protected or private derivation

Multiple inheritance Program worker0.h, worker0.cpp, worktest.cpp

Ambiguous inheritance Program worker.h, worker0.cpp, worktest.cpp // point out the ambiguities

Type conversion class SingingWaiter:public Singer, public Waiter { }; SingingWaiter ed; Worker *pw = &ed;// ambiguous Worker *pw1 = (Waiter *) &ed; // the Worker in Waiter Worker *pw2 = (Singer *) &ed; // the Worker in Singer

Inherit two base-class objects

Virtual base classes class Singer : virtual public Worker { }; class Waiter : public virtual Worker { }; class SingingWaiter: pubic Singer, public Waiter { …};

Using virtual base class If a class has an indirect inherit virtual base class, a constructor for that class should explicitly invoke a constructor for the virtual base class unless all that is needed is the default constructor for the virtual base class –SingingWaiter(const Worker &wk, int p=0, int v=Singer::other) : Waiter(wk, p), Singer(wk, v) { } // flawed –SingingWaiter(const Worker &wk, int p=0, int v=Singer::other) : Worker(wk), Waiter(wk, p), Singer(wk, v) { }// ok

Indicate which method Multiple inheritance can result in ambiguous calls SingingWaiter newhire(“Elise Hawks”, 2005, 6, soprano); newhire.Show();// ambiguous newhire.Singer::Show(); // use Singer version void SingingWaiter::Show() // best way to do it { Singer::Show();}

Problems shooting void Worker::Show() const {cout << “Name:” << fullname << “\n”; cout << “Employee ID:” << id << “\n”;} void Waiter::Show() const { Worker::Show(); cout <<“Panache rating:” << panache << “\n”; } void HeadWaiter::Show() const {Waiter::Show(); cout << “presence rating:” << presence << “\n”; } void SingingWaiter::Show() {Singer::Show();}// fail due to ignoring Waiter void SingingWaiter::Show() {Singer::Show(); Waiter::Show(); } // call Worker::show() twice

void Worker::Data() const {cout << “Name:” << fullname << “\n”; cout << “Empolyee ID:” << id << “\n”; } void Waiter::Data() const {cout << “Panache rating:” << panache << “\n”; void Singer::Data() const {cout << “Vocal range:” << pv[voice] << “\n”;} void SingingWaiter::Data() const {Singer::Data(); Waiter::Data(); } void SingingWaiter::Show() const {cout << “Category: singing waiter\n”; Worker::Data(); Data();} Program workermi.h, workermi.cpp, workmi.cpp Using modular approach

Multiple inheritance synopsis A derived class with an indirect virtual base class should have its constructors invoke the indirect base-class constructors directly, which is illegal for indirect non-virtual base classes Name ambiguity is resolved via the dominance rule

Class templates Inheritance and containment aren’t always the solution when you want to reuse code Drawbacks of different datatype –Edit header file each time when one changes the type –One can use the technique to generate just one kind of the class per program C++ class template provide a better way to generate generic class declaration C++’s Standard Template Library (STL)

The original Stack class

Using a class template Stack Stack kernels; // create a stack of int Stack colonels; // a stack of string objects Template void simple(T t) { cout << t << “\n”; } … simple(2);// generate void simple(int) simple(“two”);// generate void simple(char *) Program stacktp.h, stacktem.cpp

Stack pointer – incorrect version Stack s; // original stack Stack st; // create a stack for pointers-to-char string po; Three versions to replace “string po;” 1.char *po; cin >> po; // error 2.char po[40]; // template // bool Stack ::pop(Type &item) // { …; item = items[--top]; … } // item is Lvalue, cannot be array name 3. char *po = new char[40]; // push to the same address, and pop the same address value // pop outcome is always the last push in data

Correct version Program stcktp1.h, stkoptr1.cpp

Array template Template is usually used in container class ArrayTP, 10> twodee; int twodee [10][5]; Program arraytp.h, twod.cpp Generate 2 separate class declarations Just one class declaration through constructor

Template versatility

Using one than one type parameter Program pairs.cpp

Template specializations –Implicit instantiation –Explicit instantiation –Explicit specialization Partial specialization

Implicit instantiation The compiler doesn’t generate an implicit instantiation of the class until it needs an object

Explicit instantiation Generate ArrayTP class The compiler generates the class definition, including method definitions, even though no object of the class has yet been created or mentioned

Explicit specialization An explicit specialization is a definition for a particular type of types that is to be used instead of the general template A specialized class template definition has the form To provide a SortedArray template specialized for the const char * type, using the current notation

Partial specializations C++ allows for partial specializations, which partially restrict the generality of a template

Partial specializations Providing a special version for pointers Making a variety of restrictions The compiler would make the following choices

Member templates –Program tempmemb.cpp Templates as parameters –Program tempparm.cpp

Template classes and friends Template class can have friends 3 types of template friends –Non-template friends –Bound template friends The type of the friend is determined by the type of the class when a class is instantiated –Unbound template friends All specializations of the friend are friends to each specialization of the class

Non-template friend functions to template classes counts() function is a friend to HasFriend or HasFriend

Bound template friends The compiler would replace the template parameter T with int, giving in this form

Bound template friends The report() function is not itself a template function, it just has a parameter that is a template Need to define explicit specializations for the friends one plans to use

Template class with non-template friends Program frnd2tmp.cpp

Bound template friend functions to template classes Bound template friend involves three steps Step 1, declare each template function Step 2, declare the templates again

Bound template friend functions to template classes Step 3, declare an object of a particular specialization The compiler substitutes int for TT and generates the following class

Template friend to a template class Program tmp2tmp.cpp

Unbound template friend functions to template classes show2(hfd, hfi2) gets matched to this specialization Program manyfrnd.cpp