1 Class 19 Chapter 13 – Creating a class definition.

Slides:



Advertisements
Similar presentations
Chapter 13 – Introduction to Classes
Advertisements

Lesson 13 Introduction to Classes CS1 Lesson Introduction to Classes1.
Contents o Introduction o Characteristics of Constructor. o Types of constructor. - Default Constructor - Parameterized Constructor - Copy Constructor.
Starting Out with C++: Early Objects 5th Edition
 2006 Pearson Education, Inc. All rights reserved Midterm review Introduction to Classes and Objects.
Object Oriented Programming.  OOP Basic Principles  C++ Classes  September 2004  John Edgar 22.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
More C++ Classes Systems Programming. Systems Programming: C++ Classes 2 Systems Programming: 2 C++ Classes  Preprocessor Wrapper  Time Class Case Study.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
1 Object-Oriented Programming Using C++ CLASS 27.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
1 CSE 2341 Object Oriented Programming with C++ Note Set #6.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
More C++ Classes Systems Programming. C++ Classes  Preprocessor Wrapper  Time Class Case Study –Two versions (old and new)  Class Scope and Assessing.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
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 © 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 © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Starting Out with C++ 2nd Edition, by Tony Gaddis 1 Chapter 7 – Classes and Structured Data.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
C++ Functions. Objectives 1. Be able to implement C++ functions 2. Be able to share data among functions 2.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Chapter 10 Introduction to Classes
Functions CIS Feb-06. Summary Slide Using Functions Mathematical Functions Misc. Functions Naming Conventions Writing Functions –Function Prototype.
 Classes in c++ Presentation Topic  A collection of objects with same properties and functions is known as class. A class is used to define the characteristics.
Starting Out with C++, 3 rd Edition 1 Chapter 13 – Introduction to Classes.
Structured Data and Classes Chapter 7. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.
Chapter 3 Part I. 3.1 Introduction Programs written in C ◦ All statements were located in function main Programs written in C++ ◦ Programs will consist.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
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.
Chapter 11 Friends and Overloaded Operators. Introduction to function equal // Date.h #ifndef _DATE_H_ #define _DATE_H_ class CDate { public: CDate();
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
1 CSE 2341 Object Oriented Programming with C++ Note Set #5.
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Lecture 19: Introduction to Classes Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: Introduction to Classes and Objects Starting Out with C++ Early.
February 28, 2005 Introduction to Classes. Object Oriented Programming An object is a software bundle of related variables and methods. Software objects.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
Separating Class Specification tMyn1 Separating Class Specification from Implementation Usually class declarations are stored in their own header files.
CS1201: Programming Language 2 Classes and objects.
11 Introduction to Object Oriented Programming (Continued) Cats.
Array in C++ / review. An array contains multiple objects of identical types stored sequentially in memory. The individual objects in an array, referred.
نظام المحاضرات الالكترونينظام المحاضرات الالكتروني Destructors The destructor fulfills the opposite functionality. It is automatically called when an object.
1 Introduction to Object Oriented Programming Chapter 10.
1 CSE 2341 Object Oriented Programming with C++ Note Set #7.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
Starting Out with C++, 3 rd Edition 1 Chapter 13 – Introduction to Classes Procedural and Object-Oriented Programming Procedural programming is a method.
1 Object-Oriented Programming Using C++ CLASS 2 Honors.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
1 CSE 2341 Object Oriented Programming with C++ Note Set #12.
Introduction to C++ programming Recap- session 1 Structure of C++ program Keywords Operators – Arithmetic – Relational – Logical Data types Classes and.
Data Structures Lecture 4: Classes in C++ Azhar Maqsood NUST Institute of Information Technology (NIIT)
Pointer to an Object Can define a pointer to an object:
Procedural and Object-Oriented Programming
Structured Data.
Chapter 7: Introduction to Classes and Objects
Abstract Data Types Programmer-created data types that specify
Classes.
Inheritance & Polymorphism
Introduction to Classes
Chapter 7: Introduction to Classes and Objects
Chapter 5 Classes.
CS1201: Programming Language 2
Introduction to Classes
Lecture 8 Object Oriented Programming (OOP)
Presentation transcript:

1 Class 19 Chapter 13 – Creating a class definition

Introduction to the Class In C++, the class is the construct primarily used to create objects. class class-name { declaration statements here };

3 Example: class Rectangle { private: float Width, Length, Area; public: void SetData(float, float); void CalcArea(void); float GetWidth(void); float GetLength(void); float GetArea(void); };

4 Access Specifiers The key words private and public are access specifiers. private means they can only be accessed by the member functions. public means they can be called from statements outside the class. –Note: the default access of a class is private, but it is still a good idea to use the private key word to explicitly declare private members. This clearly documents the access specification of the class.

Defining Member Functions Class member functions are defined similarly to regular functions. void Rectangle::SetData(float W, float L) { Width = W; Length = L; }

Defining an Instance of a Class Class objects must be defined after the class is declared. Defining a class object is called the instantiation of a class. Rectangle Box; //Box is an instance of Rectangle

7 Accessing an Object’s Members Box.CalcArea();

8 Pointers to Objects Rectangle *BoxPtr; BoxPtr = &Box; BoxPtr->SetData(15,12);

9 Program 13-1 P. 786 // This program demonstrates a simple class. #include // Rectangle class declaration. class Rectangle { private: float Width; float Length; float Area;

10 Program 13-1 public: void SetData(float, float); void CalcArea(void); float GetWidth(void); float GetLength(void); float GetArea(void); };

11 Program continues // SetData copies the argument W to private member Width and // L to private member Length. void Rectangle::SetData(float W, float L) { Width = W; Length = L; } // CalcArea multiplies the private members Width and Length. // The result is stored in the private member Area. void Rectangle::CalcArea(void) { Area = Width * Length; }

12 Program continues // GetWidth returns the value in the private member Width. float Rectangle::GetWidth(void) { return Width; } // GetLength returns the value in the private member Length. float Rectangle::GetLength(void) { return Length; } // GetArea returns the value in the private member Area. float Rectangle::GetArea(void) { return Area;;}

13 Program continues int main() { Rectangle Box; float Wide, Long; cout << "This program will calculate the area of a\n"; cout << "rectangle. What is the width? "; cin >> Wide; cout << "What is the length? "; cin >> Long; Box.SetData(Wide, Long); Box.CalcArea(); cout << "Here is the rectangle's data:\n"; cout << "Width: " << Box.GetWidth() << endl; cout << "Length: " << Box.GetLength() << endl; cout << "Area: " << Box.GetArea() << endl; }

14 Program Output This program will calculate the area of a rectangle. What is the width? 10 [Enter] What is the length? 5 [Enter] Here is the rectangle's data: Width: 10 Length: 5 Area: 50

Why Have Private Members? In object-oriented programming, an object should protect its important data by making it private and providing a public interface to access that data.

Focus on Software Engineering: Some Design Considerations Usually class declarations are stored in their own header files. Member function definitions are stored in their own.CPP files. The #ifndef directive allows a program to be conditionally compiled. This prevents a header file from accidentally being included more than once.

17 Program 13-2 Contents of RECTANG.H #ifndef RECTANGLE_H #define RECTANGLE_H // Rectangle class declaration. class Rectangle { private: float Width; float Length; float Area;

18 Program 13-2 public: void SetData(float, float); void CalcArea(void); float GetWidth(void); float GetLength(void); float GetArea(void); }; #endif

19 Program continues Contents of RECTANG.CPP #include "rectang.h" // SetData copies the argument W to private member // Width and // L to private member Length. void Rectangle::SetData(float W, float L) { Width = W; Length = L; }

20 Program continues Contents of RECTANG.CPP // CalcArea multiplies the private members Width and Length. // The result is stored in the private member Area. void Rectangle::CalcArea(void) { Area = Width * Length; }

21 Program continues // GetWidth returns the value in the private member Width. float Rectangle::GetWidth(void) { return Width; } // GetLength returns the value in the private member Length. float Rectangle::GetLength(void) { return Length; } // GetArea returns the value in the private member Area. float Rectangle::GetArea(void) { return Area; }

22 Program continues Contents of the main program, PR13-2.CPP // This program demonstrates a simple class. #include #include "rectang.h" // contains Rectangle class declaration using namespace std; // Don't forget to link this program with rectang.cpp! int main() { Rectangle Box; float Wide, Long; cout << "This program will calculate the area of a\n"; cout << "rectangle. What is the width? "; cin >> Wide; cout << "What is the length? "; cin >> Long;

23 Program continues Box.SetData(Wide, Long); Box.CalcArea(); cout << "Here rectangle's data:\n"; cout << "Width: " << Box.GetWidth() << endl; cout << "Length: " << Box.GetLength() << endl; cout << "Area: " << Box.GetArea() << endl; return 0; }

24 Performing I/O in a Class Object Notice that the Rectangle example has no cin or cout. This is so anyone who writes a program that uses the Rectangle class will not be “locked into” the way the class performs input or output. Unless a class is specifically designed to perform I/O, operations like user input and output are best left to the person designing the application.

25 Table 13-1 P. 799

Focus on Software Engineering: Using Private Member Functions A private member function may only be called from a function that is a member of the same object.

Inline Member Functions When the body of a member function is defined inside a class declaration, it is declared inline.

28 Contents of RECTANG3.H #ifndef RECTANGLE_H #define RECTANGLE_H // Rectangle class declaration. class Rectangle { private: float Width; float Length; float Area; void CalcArea(void) { Area = Width * Length; }

29 Program continues public: void SetData(float, float); // Prototype float GetWidth(void) { return Width; } float GetLength(void) { return Length; } float GetArea(void) { return Area; } }; #endif

30 Program continues Contents of RECTANG3.CPP #include "rectang3.h" // SetData copies the argument W to private member Width // and // L to private member Length. void Rectangle::SetData(float W, float L) { Width = W; Length = L; CalcArea(); }

31 Program continues Contents of the main program, PR13-4.CPP #include #include "rectang3.h" // contains Rectangle class declaration // Don't forget to link this program with rectang3.cpp! int main() { Rectangle Box; float Wide, Long; cout << "This program will calculate the area of a\n"; cout << "rectangle. What is the width? "; cin >> Wide; cout << "What is the length? "; cin >> Long;

32 Program continues Box.SetData(Wide, Long); cout << "Here rectangle's data:\n"; cout << "Width: " << Box.GetWidth() << endl; cout << "Length: " << Box.GetLength() << endl; cout << "Area: " << Box.GetArea() << endl; Return 0; }

33 Program Output This program will calculate the area of a rectangle. What is the width? 10 [Enter] What is the length? 5 [Enter] Here rectangle's data: Width: 10 Length: 5 Area: 50

Constructors A constructor is a member function that is automatically called when a class object is created. Constructors have the same name as the class. Constructors must be declared publicly. Constructors have no return type.

35 Program 13-5 P. 807 // This program demonstrates a constructor. #include using namespace std; class Demo { public: Demo(void);// Constructor }; Demo::Demo(void) { cout << "Welcome to the constructor!\n"; }

36 Program continues int main() { Demo DemoObj;// Declare a Demo object; cout << "This program demonstrates an object\n"; cout << "with a constructor.\n"; return 0; }

37 Program Output Welcome to the constructor. This program demonstrates an object with a constructor.

38 Constructor Arguments When a constructor does not have to accept arguments, it is called an object’s default constructor. Like regular functions, constructors may accept arguments, have default arguments, be declared inline, and be overloaded.

39 Program 13-7 P. 809 class InventoryItem { private: char *description; int units; public: InventoryItem(void) { description = new char[51]; } void setDescription(char *d) | { strcpy(description,d); } void setUnits(int u) { units = u; } char *getDescription(void) { return description; } int getUnits(void) { return units; } };

40 Program continues int main() { InventoryItem Stock; Stock.setDescription("Wrench“); Stock.setUnits(20); cout << "Item Description: " << Stock.getDescription() << endl; cout << "Units on hand: " << Stock.getUnits() << endl; return 0; }

41 Program Output Item Description: Wrench Units on hand: 20

Destructors A destructor is a member function that is automatically called when an object is destroyed. –Destructors have the same name as the class, preceded by a tilde character (~) –In the same way that a constructor is called then the object is created, the destructor is automatically called when the object is destroyed. –In the same way that a constructor sets things up when an object is created, a destructor performs shutdown procedures when an object is destroyed.

43 Program 13-8 P. 810 // This program demonstrates a constructor. #include using namespace std; class Demo { public: Demo(void); // Constructor ~Demo(void); // Destructor }; Demo::Demo(void) { cout << "Welcome to the constructor!\n"; }

44 Program continues Demo::~Demo(void) { cout << "The destructor is now running.\n"; } int main() { Demo DemoObj;// Declare a Demo object; cout << "This program demonstrates an object\n"; cout << "with a constructor and destructor.\n"; return 0; }

45 Program Output Welcome to the constructor! This program demonstrates an object with a constructor and destructor. The destructor is now running.

46 Program 13-9 class InventoryItem {private: char *description; int units; public: InventoryItem(void) { description = new char[51]; } ~InventoryItem() { delete [] description; } void setDescription(char *d) | { strcpy(description,d); } void setUnits(int u) { units = u; } char *getDescription(void) { return description; } int getUnits(void) { return units; } };

47 Program continues int main() { InventoryItem Stock; Stock.setDescription("Wrench"); Stock.setUnits(20); cout << "Item Description: " << Stock.getDescription() << endl; cout << "Units on hand: " << Stock.getUnits() << endl; return 0; }

48 Program Output Item Description: Wrench Units on hand: 20

Constructors that Accept Arguments Information can be passed as arguments to an object’s constructor.

50 Program P. 813 Contents of SALE.H #ifndef SALE_H #define SALE_H // Sale class declaration class Sale { private: float TaxRate; float Total; public: Sale(float Rate) { TaxRate = Rate; } void CalcSale(float Cost) { Total = Cost + (Cost * TaxRate) }; float GetTotal(void) { return Total; } }; #endif

51 Contents of main program, PR13-10.CPP #include using namespace std; #include "sale.h" int main() { Sale Cashier(0.06);// 6% sales tax rate float Amnt; cout.precision(2); cout.setf(ios::fixed | ios::showpoint); cout << "Enter the amount of the sale: "; cin >> Amnt; Cashier.CalcSale(Amnt); cout << "The total of the sale is $"; cout << Cashier.GetTotal << endl; return 0; }

52 Program Output Enter the amount of the sale: The total of the sale is $132.50

53 Program Contents of SALE2.H #ifndef SALE2_H #define SALE2_H // Sale class declaration class Sale { private: float TaxRate; float Total; public: Sale(float Rate = 0.05) { TaxRate = Rate; } void CalcSale(float Cost) { Total = Cost + (Cost * TaxRate) }; float GetTotal(void) { return total; } }; #endif

54 Program continues Contents of main program, PR13-11.CPP #include #include "sale2.h“ using namespace std; int main() { Sale Cashier1;// Use default sales tax rate Sale Cashier2(0.06); // Use 6% sales tax rate float Amnt; cout.precision(2); cout.set(ios::fixed | ios::showpoint); cout << "Enter the amount of the sale: "; cin >> Amnt; Cashier1.CalcSale(Amnt); Cashier2.CalcSale(Amnt);

55 Program continues cout << "With a 0.05 sales tax rate, the total\n"; cout << "of the sale is $"; cout << Cashier1.GetTotal() << endl; cout << "With a 0.06 sales tax rate, the total\n"; cout << "of the sale is $"; cout << Cashier2.GetTotal() << endl; return 0; }

56 Program Output Enter the amount of the sale: With a 0.05 sales tax rate, the total of the sale is $ With a 0.06 sales tax rate, the total of the sale is $132.50

Focus on Software Engineering: Input Validation Objects This section shows how classes may be designed to validate user input.

Overloaded Constructors More than one constructor may be defined for a class.

59 Program Contents of INVITEM2.H #ifndef INVITEM2_H #define INVITEM2_H #include // Needed for strcpy function call. using namespace std; // InvItem class declaration class InvItem {private: char *Desc; int Units; public: InvItem(int Size = 51) { Desc = new char[Size]; } InvItem(char *D) { Desc = new char[strlen(Desc)+1]; strcpy(Desc, D); }

60 ~InvItem(void) { delete[] Desc; } void SetInfo(char *D, int U) { strcpy(Desc, D); Units = U;} void SetUnits (int U) { Units = U; } char *GetDesc(void) { return Desc; } int GetUnits(void) { return Units; } }; #endif

61 Contents of main program, PR13-13.CPP // This program demonstrates a class with overloaded // constructors #include #include "invitem2.h" using namespace std; int main() { InvItem Item1("Wrench"); InvItem Item2; Item1.SetUnits(15); Item2.SetInfo("Pliers", 25);

62 cout << "The following items are in inventory:\n"; cout << "Description: " << Item1.GetDesc() << "\t\t"; cout << "Units on Hand: " << Item1.GetUnits() << endl; cout << "Description: " << Item2.GetDesc() << "\t\t"; cout << "Units on Hand: " << Item2.GetUnits() << endl; return 0; }

63 Program Output The following items are in inventory: Description: Wrench Units on Hand: 15 Description: Pliers Units on Hand 25

Only One Default Constructor and one Destructor A class may only have one default constructor and one destructor.