Object-Oriented Design (OOD) and C++

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

Module Operator Overloading and Type Conversion. Table of Contents

Overloading Operators in C++

Operator overloading

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

Operation Overloading.

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

Chapter 2 Basic Elements of C++

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

CS304 Object Oriented Programming Final Term

Reference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that

ADTs & Classes. An introduction

Object Oriented Design

Short Notes of CS201

Week 8: Operator overloading

Come and join us at WebLyceum

Review. What is const member data? By what mechanism is const enforced? How do we initialize it? How do we initialize it?

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

CS201 - Introduction to Programming Glossary By

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

CS304 Object Oriented Programming

Instantiation of Template class

Program construction in C++ for Scientific Computing

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

C++ Important Questions with Answers

More Advanced Class Concepts

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

Data Structures (list, dictionary, tuples, sets, strings)

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 12: Classes and Data Abstraction

Come and join us at WebLyceum

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Object Oriented Design

MaanavaN.Com CS1203 OBJECT ORIENTED PROGRAMMING DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


7.1 Optional Parameters

Lecture 3 ADT and C++ Classes (II)

A Short Summary of Javali

Polymorphism Part 1 1

OBJ. ORI.& MULT. PROG., M.C.Q. BANK, FOR UNIT -2, SECOND YEAR COMP. ENGG. SEM-4, 2012 PATTERN, U.O.P. UNIT-2

Ch. 12: Operator Overloading

Absolute C++ Walter Savitch

Inheritance and Polymorphism

UNIT- 3 Introduction to C++

Introduction to Programming session 24

For Teacher's Use Only Q No Total Q No Q No

UNIVERSITY OF SWAZILAND

Vectors of Pointers to Objects. Vectors of Objects. Vectors of unique ptrs C++11. Arrays of Objects

Overloaded Operators, Functions, and Students

CE221 Programming in C++ Part 1 Introduction

C++ (Non for C Programmer) (BT307) 40 Hours

What are the characteristics of Object Oriented programming language?

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

CS201 Latest Solved MCQs

Module 10 Inheritance, Virtual Functions, and Polymorphism

Cpt S 122 Data Structures. Templates

Programming C++ Lecture 3. Howest, Fall 2012 Instructor: Dr. Jennifer B. Sartor

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT).

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

Object Orientated Analysis and Design. Benjamin Kenwright

B.C.A 2017 OBJECT ORIENTED PROGRAMMING USING C++ BCA303T MODULE SPECIFICATION SHEET

2559 : Introduction to Visual Basic.NET Programming with Microsoft.NET

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++

Operator Overloading in C++ Systems Programming

Learning Objectives. C++ For Artists 2003 Rick Miller All Rights Reserved xli

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

CS105 C++ Lecture 7. More on Classes, Inheritance

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

CS 162, Lecture 25: Exam II Review. 30 May 2018

Classes and Data Abstraction

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

END TERM EXAMINATION


III. Classes (Chap. 3)

W3101: Programming Languages C++ Ramana Isukapalli

Interview Questions of C++

M Introduction to Visual Basic.NET Programming with Microsoft.NET 5 Day Course

VB.NET. Exercise 1: Creating Your First Application in Visual Basic.NET

Function Overloading

Full file at

Object-Oriented Programming Paradigm

DHANALAKSHMI COLLEGE OF ENGINEERING, CHENNAI DEPARTMENT OF ELECTRICAL AND ELECTRONICS ENGINEERING CS6456 OBJECT ORIENTED PROGRAMMING

Final exam. Final exam will be 12 problems, drop any 2. Cumulative up to and including week 14 (emphasis on weeks 9-14: classes & pointers)

OBJECT ORIENTED PROGRAMMING. Ms. Ajeta Nandal C.R.Polytechnic,Rohtak

PIC10B/1 Winter 2014 Exam I Study Guide

Programming Abstractions

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

Object Oriented Design

Lab 2: ADT Design & Implementation

Chapter 5 Object-Oriented Programming


IS0020 Program Design and Software Tools Midterm, Fall, 2004

AN OVERVIEW OF C++ 1

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

VALLIAMMAI ENGINEERING COLLEGE

Computer Science 306 Study Guide

CS304- Object Oriented Programming LATEST SOLVED MCQS FROM FINALTERM PAPERS. MC

Object-Oriented Programming (OOP) Fundamental Principles of OOP

Lesson 12 - Operator Overloading Customising Operators

Transcription:

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 Key Terms 2-1

Chapter Overview In addition to implementing encapsulation, classes have other capabilities. For instance, you can create new classes from existing classes (inheritance). This important feature encourages code reuse and saves programmers an enormous amount of time. In C++, you can relate two or more classes in more than one way. This chapter examines two common ways to relate classes: Inheritance ( is-a relationship) and Composition ( has-a relationship). The chapter also describes various kinds of polymorphism: overloading, overriding and templates. Chapter Objectives In this chapter, students will: Learn about inheritance Learn about derived and base classes Explore how to redefine the member functions of a base class Examine how the constructors of base and derived classes work Learn how to construct the header file of a derived class Explore three types of inheritance: public, protected, and private Learn about composition Become familiar with the three basic principles of object-oriented design Learn about overloading Became aware of the restrictions on operator overloading Examine the pointer this Learn about friend functions Explore the members and nonmembers of a class Discover how to overload various operators Learn about templates Explore how to construct function templates and class templates Instructor Notes Inheritance Inheritance is an is-a relationship; for instance, every employee is a person. Inheritance lets us create new classes from existing classes. An existing class is called a base class; the new class that we create from an existing class is called the derived class. The derived class inherits the properties of the base class. Rather than create completely new classes from scratch, we can take advantage of inheritance and reduce software complexity. Each derived class, in turn, becomes a base class for a future derived class. Inheritance can be either a single inheritance or a multiple inheritance. In a single inheritance, the derived class is derived from a single base class; in a multiple inheritance, the derived class is derived from more than one base class. This chapter concentrates on single inheritance. The general syntax to define a derived class is class classname: memberaccessspecifier baseclassname { member list }; 2-2

where memberaccessspecifier is public, protected, or private. When no memberaccessspecifier is specified, it is assumed to be a private inheritance. Keep in mind the following facts about the base and derived classes: The private members of the base class are private to the base class; hence, the members of the derived class cannot directly access them. When you write the definitions of the member functions of the derived class, you cannot directly access the private members of the base class. The public members of a base class can be inherited either as public members or as private members by the derived class. That is, the public members of the base class can become either public or private members of the derived class. The derived class can include additional data and/or function members. The derived class can redefine the public member functions of the base class. That is, in the derived class, you can have a function member with the same name, number, and types of parameters as a function in the base class. However, this redefinition applies only to the objects of the derived class, not to the objects of the base class. All data members of the base class are also data members of the derived class. Similarly, the member functions of the base class (unless redefined) are also the member functions of the derived class. To redefine (override) a public member function of the base class in the derived class, the corresponding function in the derived class must have the same name, number, and types of parameters. In other words, the name of the function being redefined in the derived class must have the same formal parameter list. If the corresponding functions in the base class and the derived class have the same name but a different formal parameter list, then this is function overloading in the derived class, which is also allowed. A derived class can have its own private data members; therefore, a derived class can have its own constructors. A constructor typically serves to initialize the data members. When we declare a derived class object, this object inherits the members of the base class; however, the derived class object cannot directly access the private (data) members of the base class. The same is true for the member functions of a derived class. That is, the member functions of the derived class cannot directly access the private members of the base class. Consequently, the constructors of the derived class can (directly) initialize only the private data members of the derived class. Therefore, when a derived class object is declared, it must also automatically execute one of the constructors of the base class. Because constructors cannot be called like other functions, the execution of a derived class s constructor must trigger the execution of one of the base class s constructors. This is, in fact, what happens. Furthermore, a call to the base class s constructor is specified in the heading part of the derived class constructor s definition. To trigger the execution of a constructor (with parameters) of the base class, you specify the name of the constructor of the base class with the parameters in the heading of the definition of a constructor of the derived class. To define new classes, you create new header files. The base classes are already defined, and their definitions are contained in header files. To create new classes based on the previously defined classes, the header files of the new classes contain commands that tell the computer where to look for the definitions of the base classes. The definitions of the member functions can be placed in a separate file. Recall that to include a system-provided header file, such as iostream, in a user program, you enclose the header file between angular brackets; to include a user-defined header file in a program, you enclose the header file between double quotation marks. To include a header file in a program, you use the preprocessor command. Recall that before a program is compiled, the preprocessor first processes the program. To avoid multiple inclusions of a file in a program, we use certain preprocessor commands in the header file. These commands include: #ifndef which means if not defined #define which means define #endif which means end if The private members of a class are private to the class and cannot be directly accessed outside the class. Only member functions of that class can access the private members. As discussed previously, a derived class cannot directly access the private members of a base class. However, it is sometimes necessary for a derived class to access a private member of a base class. If you make a private member become public, then anyone can access that member. Recall that the members of a class are classified into three categories: public, private, and protected. So, 2-3

for a base class to give access to a member to its derived class and still prevent its direct access outside the class, you must declare that member under the member access specifier protected. Therefore, the accessibility of a protected member of a class is in between public and private. A derived class can directly access the protected member of a base class. To summarize, if a derived class needs to access a member of a base class, and to prevent the direct access of the member outside the base class, that member of the base class is declared under the member access specifier protected. Suppose class B is derived from class A. Then B cannot directly access the private members of A. Composition Composition is another way to relate two classes. In composition, one or more members of a class are objects of another class type. Composition is a has-a relation; for example, every person has a date of birth. Quick Quiz 1. True or False: The reserved word private is used if a member of a base class needs to be accessed by a derived class. Answer: False 2. Derived classes inherit properties from classes. Answer: base 3. The preprocessor command means if not defined. Answer: #ifndef 4. True or False: Members of a derived class can redefine members of a base class. Answer: True 5. is a has-a relationship. Answer: Composition Polymorphism: Operator and Function Overloading The ability to combine data and operations on that data is called encapsulation. It is the first principle of objectoriented design (OOD). Inheritance, the second principle of OOD, encourages code reuse. The third principle of OOD is polymorphism. First we discuss polymorphism via operator overloading, and then via templates. Templates enable the programmer to write generic codes for related functions and classes. We will simplify function overloading through the use of templates, called function templates. The third type of polymorphism via virtual functions is discussed in Appendix F. Operator Overloading Recall that the only built-in operations on classes are the assignment operator and the member selection operator. Therefore, other operators cannot be directly applied to class objects. However, C++ allows the programmer to extend the definitions of most of the operators so that operators such as relational operators, arithmetic operators, insertion operators for data output, and extraction operators for data input can be applied to classes. In C++ terminology, this is called operator overloading. 2-4

C++ allows the user to overload most of the operators so that the operators can work effectively in a specific application. It does not allow the user to create new operators. Most of the existing operators can be overloaded to manipulate class objects. In order to overload an operator, you must write a function definition (that is, the header and body).the name of the function that overloads an operator is the reserved word operator followed by the operator to be overloaded. For example, the name of the function to overload the operator >= is operator>= An operator function is the function that overloads an operator. The result of an operation is a value; therefore, the operator function is a value-returning function. The syntax of the heading for an operator function is returntype operator operatorsymbol(arguments) In C++, operator is a reserved word. Recall that the only built-in operations on classes are assignment (=) and member selection. To use other operators on class objects, they must be explicitly overloaded. Operator overloading provides the same concise expressions for user-defined data types as it does for builtin data types. To overload an operator for a class: 1. Include the statement to declare the function to overload the operator (that is, the operator function) in the definition of the class. 2. Write the definition of the operator function. When overloading an operator, keep the following in mind: You cannot change the precedence of an operator. The associativity cannot be changed. (For example, the associativity of the arithmetic operator + is from left to right and it cannot be changed.) You cannot use default arguments with an overloaded operator. You cannot change the number of arguments that an operator takes. You cannot create new operators. Only existing operators can be overloaded. The operators that cannot be overloaded are..* ::?: sizeof The meaning of how an operator works with built-in types, such as int, remains the same. Operators can be overloaded either for objects of the user-defined type, or for a combination of objects of the user-defined type and objects of the built-in type. A member function of a class can (directly) access the data members of that class for a given object. Sometimes it is necessary for a function member to refer to the object as a whole, rather than the object s individual data members. Every object of a class maintains a (hidden) pointer to itself, and the name of this pointer is this. In C++, this is a reserved word. The pointer this is available for you to use. When an object invokes a member function, the member function references the pointer this of the object. A function that is defined outside the scope of a class is called a friend function of the class. A friend function is a nonmember function of the class, but has access to the class s private data members. To make a function be a friend to a class, the reserved word friend precedes the function prototype (in the class definition). (The word friend appears only in the function prototype in the class definition, not in the definition of the friend function.) When writing the definition of a friend function, the name of the class and the scope resolution operator do not precede the name of the friend function in the function heading. Also, recall that the word friend does not appear in the heading of the friend function s definition. Certain rules must be followed when you include an operator function in the definition of a class. Most operator functions can be either member functions or nonmember functions that is, friend functions of a class. To make an operator function be a member or nonmember of a class, keep the following in mind: The function that overloads any of the operators (), [], ->, or = for a class must be declared as a member of the class. 2-5

Suppose that an operator op is overloaded for a class say, opoverclass. If the leftmost operand of op is an object of a different type (that is, not of the type opoverclass), the function that overloads the operator op for opoverclass must be a nonmember that is, a friend of the class opoverclass. If the operator function that overloads the operator op for the class opoverclass is a member of the class opoverclass, then when applying op on objects of the type opoverclass, the leftmost operand of op must be of the type opoverclass. Functions that overload the insertion operator, <<, and the extraction operator, >>, for a class must be nonmembers that is, friend functions of the class. Except for certain operators as noted previously, operators can be overloaded either as member functions or as nonmember functions. Overloading Binary Operators C++ consists of both binary and unary operators. It also has a ternary operator, which cannot be overloaded. Suppose that # represents a binary operator (arithmetic or relational) that is to be overloaded for the class opoverclass. This operator can be overloaded as either a member function of the class or a friend function. Function Prototype (to be included in the definition of the class): returntype operator op(const classname&) const; where op stands for the binary operator, arithmetic or relational, to be overloaded; returntype is the type of value returned by the function; and classname is the name of the class for which the operator is being overloaded. Function Definition: returntype classname::operator op (const classname& otherobject) const { //algorithm to perform the operation return (value); } To include the operator function operator# as a nonmember of the class in the definition of the class, the reserved word friend must appear before the function heading. Also, the function operator# must have two arguments. Function Prototype (to be included in the definition of the class): friend returntype operator op(const classname&, const classname&); where op stands for the binary operator to be overloaded, returntype is the type of value returned by the function, and classname is the name of the class for which the operator is being overloaded. Function Definition: returntype operator op(const classname& firstobject, const classname& secondobject) { //algorithm to perform the operation return (value); } The operator function that overloads the insertion operator, <<, or the extraction operator, >>, for a class must be a nonmember of that class. Function Prototype (to be included in the definition of the class): friend ostream& operator<<(ostream&, const classname&); 2-6

Function Definition: ostream& operator<<(ostream& osobject, const classname& object) { //local declaration if any //Output the members of the object //osobject<<... //Return the ostream object return osobject; } In the preceding function definition: Both parameters are reference parameters. The first parameter that is, osobject is a reference to an ostream object. The second parameter is usually a const reference to a particular class, because the most effective way to pass an object as a parameter to a class is by reference. In this case, the formal parameter does not need to copy the data members of the actual parameter. In the previous definition, the word const appears before the class name because we want only to print the data members of the object. That is, the function should not modify the data members of the object. The return type of the function is a reference to an ostream object. Notice that the return type of the function to overload the stream insertion operator, <<, is a reference. To overload the stream extraction operator, >>, for a class the following function prototype and definition apply. Function Prototype (to be included in the definition of the class): friend istream& operator>>(istream&, classname&); Function Definition: istream& operator>>(istream& isobject, classname& object) { //local declaration if any //Read the data into the object //isobject>>... //Return the stream object return isobject; } In the preceding function definition: Both parameters are reference parameters. The first parameter that is, isobject is a reference to an istream object. The second parameter is usually a reference to a particular class. The data read will be stored in the object. The return type of the function is a reference to an istream object. Notice that the return type of the function to overload the istream extraction operator, >>, is a reference. The process of overloading unary operators is similar to the process of overloading binary operators. The only difference is that in the case of a unary operator, the operator has only one operand; in the case of a binary operator, the operator has two operands. Therefore, to overload a unary operator for a class: If the operator function is a member of the class, it has no parameters. If the operator function is a nonmember that is, a friend function of the class it has one parameter. Certain operators must be overloaded as member functions of the class, and some must be overloaded as nonmember (friend) functions. What about the ones that can be overloaded as either member functions or 2-7

nonmember functions? For example, the binary arithmetic operator + can be overloaded as a member function or a nonmember function. If you overload + as a member function, the operator + has direct access to the data members of one of the objects, and you need to pass only one object as a parameter. On the other hand, if you overload + as a nonmember function, you must pass both objects as parameters. Therefore, overloading + as a nonmember could require additional memory and computer time to make a local copy of the data. Therefore, for efficiency purposes, wherever possible you should overload operators as member functions. Function Overloading Similar to operator overloading, C++ allows the programmer to overload a function name. Recall that a class can have more than one constructor, but all constructors of a class have the same name, which is the name of the class. This case is an example of overloading a function. Overloading a function refers to the creation of several functions with the same name. However, if several functions have the same name, every function must have a different formal parameter list. The types of parameters determine which function to execute. For function overloading to work, we must give the definition of each function. Templates Templates are very powerful features of C++. By using templates, you can write a single code segment for a set of related functions, called a function template, and for related classes, called a class template. The syntax we use for templates is template<class Type> declaration; where Type is the type of data, and declaration is either a function declaration or a class declaration. In C++, template is a reserved word. The word class in the heading refers to any user-defined type or built-in type. Type is referred to as a formal parameter to the template. Just as variables are parameters to functions, types (that is, data types) are parameters to templates. C++ simplifies the process of overloading functions by providing function templates. The syntax of the function template is template<class Type> function definition; where Type is referred to as a formal parameter of the template. It is used to specify the type of parameters of the function and the return type of the function, and to declare variables within the function. If you omit the body of the function in the function template definition, the function template, as usual, is the prototype. Like function templates, class templates are used to write a single code segment for a set of related classes. The syntax we use for a class template is template< class Type> class declaration Class templates are called parameterized types because, based on the parameter type, a specific class is generated. A template instantiation can be created with either a built-in or user-defined type. The function members of a class template are considered function templates. Therefore, when giving the definitions of function members of a class template, you must follow the definition of the function template. Until now, we have placed the definition of the class (in the specification file) and the definitions of the member functions (in the implementation file) in separate files. The object code was generated from the implementation file (independently of any client code) and linked with the client code. This strategy does not work with class 2-8

templates. Passing parameters to a function has an effect at run time, whereas passing a parameter to a class template has an effect at compile time. Because the actual parameter to a class is specified in the client code, and because the compiler cannot instantiate a function template without the actual parameter to the template, we can no longer compile the implementation file independently of the client code. This problem has several possible solutions. We could put the class definition and the definitions of the function templates directly in the client code, or we could put the class definition and the definitions of the function templates together in the same header file. Another alternative is to put the class definition and the definitions of the functions in separate files (as usual), but include a directive to the implementation file at the end of the header file (that is, the specification file). In either case, the function definitions and the client code are compiled together. Quick Quiz 1. True or False: When overloading an operator, you cannot change the precedence of an operator. Answer: True 2. C++ simplifies the process of overloading functions by providing function. Answer: templates 3. True or False: In C++, a class can only have one constructor. Answer: False 4. Class templates are called types because, based on the parameter type, a specific class is generated. Answer: parameterized 5. True or False: When overloading an operator, you cannot change the number of arguments that an operator takes. Answer: True 2-9

Discussion Questions Some interesting topics of discussion in this chapter include: Discuss examples of is-a and has-a relationships and possible C++ implementations. Discuss overloading and overriding. Discuss templates in further detail. Projects to Assign 1. Assign odd Exercises. 2. Assign Programming Exercises 2, 4, 6 Key Terms Base class: existing class; superclass Derived class: subclass created from existing base class. Inheritance: a meaningful way to relate two or more classes with the is-a relationship between them. Multiple inheritance: the subclass is derived from more than one superclass. Single inheritance: the subclass is derived from only one existing superclass. Template: C++ feature enabling you to write single code segments for a set of related functions or classes. 2-10