SlideShare a Scribd company logo
 
Chapter 10 Defining Classes Copyright © 2008 Pearson Addison-Wesley.  All rights reserved.
Overview 10.1  Structures  10.2  Classes 10.3  Abstract Data Types 10.4  Introduction to Inheritance Slide 10-
10.1 Structures Copyright © 2008 Pearson Addison-Wesley.  All rights reserved.
What Is a Class? A class is a data type whose variables are objects Some pre-defined classes you have used are  int char ifstream You can define your own classes as well Slide 10-
Class Definitions A class definition includes A description of the kinds of values the variable  can hold A description of the member functions We will start by defining structures as a first step toward defining classes Slide 10-
Structures A structure can be viewed as an object Contains no member functions  (The structures used here have no member functions) Contains multiple values of  possibly different types The multiple values are logically related as a single item Example:  A bank Certificate of Deposit (CD)    has the following values:      a balance     an interest rate a term (months to maturity) Slide 10-
The Certificate of Deposit structure can be defined as struct CDAccount   {   double balance; double interest_rate;   int term;  //months to maturity }; Keyword struct begins a structure definition CDAccount is the structure tag or the structure’s type  Member names are identifiers declared in the braces The CD Definition Slide 10-  Remember this semicolon!
Using the Structure Structure definition is generally placed outside any function definition This makes the structure type available to all code  that follows the structure definition To declare two variables of type CDAccount:   CDAccount  my_account, your_account; My_account and your_account contain distinct  member variables  balance, interest_rate,  and term Slide 10-
The Structure Value The Structure Value Consists of the values of the member variables The value of an object of type CDAccount Consists of the values of the member variables   balance   interest_rate term Slide 10-
Specifying Member Variables Member variables are specific to the  structure variable in which they are declared Syntax to specify a member variable:  Structure_Variable_Name . Member_Variable_Name Given the declaration:   CDAccount  my_account, your_account; Use the dot operator to specify a member variable my_account.balance   my_account.interest_rate my_account.term Slide 10-
Member variables can be used just as any other variable of the same type my_account.balance = 1000; your_account.balance = 2500; Notice that my_account.balance and your_account.balance  are different variables! my_account.balance = my_account.balance + interest; Using Member Variables Slide 10-  Display 10.1 (1) Display 10.1 (2) Display 10.2
Member variable names duplicated between  structure types are not a problem.  super_grow.quantity and apples.quantity are  different variables stored in different locations Duplicate Names Slide 10-  struct FertilizerStock {   double  quantity ;   double nitrogen_content; }; FertilizerStock  super_grow; struct CropYield {   int  quantity ;   double size; }; CropYield  apples;
Structures as Arguments Structures can be arguments in function calls The formal parameter can be call-by-value The formal parameter can be call-by-reference Example: void get_data(CDAccount& the_account); Uses the structure type CDAccount we saw earlier as the type for a call-by-reference parameter Slide 10-
Structures as Return Types Structures can be the type of a value returned by a function Example: CDAccount shrink_wrap(double the_balance,    double the_rate,     int the_term) {    CDAccount temp;   temp.balance = the_balance;   temp.interest_rate = the_rate;   temp.term = the_term;   return temp; } Slide 10-
Using Function shrink_wrap shrink_wrap builds a complete structure value in temp, which is returned by the function We can use shrink_wrap to give a variable of  type CDAccount a value in this way:    CDAccount  new_account;  new_account = shrink_wrap(1000.00, 5.1, 11); Slide 10-
Assignment and Structures The assignment operator can be used to assign values to structure types Using the CDAccount structure again: CDAccount my_account, your_account; my_account.balance = 1000.00; my_account.interest_rate = 5.1; my_account.term = 12; your_account = my_account; Assigns all member variables in your_account the  corresponding values in my_account Slide 10-
Structures can contain member variables that are also structures struct PersonInfo contains a Date structure Hierarchical Structures Slide 10-  struct  Date {   int month; int day; int year; }; struct PersonInfo {   double height;   int weight;   Date birthday ; };
Using PersonInfo A variable of type PersonInfo is declared by   PersonInfo person1; To display the birth year of person1,  first access the  birthday member of person1   cout <<  person1.birthday… But we want the year, so we now specify the  year member of the birthday member     cout << person1.birthday.year; Slide 10-
A structure can be initialized when declared Example:   struct Date {   int month;   int day;   int year; }; Can be initialized in this way   Date  due_date = {12, 31, 2004}; Initializing Classes Slide 10-
Section 10.1 Conclusion Can you Write a definition for a structure type for records consisting of a person’s wage rate, accrued vacation (in whole days), and status (hourly or salaried). Represent the status as one of the two character values ‘H’ and ‘S’.  Call the type EmployeeRecord. Slide 10-
10.2 Classes Copyright © 2008 Pearson Addison-Wesley.  All rights reserved.
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 Slide 10-
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 Slide 10-
Class DayOfYear Definition class DayOfYear {   public:     void output( );       int month;       int day; }; Slide 10-  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;   }  Slide 10-
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;   } Slide 10-
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 Slide 10-
‘ ::’ and ‘.’ ‘ ::’ used with classes to identify a member  void DayOfYear::output( )   {   // function body   }       ‘ .’used with variables to identify a member   DayOfYear birthday; birthday.output( ); Slide 10-
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 Calling Member Functions Slide 10-  Display 10.3 (1) Display 10.3 (2)
Encapsulation Encapsulation is Combining a number of items, such as variables and functions, into a single package such as an object of a class Slide 10-
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 Slide 10-
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 Slide 10-
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 Slide 10-
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 Slide 10-
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;   } Slide 10-
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 Slide 10-
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  A New DayOfYear Slide 10-  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  Slide 10-
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 … }; Slide 10-
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;  Slide 10-
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; Slide 10-
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 Program Example: BankAccount Class Slide 10-  Display 10.5 ( 1) Display 10.5 ( 2) Display 10.5 ( 3) 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( ); Slide 10-
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;  } Slide 10-
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 Slide 10-
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   }; Slide 10-
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 Constructor Definition Slide 10-
Calling A Constructor (1) A constructor is not called like a normal member function:   BankAccount  account1;    account1.BankAccount(10, 50, 2.0); Slide 10-
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 Slide 10-
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 ( ); Slide 10-
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 }; Slide 10-
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 Slide 10-
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 Calling the Default Constructor Slide 10-  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 Slide 10-
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 Slide 10-
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? Slide 10-
10.3 Abstract Data Types Copyright © 2008 Pearson Addison-Wesley.  All rights reserved.
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 Slide 10-
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  Slide 10-
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 Slide 10-
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 Slide 10-
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 Slide 10-
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  Program Example The BankAccount ADT Slide 10-  Display 10.7 (1) Display 10.7 (2) Display 10.7 (3)
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 Slide 10-
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 Slide 10-
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? Slide 10-
10.4 Introduction to Inheritance Copyright © 2008 Pearson Addison-Wesley.  All rights reserved.
Inheritance Inheritance refers to derived classes Derived classes are obtained from another class  by adding features 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 Slide 10-
Inheritance and Streams cin and an input-file stream are input streams Input-file streams are members of the class ifstream Can be connected to a file cin is a member of the class istream  (no 'f ') Cannot be connected to a file The ifstream class is a derived class of the  istream class Slide 10-
Stream Parameters Review Example:  void two_sum(ifstream& source_file) { int n1, n2;   source_file >> n1 >> n2; cout << n1 &quot; + &quot; << n2  << &quot; = &quot; << (n1 + n2) << endl; } This code could be called using   ifstream fin; fin.open(&quot;input.dat&quot;); two_sum (fin); Slide 10-
two_sum Is Not Versatile Suppose you wished to use function two_sum with cin Since cin and input-file streams are both input  streams, this call to two_sum seems to make sense:   two_sum(cin); but it will not work! Slide 10-
Fixing two_sum This version of two_sum works with cin:  void better_two_sum(istream& source_file) { int n1, n2;   source_file >> n1 >> n2; cout << n1 &quot; + &quot; << n2  << &quot; = &quot; << (n1 + n2) << endl; } better_two_sum can be called with:   better_two_sum(cin); Slide 10-
Derived Classes and  Parameters better_two_sum can also be called with: ifstream fin; fin.open(&quot;input.dat&quot;); better_two_sum(fin); fin is of two types fin is an input-file stream fin is also of type istream fin has all the features of the input stream class,  plus added capabilities A formal parameter of type istream can be replaced by an argument of type ifstream Slide 10-
Derived Class Arguments A restriction exists when using derived classes  as arguments to functions A formal parameter of type istream, can only use  member functions of the istream class Using an argument of type ifstream with a formal  parameter of type istream does not allow using  the open and close methods of the ifstream class! Open files before calling the function Close files after calling the function Slide 10-
Inheritance Relationships 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 of  class A Slide 10-
Inheritance and Output ostream is the class of all output streams cout is of type ostream ofstream is the class of output-file streams The ofstream class is a child class of ostream This function can be called with ostream or  ofstream arguments void say_hello(ostream& any_out_stream)   { any_out_stream << &quot;Hello&quot;; } Slide 10-
Program Example: Another new_line Function The new_line function from Display 6.7 only  works with cin This version works for any input stream void new_line(istream& in_stream)   {   char symbol;   do   {    in_stream.get(symbol);   } while (symbol != '\n'); } Slide 10-
Program Example: Calling new_line The new version of new_line can be called with cin as the argument new_line(cin); If the original version of new_line is kept in the  program, this call produces the same result   new_line( ); New_line can also be called with an  input-file stream as an argument   new_line(fin); Slide 10-
Default Arguments It is not necessary to have two versions of  the new_line function A default value can be specified in the parameter list The default value is selected if no argument is  available for the parameter The new_line header can be written as   new_line (istream & in_stream = cin) If new_line is called without an argument, cin is used Slide 10-
Multiple Default Arguments When some formal parameters have default values and others do not All formal parameters with default values must be at the end of the parameter list Arguments are applied to the all formal parameters  in order just as we have seen before The function call must provide at least as many  arguments as there are parameters without default values Slide 10-
Default Argument Example void default_args(int arg1, int arg2 = -3)  {   cout << arg1 << '  ' << arg2 << endl;  } default_args can be called with one or  two parameters default_args(5);  //output is  5  -3 default_args(5, 6);  //output is  5  6 Slide 10-
Section 10.4 Conclusion Can you Identify the types of cin and cout? Describe how to connect a stream to a file? Define object? Define class? Describe the relationship between parent and child classes? List functions that format output? List functions that assist character input and output? Slide 10-
Chapter 10 -- End Slide 10-
Display 10.1  (1/2)   Slide 10-  Back Next
Display 10.1 (2/2) Slide 10-  Back Next
Display 10.2 Slide 10-  Back Next
Display 10.3 (1/2) Slide 10-  Back Next
Display 10.3 (2/2) Slide 10-  Back Next
Display 10.4  (1/2) Slide 10-  Back Next
Display 10.4 (2/2) Slide 10-  Back Next
Display 10.5 (1/4) Slide 10-  Back Next
Display 10.5 (2/4) Slide 10-  Back Next
Display 10.5 (3/4) Slide 10-  Back Next
Display 10.5 (4/4) Slide 10-  Back Next
Display 10.6  (1/3) Slide 10-  Back Next
Display 10.6 (2/3) Slide 10-  Back Next
Display 10.6  (3/3) Slide 10-  Back Next
Display 10.7 (1/3) Slide 10-  Back Next
Display 10.7 (2/3) Slide 10-  Back Next
Display 10.7 (3/3) Slide 10-  Back Next

More Related Content

PPT
Savitch ch 09
PPT
Savitch ch 10
PDF
Ejercicio ADA Instrucciones y Estructuras de Control
PDF
Ejercicio ADA Tipos de Datos en ADA
PPT
Programación con C/AL para Microsoft Business Solutions Navision
PPTX
Java Queue.pptx
PPT
Savitch Ch 03
PPTX
Enumeration in c#
Savitch ch 09
Savitch ch 10
Ejercicio ADA Instrucciones y Estructuras de Control
Ejercicio ADA Tipos de Datos en ADA
Programación con C/AL para Microsoft Business Solutions Navision
Java Queue.pptx
Savitch Ch 03
Enumeration in c#

Viewers also liked (20)

PPT
Savitch Ch 01
PPT
Savitch Ch 14
PPT
Savitch c++ ppt figs ch1
PPT
Savitch ch 022
PPT
Savitch Ch 12
PPT
Savitch Ch 02
PPT
Savitch Ch 11
PPT
Savitch Ch 08
PPT
Savitch ch 04
PPT
Savitch Ch 03
PPT
Savitch Ch 15
PPT
Savitch Ch 17
PPT
Savitch ch 16
PPT
Savitch Ch 18
PPT
Savitch Ch 07
PPT
Savitch Ch 13
PPT
Savitch Ch 06
PPT
Savitch ch 01
PPT
Savitch Ch 05
PPT
Savitch Ch 04
Savitch Ch 01
Savitch Ch 14
Savitch c++ ppt figs ch1
Savitch ch 022
Savitch Ch 12
Savitch Ch 02
Savitch Ch 11
Savitch Ch 08
Savitch ch 04
Savitch Ch 03
Savitch Ch 15
Savitch Ch 17
Savitch ch 16
Savitch Ch 18
Savitch Ch 07
Savitch Ch 13
Savitch Ch 06
Savitch ch 01
Savitch Ch 05
Savitch Ch 04
Ad

Similar to Savitch Ch 10 (20)

PPTX
OOP - Introduction
PPT
CHAPTER-7 C++ PROGRAMMING ( STRUCTURE IN C++)
PDF
Advanced CPP Lecture 1- Summer School 2014 - ACA CSE IITK
PPT
Classes, objects and methods
PPT
Data structure and problem solving ch01.ppt
PPTX
Class-١.pptx vbdbbdndgngngndngnnfndfnngn
PPTX
Classes and objects
PDF
Class and object
PPTX
Class and objects
PPTX
object oriented programming-classes and objects.pptx
PPT
2 lesson 2 object oriented programming in c++
PPTX
Lecture 2 (1)
PPT
Object and class presentation
PPTX
C++ppt. Classs and object, class and object
PPT
classandobjectunit2-150824133722-lva1-app6891.ppt
PPTX
C++ & Data Structure - Unit - first.pptx
PPT
C++ Programming Course
PPT
Ccourse 140618093931-phpapp02
PPTX
Oop objects_classes
OOP - Introduction
CHAPTER-7 C++ PROGRAMMING ( STRUCTURE IN C++)
Advanced CPP Lecture 1- Summer School 2014 - ACA CSE IITK
Classes, objects and methods
Data structure and problem solving ch01.ppt
Class-١.pptx vbdbbdndgngngndngnnfndfnngn
Classes and objects
Class and object
Class and objects
object oriented programming-classes and objects.pptx
2 lesson 2 object oriented programming in c++
Lecture 2 (1)
Object and class presentation
C++ppt. Classs and object, class and object
classandobjectunit2-150824133722-lva1-app6891.ppt
C++ & Data Structure - Unit - first.pptx
C++ Programming Course
Ccourse 140618093931-phpapp02
Oop objects_classes
Ad

More from Terry Yoast (20)

PPT
9781305078444 ppt ch12
PPT
9781305078444 ppt ch11
PPT
9781305078444 ppt ch10
PPT
9781305078444 ppt ch09
PPT
9781305078444 ppt ch08
PPT
9781305078444 ppt ch07
PPT
9781305078444 ppt ch06
PPT
9781305078444 ppt ch05
PPT
9781305078444 ppt ch04
PPT
9781305078444 ppt ch03
PPT
9781305078444 ppt ch02
PPT
9781305078444 ppt ch01
PPTX
9781337102087 ppt ch13
PPTX
9781337102087 ppt ch18
PPTX
9781337102087 ppt ch17
PPTX
9781337102087 ppt ch16
PPTX
9781337102087 ppt ch15
PPTX
9781337102087 ppt ch14
PPTX
9781337102087 ppt ch12
PPTX
9781337102087 ppt ch11
9781305078444 ppt ch12
9781305078444 ppt ch11
9781305078444 ppt ch10
9781305078444 ppt ch09
9781305078444 ppt ch08
9781305078444 ppt ch07
9781305078444 ppt ch06
9781305078444 ppt ch05
9781305078444 ppt ch04
9781305078444 ppt ch03
9781305078444 ppt ch02
9781305078444 ppt ch01
9781337102087 ppt ch13
9781337102087 ppt ch18
9781337102087 ppt ch17
9781337102087 ppt ch16
9781337102087 ppt ch15
9781337102087 ppt ch14
9781337102087 ppt ch12
9781337102087 ppt ch11

Recently uploaded (20)

PDF
RMMM.pdf make it easy to upload and study
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
01-Introduction-to-Information-Management.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
Institutional Correction lecture only . . .
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
Pharma ospi slides which help in ospi learning
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
master seminar digital applications in india
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PDF
Supply Chain Operations Speaking Notes -ICLT Program
RMMM.pdf make it easy to upload and study
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
STATICS OF THE RIGID BODIES Hibbelers.pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
01-Introduction-to-Information-Management.pdf
human mycosis Human fungal infections are called human mycosis..pptx
PPH.pptx obstetrics and gynecology in nursing
O7-L3 Supply Chain Operations - ICLT Program
Abdominal Access Techniques with Prof. Dr. R K Mishra
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
2.FourierTransform-ShortQuestionswithAnswers.pdf
Institutional Correction lecture only . . .
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Pharma ospi slides which help in ospi learning
Anesthesia in Laparoscopic Surgery in India
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
102 student loan defaulters named and shamed – Is someone you know on the list?
master seminar digital applications in india
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Supply Chain Operations Speaking Notes -ICLT Program

Savitch Ch 10

  • 1.  
  • 2. Chapter 10 Defining Classes Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
  • 3. Overview 10.1 Structures 10.2 Classes 10.3 Abstract Data Types 10.4 Introduction to Inheritance Slide 10-
  • 4. 10.1 Structures Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
  • 5. What Is a Class? A class is a data type whose variables are objects Some pre-defined classes you have used are int char ifstream You can define your own classes as well Slide 10-
  • 6. Class Definitions A class definition includes A description of the kinds of values the variable can hold A description of the member functions We will start by defining structures as a first step toward defining classes Slide 10-
  • 7. Structures A structure can be viewed as an object Contains no member functions (The structures used here have no member functions) Contains multiple values of possibly different types The multiple values are logically related as a single item Example: A bank Certificate of Deposit (CD) has the following values: a balance an interest rate a term (months to maturity) Slide 10-
  • 8. The Certificate of Deposit structure can be defined as struct CDAccount { double balance; double interest_rate; int term; //months to maturity }; Keyword struct begins a structure definition CDAccount is the structure tag or the structure’s type Member names are identifiers declared in the braces The CD Definition Slide 10- Remember this semicolon!
  • 9. Using the Structure Structure definition is generally placed outside any function definition This makes the structure type available to all code that follows the structure definition To declare two variables of type CDAccount: CDAccount my_account, your_account; My_account and your_account contain distinct member variables balance, interest_rate, and term Slide 10-
  • 10. The Structure Value The Structure Value Consists of the values of the member variables The value of an object of type CDAccount Consists of the values of the member variables balance interest_rate term Slide 10-
  • 11. Specifying Member Variables Member variables are specific to the structure variable in which they are declared Syntax to specify a member variable: Structure_Variable_Name . Member_Variable_Name Given the declaration: CDAccount my_account, your_account; Use the dot operator to specify a member variable my_account.balance my_account.interest_rate my_account.term Slide 10-
  • 12. Member variables can be used just as any other variable of the same type my_account.balance = 1000; your_account.balance = 2500; Notice that my_account.balance and your_account.balance are different variables! my_account.balance = my_account.balance + interest; Using Member Variables Slide 10- Display 10.1 (1) Display 10.1 (2) Display 10.2
  • 13. Member variable names duplicated between structure types are not a problem. super_grow.quantity and apples.quantity are different variables stored in different locations Duplicate Names Slide 10- struct FertilizerStock { double quantity ; double nitrogen_content; }; FertilizerStock super_grow; struct CropYield { int quantity ; double size; }; CropYield apples;
  • 14. Structures as Arguments Structures can be arguments in function calls The formal parameter can be call-by-value The formal parameter can be call-by-reference Example: void get_data(CDAccount& the_account); Uses the structure type CDAccount we saw earlier as the type for a call-by-reference parameter Slide 10-
  • 15. Structures as Return Types Structures can be the type of a value returned by a function Example: CDAccount shrink_wrap(double the_balance, double the_rate, int the_term) { CDAccount temp; temp.balance = the_balance; temp.interest_rate = the_rate; temp.term = the_term; return temp; } Slide 10-
  • 16. Using Function shrink_wrap shrink_wrap builds a complete structure value in temp, which is returned by the function We can use shrink_wrap to give a variable of type CDAccount a value in this way: CDAccount new_account; new_account = shrink_wrap(1000.00, 5.1, 11); Slide 10-
  • 17. Assignment and Structures The assignment operator can be used to assign values to structure types Using the CDAccount structure again: CDAccount my_account, your_account; my_account.balance = 1000.00; my_account.interest_rate = 5.1; my_account.term = 12; your_account = my_account; Assigns all member variables in your_account the corresponding values in my_account Slide 10-
  • 18. Structures can contain member variables that are also structures struct PersonInfo contains a Date structure Hierarchical Structures Slide 10- struct Date { int month; int day; int year; }; struct PersonInfo { double height; int weight; Date birthday ; };
  • 19. Using PersonInfo A variable of type PersonInfo is declared by PersonInfo person1; To display the birth year of person1, first access the birthday member of person1 cout << person1.birthday… But we want the year, so we now specify the year member of the birthday member cout << person1.birthday.year; Slide 10-
  • 20. A structure can be initialized when declared Example: struct Date { int month; int day; int year; }; Can be initialized in this way Date due_date = {12, 31, 2004}; Initializing Classes Slide 10-
  • 21. Section 10.1 Conclusion Can you Write a definition for a structure type for records consisting of a person’s wage rate, accrued vacation (in whole days), and status (hourly or salaried). Represent the status as one of the two character values ‘H’ and ‘S’. Call the type EmployeeRecord. Slide 10-
  • 22. 10.2 Classes Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
  • 23. 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 Slide 10-
  • 24. 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 Slide 10-
  • 25. Class DayOfYear Definition class DayOfYear { public: void output( ); int month; int day; }; Slide 10- Member Function Declaration
  • 26. 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; } Slide 10-
  • 27. 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; } Slide 10-
  • 28. 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 Slide 10-
  • 29. ‘ ::’ and ‘.’ ‘ ::’ used with classes to identify a member void DayOfYear::output( ) { // function body } ‘ .’used with variables to identify a member DayOfYear birthday; birthday.output( ); Slide 10-
  • 30. 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 Calling Member Functions Slide 10- Display 10.3 (1) Display 10.3 (2)
  • 31. Encapsulation Encapsulation is Combining a number of items, such as variables and functions, into a single package such as an object of a class Slide 10-
  • 32. 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 Slide 10-
  • 33. 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 Slide 10-
  • 34. 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 Slide 10-
  • 35. 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 Slide 10-
  • 36. 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; } Slide 10-
  • 37. 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 Slide 10-
  • 38. 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 A New DayOfYear Slide 10- Display 10.4 (1) Display 10.4 (2)
  • 39. 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 Slide 10-
  • 40. 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 … }; Slide 10-
  • 41. 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; Slide 10-
  • 42. 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; Slide 10-
  • 43. 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 Program Example: BankAccount Class Slide 10- Display 10.5 ( 1) Display 10.5 ( 2) Display 10.5 ( 3) Display 10.5 ( 4)
  • 44. 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( ); Slide 10-
  • 45. 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; } Slide 10-
  • 46. 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 Slide 10-
  • 47. 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 }; Slide 10-
  • 48. 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 Constructor Definition Slide 10-
  • 49. Calling A Constructor (1) A constructor is not called like a normal member function: BankAccount account1; account1.BankAccount(10, 50, 2.0); Slide 10-
  • 50. 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 Slide 10-
  • 51. 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 ( ); Slide 10-
  • 52. 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 }; Slide 10-
  • 53. 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 Slide 10-
  • 54. 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 Calling the Default Constructor Slide 10- Display 10.6 (1) Display 10.6 (2) Display 10.6 (3)
  • 55. 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 Slide 10-
  • 56. 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 Slide 10-
  • 57. 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? Slide 10-
  • 58. 10.3 Abstract Data Types Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
  • 59. 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 Slide 10-
  • 60. 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 Slide 10-
  • 61. 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 Slide 10-
  • 62. 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 Slide 10-
  • 63. 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 Slide 10-
  • 64. 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 Program Example The BankAccount ADT Slide 10- Display 10.7 (1) Display 10.7 (2) Display 10.7 (3)
  • 65. 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 Slide 10-
  • 66. 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 Slide 10-
  • 67. 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? Slide 10-
  • 68. 10.4 Introduction to Inheritance Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
  • 69. Inheritance Inheritance refers to derived classes Derived classes are obtained from another class by adding features 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 Slide 10-
  • 70. Inheritance and Streams cin and an input-file stream are input streams Input-file streams are members of the class ifstream Can be connected to a file cin is a member of the class istream (no 'f ') Cannot be connected to a file The ifstream class is a derived class of the istream class Slide 10-
  • 71. Stream Parameters Review Example: void two_sum(ifstream& source_file) { int n1, n2; source_file >> n1 >> n2; cout << n1 &quot; + &quot; << n2 << &quot; = &quot; << (n1 + n2) << endl; } This code could be called using ifstream fin; fin.open(&quot;input.dat&quot;); two_sum (fin); Slide 10-
  • 72. two_sum Is Not Versatile Suppose you wished to use function two_sum with cin Since cin and input-file streams are both input streams, this call to two_sum seems to make sense: two_sum(cin); but it will not work! Slide 10-
  • 73. Fixing two_sum This version of two_sum works with cin: void better_two_sum(istream& source_file) { int n1, n2; source_file >> n1 >> n2; cout << n1 &quot; + &quot; << n2 << &quot; = &quot; << (n1 + n2) << endl; } better_two_sum can be called with: better_two_sum(cin); Slide 10-
  • 74. Derived Classes and Parameters better_two_sum can also be called with: ifstream fin; fin.open(&quot;input.dat&quot;); better_two_sum(fin); fin is of two types fin is an input-file stream fin is also of type istream fin has all the features of the input stream class, plus added capabilities A formal parameter of type istream can be replaced by an argument of type ifstream Slide 10-
  • 75. Derived Class Arguments A restriction exists when using derived classes as arguments to functions A formal parameter of type istream, can only use member functions of the istream class Using an argument of type ifstream with a formal parameter of type istream does not allow using the open and close methods of the ifstream class! Open files before calling the function Close files after calling the function Slide 10-
  • 76. Inheritance Relationships 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 of class A Slide 10-
  • 77. Inheritance and Output ostream is the class of all output streams cout is of type ostream ofstream is the class of output-file streams The ofstream class is a child class of ostream This function can be called with ostream or ofstream arguments void say_hello(ostream& any_out_stream) { any_out_stream << &quot;Hello&quot;; } Slide 10-
  • 78. Program Example: Another new_line Function The new_line function from Display 6.7 only works with cin This version works for any input stream void new_line(istream& in_stream) { char symbol; do { in_stream.get(symbol); } while (symbol != '\n'); } Slide 10-
  • 79. Program Example: Calling new_line The new version of new_line can be called with cin as the argument new_line(cin); If the original version of new_line is kept in the program, this call produces the same result new_line( ); New_line can also be called with an input-file stream as an argument new_line(fin); Slide 10-
  • 80. Default Arguments It is not necessary to have two versions of the new_line function A default value can be specified in the parameter list The default value is selected if no argument is available for the parameter The new_line header can be written as new_line (istream & in_stream = cin) If new_line is called without an argument, cin is used Slide 10-
  • 81. Multiple Default Arguments When some formal parameters have default values and others do not All formal parameters with default values must be at the end of the parameter list Arguments are applied to the all formal parameters in order just as we have seen before The function call must provide at least as many arguments as there are parameters without default values Slide 10-
  • 82. Default Argument Example void default_args(int arg1, int arg2 = -3) { cout << arg1 << ' ' << arg2 << endl; } default_args can be called with one or two parameters default_args(5); //output is 5 -3 default_args(5, 6); //output is 5 6 Slide 10-
  • 83. Section 10.4 Conclusion Can you Identify the types of cin and cout? Describe how to connect a stream to a file? Define object? Define class? Describe the relationship between parent and child classes? List functions that format output? List functions that assist character input and output? Slide 10-
  • 84. Chapter 10 -- End Slide 10-
  • 85. Display 10.1 (1/2) Slide 10- Back Next
  • 86. Display 10.1 (2/2) Slide 10- Back Next
  • 87. Display 10.2 Slide 10- Back Next
  • 88. Display 10.3 (1/2) Slide 10- Back Next
  • 89. Display 10.3 (2/2) Slide 10- Back Next
  • 90. Display 10.4 (1/2) Slide 10- Back Next
  • 91. Display 10.4 (2/2) Slide 10- Back Next
  • 92. Display 10.5 (1/4) Slide 10- Back Next
  • 93. Display 10.5 (2/4) Slide 10- Back Next
  • 94. Display 10.5 (3/4) Slide 10- Back Next
  • 95. Display 10.5 (4/4) Slide 10- Back Next
  • 96. Display 10.6 (1/3) Slide 10- Back Next
  • 97. Display 10.6 (2/3) Slide 10- Back Next
  • 98. Display 10.6 (3/3) Slide 10- Back Next
  • 99. Display 10.7 (1/3) Slide 10- Back Next
  • 100. Display 10.7 (2/3) Slide 10- Back Next
  • 101. Display 10.7 (3/3) Slide 10- Back Next