1 CSE 2341 Object Oriented Programming with C++ Note Set #5.

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.
Exercise 2.
Class and Objects.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
 2006 Pearson Education, Inc. All rights reserved Midterm review Introduction to Classes and Objects.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
More C++ Classes Systems Programming. Systems Programming: C++ Classes 2 Systems Programming: 2 C++ Classes  Preprocessor Wrapper  Time Class Case Study.
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.
Introduction to C++. Overview C++? What are references Object orientation Classes Access specifiers Constructor/destructor Interface-implementation separation.
You gotta be cool. Access Functions and Utility Functions Preprocessor Wrapper Looking Ahead to Composition and Inheritance Object Size Class Scope and.
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.
Lecture # 8 Constructors Overloading. Topics We will discuss the following main topics: – Static Class Members – Overloaded Methods – Overloaded Constructors.
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 © 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.
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.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private: //...
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.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 16: Introduction to C++
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.
By Joaquin Vila Prepared by Sally Scott ACS 168 Problem Solving Using the Computer Week 13 More on Classes Chapter 8 Week 13 More on Classes Chapter 8.
1 Review: C++ class represents an ADT 2 kinds of class members: data members and function members Class members are private by default Data members are.
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.
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.
نظام المحاضرات الالكترونينظام المحاضرات الالكتروني Object Oriented Programming(Objects& Class) Classes are an expanded concept of data structures: like.
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.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 11: Classes and Data Abstraction.
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.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
1 CSE 2341 Object Oriented Programming with C++ Note Set #12.
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
Chapter 7: Introduction to Classes and Objects
Abstract Data Types Programmer-created data types that specify
Classes.
Review: Two Programming Paradigms
Introduction to Classes
Chapter 7: Introduction to Classes and Objects
Chapter 5 Classes.
This technique is Called “Divide and Conquer”.
Introduction to Classes
Lecture 8 Object Oriented Programming (OOP)
More C++ Classes Systems Programming.
Presentation transcript:

1 CSE 2341 Object Oriented Programming with C++ Note Set #5

2 Quick Look Introduction to the C++ class –constructors/destructors –interface/implementation –attributes/member functions –using the class in a main driver

3 The Class in C++ Objects are implemented with a class in C++. Basic syntactical features of a class: class className { //declaration statements here };

4 Example Class class Rectangle { private: int length, width, area; public: void setData(int, int); void calcArea(); int getLength(); int getWidth(); void setWidth(int); int getArea(); }; access specifiers

5 Access Specifiers 3 different access specifiers –public, private, protected –prevent members of the class from being used in ways in which they were not intended Private: –only accessible by member functions of the class Public: –accessible by any function Protected: –accessible by a derived class (to come later) NOTE: Default access is private but should be explicitly indicated.

6 Defining a member function of a class Can be defined inside the class interface or externally in a separate file void Rectangle::setData(int w, int l) { width = w; length = l; area = width * length; }

7 Defining an Instance of a Class class objects may only be defined after the class is declared Instantiation –defining a class object of a particular type Rectangle box; box is an instance of Rectangle

8 Accessing a public member given an instance of an object of type T, public members of the function are accessed using the. (dot) operator Generally: T.publicMember(); Example: box.setData(2,3);

9 Pointers to Objects pointers to object types are acceptable use the -> operator to access public members from a pointer Rectangle box; Rectangle* boxPtr; boxPtr = &box; boxPtr -> setData(4, 5);

10 Interface vs. Implementation Interface – the declaration of the class Implementation – the definition of the member functions interface and implementation are typically separated into different files (also separate from main driver file) For Rectangle Class –Interface – Rectangle.h –Implementation – Rectangle.cpp

11 Rectangle.h //Declaration of class Rectangle #ifndef RECTANGLE_H #define RECTANGLE_H class Rectangle { public: void setWidth(float); void setLength(float); float getWidth(); float getLength(); float getArea(); private: float width; float length }; #endif Rectangle.h

12 #ifndef #ifndef RECTANGLE_H #define RECTANGLE_H // Other code here #endif This code ensures that the class is only defined once. If multiple source files include Rectangle, no need to compile it multiple times.

13 Rectangle.cpp #include “Rectangle.h” //Definitions of member functions //Copies the parameter to length data member void Rectangle::setLenght(float l) { length = l; } //Copies the parameter to width data member void Rectangle::setWidth(float w) { width = w; } Rectangle.cpp

14 Rectangle.cpp (continued) //return value stored in width data member float Rectangle::getWidth() { return width; } //return value stored in length data member float Rectangle::getLength() { return length; } //return calculated area of the rectangle float Rectangle::getArea() { return length * width; } Rectangle.cpp

15 Using the Class in Driver //Demonstrates use of Rectangle class #include “Rectangle.h” #include using namespace std; int main() { Rectangle box; float temp; cout << “This program will calculate “ << “the area of a rectangle.” << endl; cout << “What is the width? “; cin >> temp; box.setWidth(temp); Driver.cpp Use “” when including a user-defined class

16 Using the Class in Driver cout << “What is the length? “; cin >> temp box.setLength(temp); //Display all of box’s data cout<<“Length: “<<box.getLength()<<endl; cout<<“Width: “<<box.getWidth()<<endl; cout<<“Area: “<<box.getArea()<< endl; return 0; } Driver.cpp

17 Private Data Members – Why?? In OOP, an object should protect its private data members so they do not get inadvertently corrupted A public interface to that data is provided so it does not get corrupted

18 A More Robust Rectangle Problems with the rectangle class? Should width or length ever be negative? Have the functions which modify a data member return a bool indicating success or not

19 Rectangle.h //Declaration of class Rectangle #ifndef RECTANGLE_H #define RECTANGLE_H class Rectangle { public: bool setWidth(float); bool setLength(float); float getWidth(); float getLength(); float getArea(); private: float width; float length }; #endif Rectangle2.h

20 More Robust Rectangle Implementation #include “Rectangle.h” //Definitions of member functions //Copies the parameter to length data member bool Rectangle::setLength(float l) { if (l >= 0.0) { length = l; return true; } else { length = 0.0; return false; } Rectanglew2.cpp

21 More Robust Rectangle Implementation (continued) //Copies the parameter to width data member void Rectangle::setWidth(float w) { if (w >= 0.0) {width = w; return true; } else {width = 0.0; return false; } } //return value stored in width data member float Rectangle::getWidth() { return width; } Rectanglew2.cpp

22 Rectangle.cpp (continued) //return value stored in length data member float Rectangle::getLength() { return length; } //return calculated area of the rectangle float Rectangle::getArea() { return length * width; } Rectangle2.cpp

23 Using the Class in Driver //Demonstrates use of Rectangle class #include “Rectangle.h” #include using namespace std; int main() { Rectangle box; float temp; cout << “This program will calculate “ << “the area of a rectangle.” << endl; cout << “What is the width? “; cin >> temp; Driver2.cpp

24 Using the Class in Driver if(!box.setWidth(temp)) { cout << “Invalid Width – width set “ << “to 0.0!” << endl; } cout << “What is the length? “; cin >> temp; if(!box.setLength(temp)) { cout << “Invalid Length – length set ” << “ to 0.0!” << endl; } Driver2.cpp

25 Using the Class in Driver //Display all of box’s data cout<<“Length: “<<box.getLength()<<endl; cout<<“Width: “<<box.getWidth()<<endl; cout<<“Area: “<<box.getArea()<< endl; return 0; } Driver2.cpp

26 I/O in Classes Notice – No cin/cout in Rectangle Allows flexibility to use the object –not locked into any particular error messages, prompts, etc. Classes should only have I/O if specifically designed for such. –Best left to the person designing the application

27 Review of Different Files Rectangle.hClass Interface Rectangle.cppMember Function Definitions Driver.cppMain driver

28 More on Classes Class can have –private member functions –public data members If member function is private, can only be called by other member functions of the class or friends Member functions may be defined inside class declaration – called inlining

29 Rectangle.h //Declaration of class Rectangle #ifndef RECTANGLE_H #define RECTANGLE_H class Rectangle { public: bool setWidth(float); bool setLength(float); float getWidth() {return width;} float getLength() {return length;} float getArea() {return length * width;} private: float width; float length }; #endif Rectangle3.h Inlined member function definitions will not also appear in Rectangle.cpp

30 Special Member Functions The Constructor & The Destructor

31 Constructor A constructor –is automatically called upon object instantiation –has the same name as the name of the class –Must be declared as a public member function –NO RETURN TYPE!!!

32 Constructor Demo Class #include using namespace std; class Demo { public: Demo(); }; //Constructor defined in the.h file //Usually defined in.cpp file. Demo::Demo() { cout << “Welcome to the Constructor!” << endl; } Demo.h

33 Constructor Demo Class #include “Demo.h” #include using namespace std; int main() { cout << “Before Object Creation” << endl; Demo demoObj; cout << “After Object Creation” << endl; return 0; } demoDriver.cpp Before Object Creation Welcome to the Constructor! After Object Creation Output:

34 More on Constructors Default Constructor –constructor which accepts no arguments Constructors may –accept argument –have default arguments –be declared inline –be overloaded

35 Inventory Item Class InventoryItem.h class InventoryItem { private: char* descrip; int units; public: InventoryItem(){descrip = new char[51];} void setDescription(char* x) { strcpy(descrip, x); } void setUnits(int u) {units = u;} char* getDescription() {return descrip;} int getUnits() {return units;} };

36 Inventory Item Class InventoryItemDriver.cpp 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; } Output: Item Description: Wrench Units on Hand: 20

37 Destructor A Destructor –is a member function –is automatically called when an object is destroyed –has the same name as the class preceded with a tilde (~) –performs shutdown procedures –never accept parameters –cannot be overloaded

38 Destructor Demo Class #include using namespace std; class Demo { public: Demo(); ~Demo(); }; Demo::Demo() { cout << “Welcome to the Constructor!” << endl; } Demo::~Demo() { cout << “Goodbye from the Destructor!” << endl; } Demo2.h

39 Destructor Demo Class #include “Demo2.h” #include using namespace std; int main() { cout << “Before Object Creation.” << endl; Demo demoObj; cout << “After Object Creation” << endl; return 0; } demoDriver.cpp Before Object Creation Welcome to the Constructor! After Object Creation Goodbye From the Destructor! Output:

40 Inventory Item Class InventoryItem2.h class InventoryItem { private: char* descrip; int units; public: InventoryItem(){descrip = new char[51];} ~InventoryItem(){delete descrip;} void setDescription(char* x) { strcpy(descrip, x); } void setUnits(int u) {units = u;} char* getDescription() {return descrip;} int getUnits() {return units;} };

41 Inventory Item Class InventoryItemDriver.cpp 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; } Item Description: Wrench Units on Hand: 20 Output:

42 Argument Accepting Constructor #ifndef SALE_H #deifne SALE_H class Sale { private: float taxRate; float total; public: Sale(float rate) { taxRate = rate; } void calcSale(float cost) { total = cost + cost * taxRate; } float getTotal() {return total;} }; #endif Sale.h

43 Argument Accepting Constructor #include using namespace std; #include “Sale.h” int main() { Sale cashier(0.06); //6% tax rate float amt; cout.setprecision(2); cout.setf(ios::fixed|ios::showpoint); cout << “Enter Sale amount: “; cin >> amt; cashier.calcSale(amt); cout << “Total is: $” << cashier.getTotal() << endl; return 0; } SaleDriver.cpp

44 Argument Accepting Constructor #ifndef SALE_H #deifne SALE_H 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() {return total;} }; #endif Sale2.h Default Argument

45 Argument Accepting Constructor #include using namespace std; #include “Sale2.h” int main() { Sale cashier(0.06); //6% tax rate Sale cashier2; //5% tax rate float amt; cout.setprecision(2); cout.setf(ios::fixed|ios::showpoint); cout << “Enter Sale amount: “; cin >> amt; cashier.calcSale(amt); cashier2.calcSale(amt); SaleDriver2.cpp

46 Argument Accepting Constructor cout << “Total at 5% is: $” << cashier.getTotal() << endl; cout << “Total at 6% is: $” << cashier2.getTotal() << endl; return 0; } SaleDriver2.cpp Enter Sale amount: Total at 5% is: Total at 6% is: output:

47 Fini ?