Starting Out with C++, 3 rd Edition 1 Chapter 13 – Introduction to Classes.

Slides:



Advertisements
Similar presentations
Chapter 13 – Introduction to Classes
Advertisements

Lesson 13 Introduction to Classes CS1 Lesson Introduction to Classes1.
Class and Objects.
Chapter 10.
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.
Starting Out with C++, 3 rd Edition 1 Chapter 9 – Pointers.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
ASP.NET Programming with C# and SQL Server First Edition
C++ fundamentals.
1 Review: Two Programming Paradigms Structural (Procedural) Object-Oriented PROGRAM PROGRAM FUNCTION OBJECT Operations Data OBJECT Operations Data OBJECT.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Review of C++ Programming Part II Sheng-Fang Huang.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to Classes and Objects Outline Introduction Classes, Objects, Member Functions and Data.
1 Object-Oriented Programming Using C++ CLASS 27.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
1 Chapter 9 Scope, Lifetime, and More on Functions.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
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 © 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  Hannu Laine C++-programming Part 1 Hannu Laine.
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
C++ Programming Basic Learning Prepared By The Smartpath Information systems
Structured Data and Classes Chapter 7. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
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.
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.
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
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.
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.
Array in C++ / review. An array contains multiple objects of identical types stored sequentially in memory. The individual objects in an array, referred.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
Programming Fundamentals1 Chapter 7 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.
1 Class 19 Chapter 13 – Creating a class definition.
1 Chapter 8 Scope, Lifetime, and More on Functions CS185/09 - Introduction to Programming Caldwell College.
1 Object-Oriented Programming Using C++ CLASS 17 Honors.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
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.
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:

Starting Out with C++, 3 rd Edition 1 Chapter 13 – Introduction to Classes

Starting Out with C++, 3 rd Edition Procedural and Object-Oriented Programming Procedural programming is a method of writing software. It is a programming practice centered on the procedures, or actions that take place in a program. Object-Oriented programming is centered around the object. Objects are created form abstract data types that encapsulate data and functions together.

Starting Out with C++, 3 rd Edition 3 What’s Wrong with Procedural Programming? Programs with excessive global data Complex and convoluted programs Programs that are difficult to modify and extend

Starting Out with C++, 3 rd Edition 4 What is Object-Oriented Programming? OOP is centered around the object, which packages together both the data and the functions that operate on the data.

Starting Out with C++, 3 rd Edition 5 Figure 13-1 Member Variables float width; float length; float area; Member Functions void setData(float w, float l) { … function code … } void calcArea(void) { … function code … } void getWidth(void) { … function code … } void getLength(void) { … function code … } void getArea(void) { … function code … }

Starting Out with C++, 3 rd Edition 6 Terminology In OOP, an object’s member variables are often called its attributes and its member functions are sometimes referred to as its behaviors or methods.

Starting Out with C++, 3 rd Edition 7 Figure 13-2

Starting Out with C++, 3 rd Edition 8 How are Objects Used? Although the use of objects is only limited by the programmer’s imagination, they are commonly used to create data types that are either very specific or very general in purpose.

Starting Out with C++, 3 rd Edition 9 General Purpose Objects –Creating data types that are improvements on C++’s built-in data types. For example, an array object could be created that works like a regular array, but additionally provides bounds-checking. –Creating data types that are missing from C++. For instance, an object could be designed to process currencies or dates as if they were built-in data types. –Creating objects that perform commonly needed tasks, such as input validation and screen output in a graphical user interface.

Starting Out with C++, 3 rd Edition 10 Application-Specific Objects Data types created for a specific application. For example, in an inventory program.

Starting Out with C++, 3 rd Edition Introduction to the Class In C++, the class is the construct primarily used to create objects. class class-name { // declaration statements here };

Starting Out with C++, 3 rd Edition 12 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); };

Starting Out with C++, 3 rd Edition 13 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.

Starting Out with C++, 3 rd Edition 14 Defining Member Functions Class member functions are defined similarly to regular functions. void Rectangle::setData(float w, float l) { width = w; length = l; }

Starting Out with C++, 3 rd Edition 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

Starting Out with C++, 3 rd Edition 16 Accessing an Object’s Members box.calcArea();

Starting Out with C++, 3 rd Edition 17 Pointers to Objects Rectangle *boxPtr; boxPtr = &box; boxPtr->setData(15,12);

Starting Out with C++, 3 rd Edition 18 Program 13-1 // This program demonstrates a simple class. #include // Rectangle class declaration. class Rectangle { private: float width; float length; float area; public: void setData(float, float); void calcArea(void); float getWidth(void); float getLength(void); float getArea(void); };

Starting Out with C++, 3 rd Edition 19 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; }

Starting Out with C++, 3 rd Edition 20 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; }

Starting Out with C++, 3 rd Edition 21 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; }

Starting Out with C++, 3 rd Edition 22 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

Starting Out with C++, 3 rd Edition 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.

Starting Out with C++, 3 rd Edition 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.

Starting Out with C++, 3 rd Edition 25 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; public: void setData(float, float); void calcArea(void); float getWidth(void); float getLength(void); float getArea(void); }; #endif

Starting Out with C++, 3 rd Edition 26 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; } // calcArea multiplies the private members width and length. // The result is stored in the private member area. void Rectangle::calcArea(void) { area = width * length; }

Starting Out with C++, 3 rd Edition 27 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; }

Starting Out with C++, 3 rd Edition 28 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;

Starting Out with C++, 3 rd Edition 29 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; }

Starting Out with C++, 3 rd Edition 30 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.

Starting Out with C++, 3 rd Edition 31 Table 13-4

Starting Out with C++, 3 rd Edition 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.

Starting Out with C++, 3 rd Edition 33 Program 13-3 #include #include "rectang2.h" // contains Rectangle class declaration // Don't forget to link this program with rectang2.cpp! using namespace std; 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); cout << "Here rectangle's data:\n"; cout << "width: " << box.getWidth() << endl; cout << "length: " << box.getLength() << endl; cout << "area: " << box.getArea() << endl; }

Starting Out with C++, 3 rd Edition Inline Member Functions When the body of a member function is defined inside a class declaration, it is declared inline.

Starting Out with C++, 3 rd Edition 35 Program 13-4 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; }

Starting Out with C++, 3 rd Edition 36 Program continues public: void setData(float, float); // Prototype float getWidth(void) { return width; } float getLength(void) { return length; } float getArea(void) { return area; } }; #endif 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(); }

Starting Out with C++, 3 rd Edition 37 Program continues Contents of the main program, pr13-4.cpp #include #include "rectang3.h" // contains Rectangle class declaration using namespace std; // 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;

Starting Out with C++, 3 rd Edition 38 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; }

Starting Out with C++, 3 rd Edition 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.

Starting Out with C++, 3 rd Edition 40 Program 13-5 // This program demonstrates a constructor. #include using namespace std; class Demo { public: Demo(void);// Constructor }; Demo::Demo(void) { cout << "Welcome to the constructor!\n"; }

Starting Out with C++, 3 rd Edition 41 Program continues int main() { Demo demoObj;// Declare a Demo object; cout << "This program demonstrates an object\n"; cout << "with a constructor.\n"; }

Starting Out with C++, 3 rd Edition 42 Program Output Welcome to the constructor. This program demonstrates an object with a constructor.

Starting Out with C++, 3 rd Edition 43 Program 13-6 // This program demonstrates a constructor. #include using namespace std; class Demo { public: Demo(void); // Constructor }; Demo::Demo(void) { cout << "Welcome to the constructor!\n"; }

Starting Out with C++, 3 rd Edition 44 Program continues int main() { cout << "This is displayed before the object\n"; cout << "is declared.\n\n"; Demo demoObj; cout << "\nThis is displayed after the object\n"; cout << "is declared.\n"; }

Starting Out with C++, 3 rd Edition 45 Program Output This is displayed before the object is declared. Welcome to the constructor. This is displayed after the object is declared.

Starting Out with C++, 3 rd Edition 46 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.

Starting Out with C++, 3 rd Edition 47 Program 13-7 // This program demonstrates a class with a constructor #include using namespace std; class InvItem { private: char *desc; int units; public: InvItem(void) { desc = new char[51]; } void setInfo(char *dscr, int un) { strcpy(desc, dscr); units = un;} char *getDesc(void) { return desc; } int getUnits(void) { return units; } };

Starting Out with C++, 3 rd Edition 48 Program continues int main() { InvItem stock; stock.setInfo("Wrench", 20); cout << "Item Description: " << stock.getDesc() << endl; cout << "Units on hand: " << stock.getUnits() << endl; }

Starting Out with C++, 3 rd Edition 49 Program Output Item Description: Wrench Units on hand: 20

Starting Out with C++, 3 rd Edition 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.

Starting Out with C++, 3 rd Edition 51 Program 13-8 // This program demonstrates a destructor. #include using namespace std; class Demo { public: Demo(void); // Constructor ~Demo(void); // Destructor }; Demo::Demo(void) { cout << "Welcome to the constructor!\n"; }

Starting Out with C++, 3 rd Edition 52 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"; }

Starting Out with C++, 3 rd Edition 53 Program Output Welcome to the constructor! This program demonstrates an object with a constructor and destructor. The destructor is now running.

Starting Out with C++, 3 rd Edition 54 Program 13-9 #include using namespace std; class InvItem { private: char *desc; int units; public: InvItem(void) { desc = new char[51]; } ~InvItem(void) { delete desc; } void setInfo(char *dscr, int un) { strcpy(desc, dscr); units = un;} char *getDesc(void) { return desc; } int getUnits(void) { return units; } };

Starting Out with C++, 3 rd Edition 55 Program continues int main() { InvItem stock; stock.setInfo("Wrench", 20); cout << "Item Description: " << stock.getDesc() << endl; cout << "Units on hand: " << stock.getUnits() << endl; }

Starting Out with C++, 3 rd Edition 56 Program Output Item Description: Wrench Units on hand: 20

Starting Out with C++, 3 rd Edition Constructors that Accept Arguments Information can be passed as arguments to an object’s constructor.

Starting Out with C++, 3 rd Edition 58 Program 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

Starting Out with C++, 3 rd Edition 59 Program continues Contents of main program, pr13-10.cpp #include #include "sale.h” using namespace std; 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; }

Starting Out with C++, 3 rd Edition 60 Program Output Enter the amount of the sale: The total of the sale is $132.50

Starting Out with C++, 3 rd Edition 61 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

Starting Out with C++, 3 rd Edition 62 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);

Starting Out with C++, 3 rd Edition 63 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; }

Starting Out with C++, 3 rd Edition 64 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

Starting Out with C++, 3 rd Edition Focus on Software Engineering: Input Validation Objects This section shows how classes may be designed to validate user input.

Starting Out with C++, 3 rd Edition 66 Program Content of Chrange.h // Specification file for the CharRange class #ifndef CHRANGE_H #define CHRANGE_H Class CharRange { Private: char input;// To hold the user input char lower;// Lowest valid character char upper// Highest valid character char *errMsg;// Pointer to user defined error message Public: CharRange (char, char, const char *); ~CharRange() { delete errMsg; } void setLower(char ch) { lower = ch; } void setUpper(char ch) { upper = ch; } char getLower() { return lower; } char getUpper() { return upper; } char getChar(); }; #endif

Starting Out with C++, 3 rd Edition 67 Program Content of Chrange.cpp // Implementation file for the CharRange class. #include <iostream #include #include”Chrange.h” using namespace std; //CharRange constructor. Parameters low and high hold the lower and upper characters in the // range. Str points to a C-string that is an error message to display when a character outside // the range is entered. CharRange::CharRange(char low, char high, const char *str) { //set the lower and upper characters lower = toupper(low); upper = toupper(high); //Allocate memory for the user-defined error message. errMsg = new char[strlen(str) + 1]; // Copy the user-defined error message to errMsg strcpy(errMsg, str); } Continue next screen

Starting Out with C++, 3 rd Edition 68 Program Content of Chrange.cpp - cont. // getChar member function. This function reads a character from the keyboard. // If the character is less than the contents of lower, or greater than the content of upper // (both private members of the CharRange class), the error message stored in the errMsg // is displayed and another character is read. If the character is within the range, it is // returned from the function. Char CharRange::getChar() { // Get a character from the keyboard and store it in input cin.get(input); cin.ignore(); //Convert input to uppercase input = toupper(input); while(input upper) { cout << errMsg; cin.get(input); cin.ignore(); input = toupper(input); } return input; }

Starting Out with C++, 3 rd Edition 69 Program // This program demonstrates the CharRange class. #include #include "chrange.h" // Remember to compile & link chrange.cpp using namespace std; int main() { // Create an object to check for characters // in the range J - N. CharRange input('J', 'N'); cout << "Enter any of the characters J, K, l, M, or N.\n"; cout << "Entering N will stop this program.\n"; while (input.getChar() != 'N'); }

Starting Out with C++, 3 rd Edition 70 Program Output with Example Input Enter any of the characters J, K, l, M, or N Entering N will stop this program. j k q n [Enter]

Starting Out with C++, 3 rd Edition Overloaded Constructors More than one constructor may be defined for a class.

Starting Out with C++, 3 rd Edition 72 Program Contents of invitem2.h #ifndef INVITEM2_H #define INVITEM2_H #include // Needed for strcpy function call. // 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(d)+1]; strcpy(desc, d); }

Starting Out with C++, 3 rd Edition 73 Program continues ~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 Contents of main program, pr13-13.cpp // This program demonstrates a class with overloaded constructors #include #include "invitem2.h” using namespace std; int main() {

Starting Out with C++, 3 rd Edition 74 Program continues InvItem item1("Wrench"); InvItem item2; item1.setUnits(15); item2.setInfo("Pliers", 25); 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; }

Starting Out with C++, 3 rd Edition 75 Program Output The following items are in inventory: Description: Wrench Units on Hand: 15 Description: Pliers Units on Hand 25

Starting Out with C++, 3 rd Edition Only One Default Constructor and one Destructor A class may only have one default constructor and one destructor.

Starting Out with C++, 3 rd Edition Arrays of Objects You may declare and work with arrays of class objects. InvItem inventory[40];

Starting Out with C++, 3 rd Edition 78 Program Contents of invitem3.h #ifndef INVITEM3_H #define INVITEM3_H #include // Needed for strcpy function call. // InvItem class declaration class InvItem { private: char *desc; int units; public: InvItem(int size = 51) { desc = new char[size]; } InvItem(char *d) { desc = new[strlen(d)+1]; strcpy(desc, d); }

Starting Out with C++, 3 rd Edition 79 Program continues InvItem(char *d, int u) { desc = new[strlen(d)+1]; strcpy(desc, d); units = u; } ~InvItem(void) { delete [] desc; } void setInfo(char * dscr, int u) { strcpy(desc, dscr); units = un;} void setUnits (int u) { units = u; } char *getDesc(void) { return desc; } int getUnits(void) { return units; } }; #endif Contents of main program, pr13-14.cpp // This program demonstrates an array of objects. #include #include "invitem3.h” using namespace std;

Starting Out with C++, 3 rd Edition 80 Program continues int main() { InvItem Inventory[5] = { InvItem("Adjustable Wrench", 10), InvItem("Screwdriver", 20), InvItem("Pliers", 35), InvItem("Ratchet", 10), InvItem("Socket Wrench", 7) }; cout << "Inventory Item\t\tUnits On Hand\n"; cout << " \n"; for (int Index = 0; Index < 5; Index++) { cout << setw(17) << Inventory[Index].GetDesc(); cout << setw(12) << Inventory[Index].GetUnits() << endl; }

Starting Out with C++, 3 rd Edition 81 Program Output Inventory ItemUnits On Hand Adjustable Wrench 10 Screwdriver 20 Pliers 35 Ratchet 10 Socket Wrench 7