Chapter 10 Defining Classes. Chapter 10 Defining Classes.

Slides:



Advertisements
Similar presentations
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: Introduction to Classes and Objects Starting Out with C++ Early.
Advertisements

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Overview 10.1 Structures 10.2 Classes 10.3 Abstract Data Types.
Starting Out with C++: Early Objects 5th Edition
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10 Defining Classes.
C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects.
Copyright © 2003 Pearson Education, Inc. Slide 1.
Chapter 7: Introduction to Classes and Objects
C++ fundamentals.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: Introduction to Classes and Objects Starting Out with C++ Early.
Remarks  Can only manually release memory blocks allocated by new operator delete [] ptr; delete ptr;  Dynamically allocated variables and arrays will.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Introduction To Classes Chapter Procedural And Object Oriented Programming Procedural programming focuses on the process/actions that occur in a.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Procedural and Object-Oriented Programming 13.1.
1 Chapter 13 Introduction to Classes. 2 Topics 12.1 Procedural and Object-Oriented Programming 12.2 Introduction to Classes 12.3 Defining an Instance.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: Introduction to Classes and Objects Starting Out with C++
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: Introduction to Classes and Objects Starting Out with C++
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10 Defining Classes.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 7: Introduction.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Chapter 10 Defining Classes. Slide Overview 10.1 Structures 10.2 Classes 10.3 Abstract Data Types.
1 Chapter 10 Defining Classes. 2 Overview Introduction Classes (10.2) Abstract Data Types and Structures (10.1)(10.3) Abstract Data Types and Structures.
Chapter 7: Introduction to Classes and Objects Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified.
Structured Data and Classes Chapter 7. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.
Chapter 6 Defining Classes. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Introduction Structures (6.1) Classes (6.2)
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 10 Defining Classes.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 10 Defining Classes.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
CSci 162 Lecture 10 Martin van Bommel. Procedures vs Objects Procedural Programming –Centered on the procedures or actions that take place in a program.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 12 Introduction to Classes.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 10 Defining Classes.
C++ Class. © 2005 Pearson Addison-Wesley. All rights reserved 3-2 Abstract Data Types Figure 3.1 Isolated tasks: the implementation of task T does not.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: Introduction to Classes and Objects Starting Out with C++ Early.
Slide 1 Chapter 6 Structures and Classes. Slide 2 Learning Objectives  Structures  Structure types  Structures as function arguments  Initializing.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: Introduction to Classes and Objects Starting Out with C++
CSIS 123A Lecture 1 Intro To Classes Glenn Stevenson CSIS 113A MSJC.
Computer Programming II Lecture 5. Introduction to Object Oriented Programming (OOP) - There are two common programming methods : procedural programming.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 10 Defining Classes.
Pointer to an Object Can define a pointer to an object:
Structures and Classes
Procedural and Object-Oriented Programming
Chapter 7: Introduction to Classes and Objects
Chapter 7: Introduction to Classes and Objects
Abstract Data Types Programmer-created data types that specify
Chapter 10 Defining Classes. Chapter 10 Defining Classes.
Chapter 10 Defining Classes
Chapter 10 Defining Classes. Chapter 10 Defining Classes.
10.2 Classes Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 1.
Review: Two Programming Paradigms
Chapter 3: Using Methods, Classes, and Objects
About the Presentations
Introduction to Classes
Chapter 7: Introduction to Classes and Objects
Chapter 7: Introduction to Classes and Objects
Chapter 7: Introduction to Classes and Objects
Introduction to Object-oriented Programming
Object-Oriented Programming: Classes and Objects
Introduction to Classes
Chapter 9 Objects and Classes
Learning Objectives Classes Constructors Principles of OOP
Object Oriented Programming in java
Chapter 9 Introduction To Classes
Lecture 8 Object Oriented Programming (OOP)
Presentation transcript:

Chapter 10 Defining Classes

Overview 10.1 Structures ---- Object Oriented Programming 10.2 Classes 10.3 Abstract Data Types 10.4 Introduction to Inheritance

Objects are used to model real-world things. You can think of an object as a rather complex variable that contains multiple chunks of data

Real world objects have attributes Let’s consider an object that represents a time. Real world objects have attributes An object’s attributes describe its “state of being” seconds minutes am/pm hours

We hide the data from anyone outside of the object by making it “private” Joe WageEarner 12356 $12.50 40 A Time object

The attributes of an object are stored inside the object as data members. The hour value is stored as an integer 3 The minute value is stored as an integer 35 pm am or pm is stored as a string An “Time” object

An object also has behaviors behaviors define how you interact with the object What can you do with a time? set the hours Get the hours

getHour ( ) setHour( ) Behaviors are expressed as methods that give us controlled access to the data. These are “public” so that we can see them. Joe WageEarner 12356 getHour ( ) setHour( ) $12.50 40 An “Time” object

Then we write statements that send messages to the objects Joe WageEarner joe.getHours( ); 12356 getHour ( ) setHour ( ) $12.50 40 An “Time” object named joe

An Object’s Attributes and Behaviors Should Work Together this is called cohesion

Encapsulation Encapsulation is Combining a number of items, such as variables and functions, into a single package such as an object of a class Encapsulation in C++ In normal terms Encapsulation is defined as wrapping up of data and information under a single unit. In Object Oriented Programming, Encapsulation is defined as binding together the data and the functions that manipulates them. Consider a real life example of encapsulation, in a company there are different sections like the accounts section, finance section, sales section etc. The finance section handles all the financial transactions and keep records of all the data related to finance. Similarly the sales section handles all the sales related activities and keep records of all the sales. Now there may arise a situation when for some reason an official from finance section needs all the data about sales in a particular month. In this case, he is not allowed to directly access the data of sales section. He will first have to contact some other officer in the sales section and then request him to give the particular data. This is what encapsulation is. Here the data of sales section and the employees that can manipulate them are wrapped under a single name “sales section”. Encapsulation also lead to data abstraction or hiding. As using encapsulation also hides the data. In the above example the data of any of the section like sales, finance or accounts is hidden from any other section.

Encapsulation Time object getHour( ) member methods are calling method declared as public calling method we should not allow code outside of the object to reach in and change the data directly. Instead, we call methods in the object to do it for us. hour minute member data is declared as private The terms public and private are called access modifiers

Introduction to Classes A class is said to be an abstraction of the real world object that we are modeling. Classes are sometimes called Abstract Data Types. Class: a programmer-defined data type used to define objects It is a pattern for creating objects ex: string fName, lName; creates two objects of the string class

Introduction to Classes Class declaration format: class className { declaration; }; Notice the required ;

Access Specifiers Used to control access to members of the class. Each member is declared to be either public: can be accessed by functions outside of the class or private: can only be called by or accessed by functions that are members of the class

Class Example class Square { private: int side; public: void setSide(int s) { side = s; } int getSide() { return side; } }; Access specifiers

More on Access Specifiers Can be listed in any order in a class Can appear multiple times in a class If not specified, the default is private

Defining Member Functions Member functions are part of a class declaration Can place entire function definition inside the class declaration or Can place just the prototype inside the class declaration and write the function definition after the class

Types of Member Functions Acessor, get, getter function: uses but does not modify a member variable ex: getSide Mutator, set, setter function: modifies a member variable ex: setSide

Defining Member Functions Inside the Class Declaration Member functions defined inside the class declaration are called inline functions Only very short functions, like the one below, should be inline functions int getSide() { return side; }

Inline Member Function Example class Square { private: int side; public: void setSide(int s) { side = s; } int getSide() { return side; } }; inline functions

Defining Member Functions After the Class Declaration Put a function prototype in the class declaration In the function definition, precede the function name with the class name and scope resolution operator (::) int Square::getSide() { return side; } See pr7-02.cpp and pr7-03.cpp

Conventions and a Suggestion Member variables are usually private Accessor and mutator functions are usually public Use ‘get’ in the name of accessor functions, ‘set’ in the name of mutator functions Suggestion: calculate values to be returned in accessor functions when possible, to minimize the potential for stale data

Creating and Using Objects An object is an instance of a class It is defined just like other variables Square sq1, sq2; It can access members using dot operator sq1.setSide(5); cout << sq1.getSide(); See pr7-01.cpp

10.2 Classes

Classes A class is a data type whose variables are objects The definition of a class includes Description of the kinds of values of the member variables Description of the member functions A class description is somewhat like a structure definition plus the member variables

A Class Example To create a new type named DayOfYear as a class definition Decide on the values to represent This example’s values are dates such as July 4 using an integer for the number of the month Member variable month is an int (Jan = 1, Feb = 2, etc.) Member variable day is an int Decide on the member functions needed We use just one member function named output

Class DayOfYear Definition class DayOfYear { public: void output( ); int month; int day; }; Member Function Declaration

Defining a Member Function Member functions are declared in the class declaration Member function definitions identify the class in which the function is a member void DayOfYear::output() { cout << “month = “ << month << “, day = “ << day << endl; }

Member Function Definition Member function definition syntax: Returned_Type Class_Name::Function_Name(Parameter_List) { Function Body Statements } Example: void DayOfYear::output( ) { cout << “month = “ << month << “, day = “ << day << endl; }

The ‘::’ Operator ‘::’ is the scope resolution operator Tells the class a member function is a member of void DayOfYear::output( ) indicates that function output is a member of the DayOfYear class The class name that precedes ‘::’ is a type qualifier

‘::’ and ‘.’ ‘::’ used with classes to identify a member void DayOfYear::output( ) { // function body } ‘.’used with variables to identify a member DayOfYear birthday; birthday.output( );

Calling Member Functions Calling the DayOfYear member function output is done in this way: DayOfYear today, birthday; today.output( ); birthday.output( ); Note that today and birthday have their own versions of the month and day variables for use by the output function Display 10.3 (1) Display 10.3 (2)

Problems With DayOfYear Changing how the month is stored in the class DayOfYear requires changes to the program If we decide to store the month as three characters (JAN, FEB, etc.) instead of an int cin >> today.month will no longer work because we now have three character variables to read if(today.month == birthday.month) will no longer work to compare months The member function “output” no longer works

Ideal Class Definitions Changing the implementation of DayOfYear requires changes to the program that uses DayOfYear An ideal class definition of DayOfYear could be changed without requiring changes to the program that uses DayOfYear

Fixing DayOfYear To fix DayOfYear We need to add member functions to use when changing or accessing the member variables If the program never directly references the member variables, changing how the variables are stored will not require changing the program We need to be sure that the program does not ever directly reference the member variables

“Setter”Methods void Time::setHour(int hr) { hour = hr; } they are usually named “set” plus the name of the instance variable they will store the value in. void Time::setHour(int hr) { hour = hr; } setters never return anything setters always take a parameter

“Getter”Methods int Time::getHour( ) const { return hour; } getters take no parameters getters always return something int Time::getHour( ) const { return hour; } The const keyword is required to tell the compiler that the function does not alter the object. they are usually named “get” plus the name of the instance variable they will return the value of.

Public Or Private? C++ helps us restrict the program from directly referencing member variables private members of a class can only be referenced within the definitions of member functions If the program tries to access a private member, the compiler gives an error message Private members can be variables or functions

Private Variables Private variables cannot be accessed directly by the program Changing their values requires the use of public member functions of the class To set the private month and day variables in a new DayOfYear class use a member function such as void DayOfYear::set(int new_month, int new_day) { month = new_month; day = new_day; }

Public or Private Members The keyword private identifies the members of a class that can be accessed only by member functions of the class Members that follow the keyword private are private members of the class The keyword public identifies the members of a class that can be accessed from outside the class Members that follow the keyword public are public members of the class

A New DayOfYear Display 10.4 (1) Display 10.4 (2) The new DayOfYear class demonstrated in Display 10.4… Uses all private member variables Uses member functions to do all manipulation of the private member variables Member variables and member function definitions can be changed without changes to the program that uses DayOfYear Display 10.4 (1) Display 10.4 (2)

Using Private Variables It is normal to make all member variables private Private variables require member functions to perform all changing and retrieving of values Accessor functions allow you to obtain the values of member variables Example: get_day in class DayOfYear Mutator functions allow you to change the values of member variables Example: set in class DayOfYear

General Class Definitions The syntax for a class definition is class Class_Name { public: Member_Specification_1 Member_Specification_2 … Member_Specification_3 private: Member_Specification_n+1 Member_Specification_n+2 … };

Declaring an Object Once a class is defined, an object of the class is declared just as variables of any other type Example: To create two objects of type Bicycle: class Bicycle { // class definition lines }; Bicycle my_bike, your_bike;

Program Example: BankAccount Class This bank account class allows Withdrawal of money at any time All operations normally expected of a bank account (implemented with member functions) Storing an account balance Storing the account’s interest rate Display 10.5 ( 1) Display 10.5 ( 3) Display 10.5 ( 2) Display 10.5 ( 4)

Calling Public Members Recall that if calling a member function from the main function of a program, you must include the the object name: account1.update( );

Calling Private Members When a member function calls a private member function, an object name is not used fraction (double percent); is a private member of the BankAccount class fraction is called by member function update void BankAccount::update( ) { balance = balance + fraction(interest_rate)* balance; }

Constructors A constructor can be used to initialize member variables when an object is declared A constructor is a member function that is usually public A constructor is automatically called when an object of the class is declared A constructor’s name must be the name of the class A constructor cannot return a value No return type, not even void, is used in declaring or defining a constructor

Constructor Declaration A constructor for the BankAccount class could be declared as: class BankAccount { public: BankAccount(int dollars, int cents, double rate); //initializes the balance to $dollars.cents //initializes the interest rate to rate percent …//The rest of the BankAccount definition };

Constructor Definition The constructor for the BankAccount class could be defined as BankAccount::BankAccount(int dollars, int cents, double rate) { if ((dollars < 0) || (cents < 0) || ( rate < 0 )) { cout << “Illegal values for money or rate\n”; exit(1); } balance = dollars + 0.01 * cents; interest_rate = rate; } Note that the class name and function name are the same

Calling A Constructor (1) A constructor is not called like a normal member function: BankAccount account1; account1.BankAccount(10, 50, 2.0);

Calling A Constructor (2) A constructor is called in the object declaration BankAccount account1(10, 50, 2.0); Creates a BankAccount object and calls the constructor to initialize the member variables

Overloading Constructors Constructors can be overloaded by defining constructors with different parameter lists Other possible constructors for the BankAccount class might be BankAccount (double balance, double interest_rate); BankAccount (double balance); BankAccount (double interest_rate); BankAccount ( );

The Default Constructor A default constructor uses no parameters A default constructor for the BankAccount class could be declared in this way class BankAccount { public: BankAccount( ); // initializes balance to $0.00 // initializes rate to 0.0% … // The rest of the class definition };

Default Constructor Definition The default constructor for the BankAccount class could be defined as BankAccount::BankAccount( ) { balance = 0; rate = 0.0; } It is a good idea to always include a default constructor even if you do not want to initialize variables

Calling the Default Constructor The default constructor is called during declaration of an object An argument list is not used BankAccount account1; // uses the default BankAccount constructor BankAccount account1( ); // Is not legal Display 10.6 (1) Display 10.6 (2) Display 10.6 (3)

Initialization Sections An initialization section in a function definition provides an alternative way to initialize member variables BankAccount::BankAccount( ): balance(0), interest_rate(0.0); { // No code needed in this example } The values in parenthesis are the initial values for the member variables listed

The Assignment Operator Objects and structures can be assigned values with the assignment operator (=) Example: DayOfYear due_date, tomorrow; tomorrow.set(11, 19); due_date = tomorrow;

Class Memberwise Assignment Can use = to assign one object to another, or to initialize an object with an object’s data Examples (assuming class V): V v1, v2; … // statements that assign … // values to members of v1 v2 = v1; // assignment V v3 = v2; // initialization See pr11-05.cpp

Copy Constructors Special constructor used when a newly created object is initialized to the data of another object of same class Default copy constructor copies field-to-field, using memberwise assignment The default copy constructor works fine in most cases See pr11-06.cpp

Programmer-Defined Copy Constructors A copy constructor is one that takes a reference parameter to another object of the same class The copy constructor uses the data in the object passed as parameter to initialize the object being created Reference parameter should be const to avoid potential for data corruption

Copy Constructor – When Is It Used? A copy constructor is called when An object is initialized from an object of the same class An object is passed by value to a function An object is returned using a return statement from a function

Parameters and Initialization Member functions with parameters can use initialization sections BankAccount::BankAccount(int dollars, int cents, double rate) : balance (dollars + 0.01 * cents), interest_rate(rate) { if (( dollars < 0) || (cents < 0) || (rate < 0)) { cout << “Illegal values for money or rate\n”; exit(1); } } Notice that the parameters can be arguments in the initialization

Member Initializers C++11 supports a feature called member initialization Simply set member variables in the class Ex: class Coordinate { private: int x=1; int y=2; ... }; Creating a Coordinate object will initialize its x variable to 1 and y to 2 (assuming a constructor isn’t called that sets the values to something else)

Constructor Delegation C++11 also supports constructor delegation. This lets you have a constructor invoke another constructor in the initialization section. For example, make the default constructor call a second constructor that sets X to 99 and Y to 99: Coordinate::Coordinate() : Coordinate(99,99) { }

Section 10.2 Conclusion Can you Describe the difference between a class and a structure? Explain why member variables are usually private? Describe the purpose of a constructor? Use an initialization section in a function definition?

10.3 Abstract Data Types

Abstract Data Types A data type consists of a collection of values together with a set of basic operations defined on the values A data type is an Abstract Data Type (ADT) if programmers using the type do not have access to the details of how the values and operations are implemented

Classes To Produce ADTs To define a class so it is an ADT Separate the specification of how the type is used by a programmer from the details of how the type is implemented Make all member variables private members Basic operations a programmer needs should be public member functions Fully specify how to use each public function Helper functions should be private members

ADT Interface The ADT interface tells how to use the ADT in a program The interface consists of The public member functions The comments that explain how to use the functions The interface should be all that is needed to know how to use the ADT in a program

ADT Implementation The ADT implementation tells how the interface is realized in C++ The implementation consists of The private members of the class The definitions of public and private member functions The implementation is needed to run a program The implementation is not needed to write the main part of a program or any non-member functions

ADT Benefits Changing an ADT implementation does require changing a program that uses the ADT ADT’s make it easier to divide work among different programmers One or more can write the ADT One or more can write code that uses the ADT Writing and using ADTs breaks the larger programming task into smaller tasks

Program Example The BankAccount ADT In this version of the BankAccount ADT Data is stored as three member variables The dollars part of the account balance The cents part of the account balance The interest rate This version stores the interest rate as a fraction The public portion of the class definition remains unchanged from the version of Display 10.6 Display 10.7 (1) Display 10.7 (3) Display 10.7 (2)

Interface Preservation To preserve the interface of an ADT so that programs using it do not need to be changed Public member declarations cannot be changed Public member definitions can be changed Private member functions can be added, deleted, or changed

Information Hiding Information hiding was refered to earlier as writing functions so they can be used like black boxes ADT’s implement information hiding because The interface is all that is needed to use the ADT Implementation details of the ADT are not needed to know how to use the ADT Implementation details of the data values are not needed to know how to use the ADT

Section 10.3 Conclusion Can you Describe an ADT? Describe how to implement an ADT in C++? Define the interface of an ADT? Define the implementation of an ADT?

Object Oriented Programming Review from Chapter 1 Object Oriented Programming

Object Oriented Programming Abbreviated OOP Used for many modern programs Program is viewed as interacting objects Each object contains algorithms to describe its behavior Program design phase involves designing objects and their algorithms

OOP Characteristics Encapsulation Information hiding Objects contain their own data and algorithms Inheritance Writing reusable code Objects can inherit characteristics from other objects Polymorphism A single name can have multiple meanings depending on its context

Object-Oriented Programming Terminology object: software entity that combines data and functions that act on the data in a single unit attributes: the data items of an object, stored in member variables member functions (methods): procedures/ functions that act on the attributes of the class

More Object-Oriented Programming Terminology data hiding: restricting access to certain members of an object. The intent is to allow only member functions to directly access and modify the object’s data encapsulation: the bundling of an object’s data and procedures into a single entity

Why Hide Data? Protection – Member functions provide a layer of protection against inadvertent or deliberate data corruption Need-to-know – A programmer can use the data via the provided member functions. As long as the member functions return correct information, the programmer needn’t worry about implementation details.

Object-Oriented Programming Procedural programming uses variables to store data, and focuses on the processes/ functions that occur in a program. Data and functions are separate and distinct. Object-oriented programming is based on objects that encapsulate the data and the functions that operate on it.

Object Example Square object’s data item: side Member variables (attributes) int side; Member functions void setSide(int s) { side = s; } int getSide() { return side; } Square object’s data item: side Square object’s functions: setSide - set the size of the side of the square, getSide - return the size of the side of the square

10.3 Abstract Data Types

Abstract Data Types A data type consists of a collection of values together with a set of basic operations defined on the values A data type is an Abstract Data Type (ADT) if programmers using the type do not have access to the details of how the values and operations are implemented

Classes To Produce ADTs To define a class so it is an ADT Separate the specification of how the type is used by a programmer from the details of how the type is implemented Make all member variables private members Basic operations a programmer needs should be public member functions Fully specify how to use each public function Helper functions should be private members

ADT Interface The ADT interface tells how to use the ADT in a program The interface consists of The public member functions The comments that explain how to use the functions The interface should be all that is needed to know how to use the ADT in a program

ADT Implementation The ADT implementation tells how the interface is realized in C++ The implementation consists of The private members of the class The definitions of public and private member functions The implementation is needed to run a program The implementation is not needed to write the main part of a program or any non-member functions

ADT Benefits Changing an ADT implementation does require changing a program that uses the ADT ADT’s make it easier to divide work among different programmers One or more can write the ADT One or more can write code that uses the ADT Writing and using ADTs breaks the larger programming task into smaller tasks

Program Example The BankAccount ADT In this version of the BankAccount ADT Data is stored as three member variables The dollars part of the account balance The cents part of the account balance The interest rate This version stores the interest rate as a fraction The public portion of the class definition remains unchanged from the version of Display 10.6 Display 10.7 (1) Display 10.7 (3) Display 10.7 (2)

Interface Preservation To preserve the interface of an ADT so that programs using it do not need to be changed Public member declarations cannot be changed Public member definitions can be changed Private member functions can be added, deleted, or changed

Information Hiding Information hiding was refered to earlier as writing functions so they can be used like black boxes ADT’s implement information hiding because The interface is all that is needed to use the ADT Implementation details of the ADT are not needed to know how to use the ADT Implementation details of the data values are not needed to know how to use the ADT

Section 10.3 Conclusion Can you Describe an ADT? Describe how to implement an ADT in C++? Define the interface of an ADT? Define the implementation of an ADT?

Introduction to Inheritance 10.4 Introduction to Inheritance

Inheritance Inheritance refers to derived classes Derived classes are obtained from another class by adding features A derived class inherits the member functions and variables from its parent class without having to re-write them Example In Chapter 6 we saw that the class of input-file streams is derived from the class of all input streams by adding member functions such as open and close cin belongs to the class of all input streams, but not the class of input-file streams

Inheritance Example Natural hierarchy of bank accounts Most general: A Bank Account stores a balance A Checking Account “IS A” Bank Account that allows customers to write checks A Savings Account “IS A” Bank Account without checks but higher interest Accounts are more specific as we go down the hierarchy Each box can be a class

Inheritance Relationships The more specific class is a derived or child class The more general class is the base, super, or parent class If class B is derived from class A Class B is a derived class of class A Class B is a child of class A Class A is the parent of class B Class B inherits the member functions and variables of class A

Defining Derived Classes Give the class name as normal, but add a colon and then the name of the base class Objects of type SavingsAccount can access member functions defined in SavingsAccount or BankAccount class SavingsAccount : public BankAccount { … } Display 10.9 (1-3)

Section 10.4 Conclusion Can you Define object? Define class? Describe the relationship between parent and child classes? Describe the benefit of inheritance?

Abstract Data Types Programmer-created data types that specify legal values that can be stored operations that can be done on the values The user of an abstract data type (ADT) does not need to know any implementation details (e.g., how the data is stored or how the operations on it are carried out)

Abstraction in Software Development Abstraction allows a programmer to design a solution to a problem and to use data items without concern for how the data items are implemented This has already been encountered in the book: To use the pow function, you need to know what inputs it expects and what kind of results it produces You do not need to know how it works

Abstraction and Data Types Abstraction: a definition that captures general characteristics without details ex: An abstract triangle is a 3-sided polygon. A specific triangle may be scalene, isosceles, or equilateral Data Type: defines the kind of values that can be stored and the operations that can be performed on it

Object-Oriented Programming Terminology object: software entity that combines data and functions that act on the data in a single unit attributes: the data items of an object, stored in member variables member functions (methods): procedures/ functions that act on the attributes of the class

More Object-Oriented Programming Terminology data hiding: restricting access to certain members of an object. The intent is to allow only member functions to directly access and modify the object’s data encapsulation: the bundling of an object’s data and procedures into a single entity

Why Hide Data? Protection – Member functions provide a layer of protection against inadvertent or deliberate data corruption Need-to-know – A programmer can use the data via the provided member functions. As long as the member functions return correct information, the programmer needn’t worry about implementation details.

7.2 Object-Oriented Programming Procedural programming uses variables to store data, and focuses on the processes/ functions that occur in a program. Data and functions are separate and distinct. Object-oriented programming is based on objects that encapsulate the data and the functions that operate on it.

Object Example Square object’s data item: side Member variables (attributes) int side; Member functions void setSide(int s) { side = s; } int getSide() { return side; } Square object’s data item: side Square object’s functions: setSide - set the size of the side of the square, getSide - return the size of the side of the square

7.3 Introduction to Classes Class: a programmer-defined data type used to define objects It is a pattern for creating objects ex: string fName, lName; creates two objects of the string class

Introduction to Classes Class declaration format: class className { declaration; }; Notice the required ;

Access Specifiers Used to control access to members of the class. Each member is declared to be either public: can be accessed by functions outside of the class or private: can only be called by or accessed by functions that are members of the class

Class Example class Square { private: int side; public: void setSide(int s) { side = s; } int getSide() { return side; } }; Access specifiers

More on Access Specifiers Can be listed in any order in a class Can appear multiple times in a class If not specified, the default is private

Creating and Using Objects An object is an instance of a class It is defined just like other variables Square sq1, sq2; It can access members using dot operator sq1.setSide(5); cout << sq1.getSide(); See pr7-01.cpp

Types of Member Functions Acessor, get, getter function: uses but does not modify a member variable ex: getSide Mutator, set, setter function: modifies a member variable ex: setSide

Defining Member Functions Member functions are part of a class declaration Can place entire function definition inside the class declaration or Can place just the prototype inside the class declaration and write the function definition after the class

Defining Member Functions Inside the Class Declaration Member functions defined inside the class declaration are called inline functions Only very short functions, like the one below, should be inline functions int getSide() { return side; }

Inline Member Function Example class Square { private: int side; public: void setSide(int s) { side = s; } int getSide() { return side; } }; inline functions

Defining Member Functions After the Class Declaration Put a function prototype in the class declaration In the function definition, precede the function name with the class name and scope resolution operator (::) int Square::getSide() { return side; } See pr7-02.cpp and pr7-03.cpp

Conventions and a Suggestion Member variables are usually private Accessor and mutator functions are usually public Use ‘get’ in the name of accessor functions, ‘set’ in the name of mutator functions Suggestion: calculate values to be returned in accessor functions when possible, to minimize the potential for stale data

Tradeoffs of Inline vs. Regular Member Functions When a regular function is called, control passes to the called function the compiler stores return address of call, allocates memory for local variables, etc. Code for an inline function is copied into the program in place of the call when the program is compiled This makes alarger executable program, but There is less function call overhead, and possibly faster execution

Constructors A constructor is a member function that is often used to initialize data members of a class Is called automatically when an object of the class is created It must be a public member function It must be named the same as the class It must have no return type See pr7-04.cpp and pr7-05.cpp

Constructor – 2 Examples Inline: class Square { . . . public: Square(int s) { side = s; } }; Declaration outside the class: Square(int); //prototype //in class Square::Square(int s) side = s; }

Overloading Constructors A class can have more than 1 constructor Overloaded constructors in a class must have different parameter lists Square(); Square(int); See pr7-06.cpp

The Default Constructor Constructors can have any number of parameters, including none A default constructor is one that takes no arguments either due to No parameters or All parameters have default values If a class has any programmer-defined constructors, it must have a programmer- defined default constructor

Default Constructor Example class Square { private: int side; public: Square() // default { side = 1; } // constructor // Other member // functions go here }; Has no parameters

Another Default Constructor Example class Square { private: int side; public: Square(int s = 1) // default { side = s; } // constructor // Other member // functions go here }; Has parameter but it has a default value

Invoking a Constructor To create an object using the default constructor, use no argument list and no () Square square1; To create an object using a constructor that has parameters, include an argument list Square square1(8);

Destructors (i.e., it cannot be overloaded) Is a public member function automatically called when an object is destroyed The destructor name is ~className, e.g., ~Square It has no return type It takes no arguments Only 1 destructor is allowed per class (i.e., it cannot be overloaded) See pr7-07.cpp

Private Member Functions A private member function can only be called by another member function of the same class It is used for internal processing by the class, not for use outside of the class See pr7-08.cpp

Passing Objects to Functions A class object can be passed as an argument to a function When passed by value, function makes a local copy of object. Original object in calling environment is unaffected by actions in function When passed by reference, function can use ‘set’ functions to modify the object. See pr7-09.cpp

Notes on Passing Objects Using a value parameter for an object can slow down a program and waste space Using a reference parameter speeds up program, but allows the function to modify data in the parameter

Notes on Passing Objects To save space and time, while protecting parameter data that should not be changed, use a const reference parameter void showData(const Square &s) // header In order to for the showData function to call Square member functions, those functions must use const in their prototype and header: int Square::getSide() const;

Returning an Object from a Function A function can return an object Square initSquare(); // prototype s1 = initSquare(); // call The function must define a object for internal use to use with return statement

Returning an Object Example Square initSquare() { Square s; // local variable int inputSize; cout << "Enter the length of side: "; cin >> inputSize; s.setSide(inputSize); return s; } See pr7-10.cpp

Object Composition Occurs when an object is a member variable of another object. It is often used to design complex objects whose members are simpler objects ex. Define a rectangle class. Then, define a carpet class and use a rectangle object as a member of a carpet object. See pr7-11.cpp

Object Composition, cont.

Separating Class Specification, Implementation, and Client Code Separating class declaration, member function definitions, and the program that uses the class into separate files is considered good design

Using Separate Files Place class declaration in a header file that serves as the class specification file. Name the file classname.h (for example, Square.h) Place member function definitions in a class implementation file. Name the file classname.cpp (for example, Square.cpp)This file should #include the class specification file. A client program (client code) that uses the class must #include the class specification file and be compiled and linked with the class implementation file. See pr7-12.cpp, Rectangle.cpp, and Rectangle.h

Include Guards Used to prevent a header file from being included twice Format: #ifndef symbol_name #define symbol_name . . . (normal contents of header file) #endif symbol_name is usually the name of the header file, in all capital letters: #ifndef SQUARE_H #define SQUARE_H . . .

Chapter 10 -- End

Display 10.1 (1/2) Back Next

Display 10.1 (2/2) Back Next

Display 10.2 Back Next

Display 10.3 (1/2) Back Next

Display 10.3 (2/2) Back Next

Display 10.4 (1/2) Back Next

Display 10.4 (2/2) Back Next

Display 10.5 (1/4) Back Next

Display 10.5 (2/4) Back Next

Display 10.5 (3/4) Back Next

Display 10.5 (4/4) Back Next

Display 10.6 (1/3) Back Next

Display 10.6 (2/3) Back Next

Display 10.6 (3/3) Back Next

Display 10.7 (1/3) Back Next

Display 10.7 (2/3) Back Next

Display 10.7 (3/3) Back Next

Display 10.8 Back Next

Display 10.9 (1/3) Back Next

Display 10.9 (2/3) Back Next

Display 10.9 (3/3) Back Next

Introduction to Computers and C++ Programming Chapter 1 Introduction to Computers and C++ Programming

Chapter 7: Introduction to Classes and Objects Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda

Topics 7.1 Abstract Data Types 7.2 Object-Oriented Programming 7.3 Introduction to Classes 7.4 Creating and Using Objects 7.5 Defining Member Functions 7.6 Constructors 7.7 Destructors 7.8 Private Member Functions

Topics (Continued) 7.9 Passing Objects to Functions 7.10 Object Composition 7.11 Separating Class Specification, Implementation, and Client Code

7.1 Abstract Data Types Structures/Classes that are defined by the operations that are performed by/on it. Have no implementation defined “interface contract” that the object provides

7.1 Abstract Data Types Programmer-created data types that specify legal values that can be stored operations that can be done on the values The user of an abstract data type (ADT) does not need to know any implementation details (e.g., how the data is stored or how the operations on it are carried out)

Abstraction in Software Development Abstraction allows a programmer to design a solution to a problem and to use data items without concern for how the data items are implemented This has already been encountered in the book: To use the pow function, you need to know what inputs it expects and what kind of results it produces You do not need to know how it works

Abstraction and Data Types Abstraction: a definition that captures general characteristics without details ex: An abstract triangle is a 3-sided polygon. A specific triangle may be scalene, isosceles, or equilateral Data Type: defines the kind of values that can be stored and the operations that can be performed on it

7.6 Constructors A constructor is a member function that is often used to initialize data members of a class Is called automatically when an object of the class is created It must be a public member function It must be named the same as the class It must have no return type See pr7-04.cpp and pr7-05.cpp

Constructor – 2 Examples Inline: class Square { . . . public: Square(int s) { side = s; } }; Declaration outside the class: Square(int); //prototype //in class Square::Square(int s) side = s; }

Overloading Constructors A class can have more than 1 constructor Overloaded constructors in a class must have different parameter lists Square(); Square(int); See pr7-06.cpp

The Default Constructor Constructors can have any number of parameters, including none A default constructor is one that takes no arguments either due to No parameters or All parameters have default values If a class has any programmer-defined constructors, it must have a programmer- defined default constructor

Default Constructor Example class Square { private: int side; public: Square() // default { side = 1; } // constructor // Other member // functions go here }; Has no parameters

Another Default Constructor Example class Square { private: int side; public: Square(int s = 1) // default { side = s; } // constructor // Other member // functions go here }; Has parameter but it has a default value

Invoking a Constructor To create an object using the default constructor, use no argument list and no () Square square1; To create an object using a constructor that has parameters, include an argument list Square square1(8);

7.7 Destructors Is a public member function automatically called when an object is destroyed The destructor name is ~className, e.g., ~Square It has no return type It takes no arguments Only 1 destructor is allowed per class (i.e., it cannot be overloaded) See pr7-07.cpp

7. 8 Private Member Functions A private member function can only be called by another member function of the same class It is used for internal processing by the class, not for use outside of the class See pr7-08.cpp

7.9 Passing Objects to Functions A class object can be passed as an argument to a function When passed by value, function makes a local copy of object. Original object in calling environment is unaffected by actions in function When passed by reference, function can use ‘set’ functions to modify the object. See pr7-09.cpp

Notes on Passing Objects Using a value parameter for an object can slow down a program and waste space Using a reference parameter speeds up program, but allows the function to modify data in the parameter

Notes on Passing Objects To save space and time, while protecting parameter data that should not be changed, use a const reference parameter void showData(const Square &s) // header In order to for the showData function to call Square member functions, those functions must use const in their prototype and header: int Square::getSide() const;

Returning an Object from a Function A function can return an object Square initSquare(); // prototype s1 = initSquare(); // call The function must define a object for internal use to use with return statement

Returning an Object Example Square initSquare() { Square s; // local variable int inputSize; cout << "Enter the length of side: "; cin >> inputSize; s.setSide(inputSize); return s; } See pr7-10.cpp

7.10 Object Composition Occurs when an object is a member variable of another object. It is often used to design complex objects whose members are simpler objects ex. (from book): Define a rectangle class. Then, define a carpet class and use a rectangle object as a member of a carpet object. See pr7-11.cpp

Object Composition, cont.

Chapter 7: Introduction to Classes and Objects Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda

7.11 Separating Class Specification, Implementation, and Client Code Separating class declaration, member function definitions, and the program that uses the class into separate files is considered good design

Using Separate Files Place class declaration in a header file that serves as the class specification file. Name the file classname.h (for example, Square.h) Place member function definitions in a class implementation file. Name the file classname.cpp (for example, Square.cpp)This file should #include the class specification file. A client program (client code) that uses the class must #include the class specification file and be compiled and linked with the class implementation file. See pr7-12.cpp, Rectangle.cpp, and Rectangle.h

Include Guards Used to prevent a header file from being included twice Format: #ifndef symbol_name #define symbol_name . . . (normal contents of header file) #endif symbol_name is usually the name of the header file, in all capital letters: #ifndef SQUARE_H #define SQUARE_H . . .

What Should Be Done Inside vs. Outside the Class Class should be designed to provide functions to store and retrieve data In general, input and output (I/O) should be done by functions that use class objects, rather than by class member functions See Rectangle.h, Rectangle.cpp, and pr7-12.cpp

Chapter 7: Introduction to Classes and Objects Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda

7.14 Introduction to Object-Oriented Analysis and Design Object-Oriented Analysis: that phase of program development when the program functionality is determined from the requirements It includes identification of objects and classes definition of each class's attributes identification of each class's behaviors definition of the relationship between classes

Identify Objects and Classes Consider the major data elements and the operations on these elements Candidates include user-interface components (menus, text boxes, etc.) I/O devices physical objects historical data (employee records, transaction logs, etc.) the roles of human participants

Define Class Attributes Attributes are the data elements of an object of the class They are necessary for the object to work in its role in the program

Define Class Behaviors For each class, Identify what an object of a class should do in the program The behaviors determine some of the member functions of the class

Relationships Between Classes Possible relationships Access ("uses-a") Ownership/Composition ("has-a") Inheritance ("is-a")

Finding the Classes Technique: Write a description of the problem domain (objects, events, etc. related to the problem) List the nouns, noun phrases, and pronouns. These are all candidate objects Refine the list to include only those objects that are relevant to the problem

Determine Class Responsibilities What is the class responsible to know? What is the class responsible to do? Use these to define some of the member functions

Object Reuse A well-defined class can be used to create objects in multiple programs By re-using an object definition, program development time is shortened One goal of object-oriented programming is to support object reuse

Chapter 7: Introduction to Classes and Objects Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda