1 Class Features and Design Issues COSC 1567 C++ Programming Lecture 5.

Slides:



Advertisements
Similar presentations
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Advertisements

Chapter 11 Separate Compilation and Namespaces. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Separate Compilation.
Copyright © 2002 Pearson Education, Inc. Slide 1.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
VBA Modules, Functions, Variables, and Constants
Chapter 11 Separate Compilation and Namespaces Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
 2006 Pearson Education, Inc. All rights reserved Midterm review Introduction to Classes and Objects.
Object Oriented Programming.  OOP Basic Principles  C++ Classes  September 2004  John Edgar 22.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
More C++ Classes Systems Programming. Systems Programming: C++ Classes 2 Systems Programming: 2 C++ Classes  Preprocessor Wrapper  Time Class Case Study.
Guide To UNIX Using Linux Third Edition
Chapter 13: Object-Oriented Programming
1 Using Classes Object-Oriented Programming Using C++ Second Edition 5.
Using Classes Object-Oriented Programming Using C++ Second Edition 5.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
You gotta be cool. Access Functions and Utility Functions Preprocessor Wrapper Looking Ahead to Composition and Inheritance Object Size Class Scope and.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Chapter 8 More Object Concepts
1 Understanding Inheritance COSC 156 C++ Programming Lecture 8.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
Chapter 8 Friends and Overloaded Operators. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Friend Function (8.1) Overloading.
More C++ Classes Systems Programming. C++ Classes  Preprocessor Wrapper  Time Class Case Study –Two versions (old and new)  Class Scope and Assessing.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Chapter 6: User-Defined Functions
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
Programming Logic and Design Using Methods. 2 Objectives Review how to use a simple method with local variables and constants Create a method that requires.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Class Features and Design Issues Object-Oriented Programming Using C++ Second Edition 6.
Chapter 10 Introduction to Classes
Data Structures Using C++ 2E1 Inheritance An “is-a” relationship –Example: “every employee is a person” Allows new class creation from existing classes.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
Simple Classes. ADTs A specification for a real world data item –defines types and valid ranges –defines valid operations on the data. Specification is.
1 Chapter Four Creating and Using Classes. 2 Objectives Learn about class concepts How to create a class from which objects can be instantiated Learn.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Chapter 9 Separate Compilation and Namespaces. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Separate Compilation (9.1)
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 12 Separate Compilation and Namespaces.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Separate Compilation and Namespaces.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
Array in C++ / review. An array contains multiple objects of identical types stored sequentially in memory. The individual objects in an array, referred.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
Chapter 7 Constructors and Other Tools Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-1 Learning Objectives  Classes  Constructors  Principles of OOP  Class type member.
CLASSES AND OBJECTS Chapter 3 : constructor, Separate files, validating data.
100 學年度碩士班新生暑期課程 程式設計 Object-Oriented Programming: Part I The Basics of Classes.
Programming Logic and Design Fifth Edition, Comprehensive Chapter 7 Using Methods.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Classes in C++ By: Mr. Jacobs. Objectives  Explore the implications of permitting programmers to define their own data types and then present C++ mechanism.
Classes C++ representation of an object
Class Features and Design Issues
Class Features and Design Issues
Auburn University COMP 3000 Object-Oriented Programming for Engineers and Scientists Constructors and Other Tools Dr.
User-Defined Functions
Understanding Inheritance
Chapter 9 Classes: A Deeper Look, Part 1
Learning Objectives Classes Constructors Principles of OOP
Introduction to Classes and Objects
Constructors and Other Tools
Classes, Objects and Methods
More C++ Classes Systems Programming.
SPL – PS3 C++ Classes.
Presentation transcript:

1 Class Features and Design Issues COSC 1567 C++ Programming Lecture 5

2 Objectives Classify the roles of member functions Constructors Override constructor default values Overload constructors Use a class within another class Preprocessor directives #ifndef, #define, and #endif Managing attributes and functions of classes Coupling and cohesion

3 Introducing Member Functions You can create an infinite number of classes and write an infinite number of functions You can classify the roles of member functions into four basic groups: –Inspector functions, also called access functions –Mutator functions, also known as implementors –Auxiliary functions, also known as facilitators –Manager functions

4 Understanding Constructors A constructor is a function that is called automatically each time an object is created Constructors have been used When declare a simple scalar variable, such as int number, C++ calls an internal constructor function that reserves a memory location of the correct size for an integer, and attaches the name “number” to that location The definition int number = 23; calls a constructor that reserves memory, attaches a name, and assigns a value

5 Understanding Constructors Until now, when you created class objects, you let C++ provide its own constructor for the objects When an object is created, its data fields store whatever values (often called garbage values) happen to be in those positions in computer memory After you instantiated objects in your programs, you used a mutator function with a name such as setValues() to assign useful values to data members

Constructors Initialization of objects –Initialize some or all member variables –Other actions possible as well A special kind of member function –Automatically called when object declared Very useful tool –Key principle of OOP 6

Constructor Definitions Constructors defined like any member function –Except: 1.Must have same name as class 2.Cannot return a value; not even void! 7

8 Understanding Constructors That process is similar to declaring a variable and assigning a value to it later However, you might want to initialize one or more of an object’s data members immediately upon creation When you want to initialize an object, or perform other tasks when the object is created, then you must write your own constructor for the class

9 Writing Your Own Constructors A constructor that requires no arguments is a default constructor, regardless of whether the constructor has an empty argument list or an argument list in which a default value is provided for each argument Constructor functions differ from other member functions in two ways: –You must give a constructor function the same name as the class for which it is a constructor –You cannot give a constructor function a return type (it’s not necessary because constructors always return an object of the class to which they belong)

10 Writing Your Own Constructors A constructor must have the same name as its class because the constructor is called automatically when an object is created If you named a constructor something other than its class name, C++ would not know it was a constructor Constructor functions are not coded with a return type

11 Writing Your Own Constructors The constructor function Employee() shown in Figure 6-2 is called a default constructor because it does not require any arguments

12 Employee Class and main() Function that Instantiates an Employee EX5-1.cpp

Another Constructor Example Class definition with constructor: –class DayOfYear { public: DayOfYear(int monthValue, int dayValue); //Constructor initializes month & day void input(); void output(); … private: int month; int day; } 13

Constructor Notes Notice name of constructor: DayOfYear –Same name as class itself! Constructor declaration has no return-type –Not even void! Constructor in public section –It’s called when objects are declared –If private, could never declare objects! 7

Calling Constructors Declare objects: DayOfYear date1(7, 4), date2(5, 5); Objects are created here –Constructor is called –Values in parens passed as arguments to constructor –Member variables month, day initialized: date1.month  7 date2.month  5 date1.dat  4 date2.day  5 8

Constructor Equivalency Consider: –DayOfYear date1, date2 date1.DayOfYear(7, 4);// ILLEGAL! date2.DayOfYear(5, 5);// ILLEGAL! Seemingly OK… –CANNOT call constructors like other member functions! 16

Constructor Code Constructor definition is like all other member functions: DayOfYear::DayOfYear(int monthValue, int dayValue) { month = monthValue; day = dayValue; } Note same name around :: –Clearly identifies a constructor Note no return type –Just as in class definition 10

Alternative Definition Previous definition equivalent to: DayOfYear::DayOfYear(int monthValue, int dayValue) : month(monthValue), day(dayValue)  {…} Third line called "Initialization Section" Body left empty Preferable definition version 11

Class with Constructors Example: Display 7.1 Class with Constructors (1 of 3) 19

Class with Constructors Example: Display 7.1 Class with Constructors (2 of 3) 20

Class with Constructors Example: Display 7.1 Class with Constructors (3 of 3) 21 Ex5-2.cpp

Constructor Additional Purpose Not just initialize data Body doesn’t have to be empty –In initializer version Validate the data! –Ensure only appropriate data is assigned to class private member variables –Powerful OOP principle 22

23 Employee Class with Constructor that Uses Default Arguments EX5-3.cpp EX5-4.cpp

24 Overriding the Constructor’s Default Arguments To replace the default values assigned by a constructor, you can use a mutator function such as setValues() You also can override a constructor’s default values by passing arguments to the constructor when you instantiate an object Two rules apply to the use of default parameters with constructor functions: –If you want to override constructor default values for an object you are instantiating, you also must override all parameters to the left of that value –If you omit any constructor argument when you instantiate an object, you must use default values for all parameters to the right of that argument

25 Overriding the Constructor’s Default Arguments The result of the three instantiations is as follows: –An assistant with the default ID of 9999, an an hourly rate of 5.65 –A clerk whose 1111 ID overrides the default idNumber, but whose hourly rate is the default 5.65 –A driver show 2222 ID and hourly rate of both override the default values in the constructor

26 Overloading Constructors Just like other C++ functions, constructors can be overloaded Overloading a function name allows you to use the same name for separate functions that have different argument lists Constructor functions for a given class must all have the same name as their class If you provide two or more constructors for the same class, they are overloaded by definition

Overloading Constructors Recall: a signature consists of: –Name of function –Parameter list Provide constructors for all possible argument-lists –Particularly "how many" 27

28 Employee Class with Overloaded Constructors EX5-5.cpp EX5-6.cpp

Default Constructor Defined as: constructor without arguments One should always be defined Auto-Generated? –Yes & No –If no constructors AT ALL are defined  Yes –If any constructors are defined  No If no default constructor: –Cannot declare: MyClass myObject; With no initializers 29 Ex5-7.cpp

30 Using Destructors A destructor is a function that is called automatically each time an object is destroyed An object is destroyed when it goes out of scope The rules for creating destructor function prototypes are similar to the rules for constructor function prototypes –As with constructors, you must give a destructor function the same name as its class ( and therefore the same name as any constructor for that class) –As with constructors, you cannot give a destructor function a return type –Unlike constructors, you cannot pass any values to a destructor

31 Using Destructors A destructor must have the same name as its class (plus the tilde) because it is called automatically when an object is destroyed Only one destructor can exist for each class The Object class in Figure 6-13 contains one field, a constructor, and a destructor

32 Using Destructors Ex5-8.cpp Ex5-9.cpp

33 Using Classes within Classes On many occasions you might want to use a class within another class Just as you build any complex real-life item, such as an automobile, from other well-designed parts, complex classes are easier to create if you use previously written, well-designed classes as components

Using Classes within Classes Class member variables can be any type –Including objects of other classes! –Type of class relationship Powerful OOP principle Need special notation for constructors –So they can call "back" to member object’s constructor 34

35 The InventoryItem Class

36 The Salesperson Class

37 Using Classes within Classes To represent a sales transaction, you want to include information about the item sold and the salesperson who sold it You could write a transaction class that contained individual fields, such as item stock number and salesperson ID number, but it is more efficient to reuse the InventoryItem and Salesperson classes that are already created and tested

38 The Transaction Class

39 Using Classes within Classes Ex5-10.cpp

Another Example for Class Member Variable (Using classes in a class) 40

Class Member Variable Example: Display 7.3 A Class Member Variable (2 of 5) 41

Class Member Variable Example: Display 7.3 A Class Member Variable (3 of 5) 42

Class Member Variable Example: Display 7.3 A Class Member Variable (4 of 5) 43

Class Member Variable Example: Display 7.3 A Class Member Variable (5 of 5) 36 Ex5-11.cpp

45 Considering Reusability and Maintenance Issues Reusability is a major focus of thinking in an object- oriented manner Creating self-contained components such as InventoryItem that you include in other classes makes program maintenance easier More than half of most programmers time on the job (and almost all of new programmers’ time) is spent maintaining or changing existing programs The more places a change must be made, the more time it takes, the more likely that an error occurs when that change is made, and the greater the change that one of the necessary changes is overlooked

Class Header Files Class interface always in header file –Use.h naming convention Programs that use class will "include" it –#include "myclass.h" –Quotes indicate you wrote header Find it in "your" working directory –Recall library includes, e.g., indicate predefined library header file Find it in library directory 46

Class Implementation Files Class implementation in.cpp file –Typically give interface file and implementation file same name myclass.h and myclass.cpp –All class’s member function defined here –Implementation file must #include class’s header file.cpp files in general, typically contain executable code –e.g., Function definitions, including main() 47

Class Files Class header file #included by: –Implementation file –Program file Often called "application file" or "driver file" Organization of files is system dependent –Typical IDE has "project" or "workspace" Implementation files "combined" here Header files still "#included" 48

Multiple Compiles of Header Files Header files –Typically included multiple times e.g., class interface included by class implementation and program file –Must only be compiled once! –No guarantee "which #include" in which file, compiler might see first Use preprocessor –Tell compiler to include header only once 49

Other Library Files Libraries not just for classes Related functions –Prototypes  header file –Definitions  implementation file Other type definitions –structs, simple typedefs  header file –Constant declarations  header file 50

51 Using #IFNDEF, #DEFINE, and #ENDIF After you have created a collection of useful classes, often called a library, you might find that many class files contain the same #include statement Using the #define directive alone does not provide much benefit Instead, it is usually coupled with two other directives #ifndef and #endif The C++ directive #ifndef allows you to test whether a class has already been defined in a project

52 Using #IFNDEF, #DEFINE, and #ENDIF The #ifndef directive means “if not defined” If you place an #ifndef at the beginning of a class, and the class has not been defined, then the #define directive will be implemented Ex5-12.cpp InventoryItem.cpp SalesPerson.cpp Transaction.cpp

53 Improving Functions As you write larger and more complicated programs, be sure to spend time on planning and design Each class you design must be well thought out A final product is great only if each component is well designed—just ask anyone with a $30,000 car that leaks oil

54 Selecting Member Data and Function Names When you begin to design a class and select its member functions, you need to consider the following questions: –Will special initialization tasks be necessary? –Will any special clean-up tasks be carried out when a class object goes out of scope? –Will class data members be assigned values after their construction?

55 Selecting Member Data and Function Names C++ identifiers must not include spaces and cannot begin with a number, but you also must apply other general guidelines: –Use meaningful names –Use pronounceable names –Be judicious in your use of abbreviations –Avoid using digits in a name –Use capitalization freely in multi-word names –Include a form of “to be,” such as “is” or “are,” in names for variables that hold a status –Often a verb-noun provides a good combination for a function

56 Selecting Member Data and Function Names Luckily, you do not have to write a C++ class or program completely before you can see whether the overall plan works Most programmers use stubs during the initial phases of a project Stubs are simple routines that do nothing (or very little); you incorporate them into a program as placeholders

57 Reducing Coupling Between Functions Coupling is a measure of the strength of the connection between two functions; it expresses the extent to which information is exchanged by functions Coupling is either tight coupling or loose coupling, depending on how much one function depends on information from another Tight coupling, which features much dependence between functions, makes programs more prone to errors

58 Increasing Cohesion within a Function Cohesion refers to how well the operations in a function relate to one another In highly cohesive functions, all operations are related Functional cohesion occurs when all of the function operations contribute to the performance of only one task The function square() is highly cohesive; it performs one simple task, squaring a number Sequential cohesion arises when a function performs operations that must be carried out in a specific order, on the same data

59 Summary You can classify the roles of member functions into four basic groups: –Inspector— Mutator –Auxillary— Manager A constructor is a function that is called automatically each time an object is created If you want to override constructor default values for an object you are instantiating, you also must override all parameters to the left of that value If you provide two or more constructors for the same class, they are overloaded by definition

60 Summary A destructor is a function that is called automatically each time an object is destroyed It has the same name as its class, preceded with a tilde You can use a class within another class, which gives you the ability to reuse well-crafted components instead of starting from scratch each time you create a class You cannot compile a program that includes the same file multiple times

61 Summary When you create classes, you must decide on attributes and functions Coupling is a measure of the strength of the connection between two functions Tight coupling, which features dependence between functions, makes programs more prone to errors; loose coupling occurs when functions do not depend on others Cohesion refers to how well the operations in a function relate to one another

62 Declarations! Test 1 –Feb. 14, 2011 –7:30pm-9:30pm –This room –Closed books and closed notes. Contents –Lecture 1-Lecure 5 Question types: –True or False –Multiple choices –Fill in blanks –Reading programs