l A class in C++ is similar to a structure. l A class contains members: - variables AND - public: accessible outside the class.

Similar documents
! A class in C++ is similar to a structure. ! A class contains members: - variables AND. - public: accessible outside the class.

! A class in C++ is similar to a structure. ! A class contains members: - variables AND. - public: accessible outside the class.

The Class. Classes and Objects. Example class: Time class declaration with functions defined inline. Using Time class in a driver.

l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains the following: - variables AND

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains the following: - variables AND

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

Overloading Operators

! Search: find a given target item in an array, ! Linear Search: Very simple search method: ! Operators such as =, +, <, and others can be

Procedural Programming

W8.1 Continuing Classes friend Functions and friend Classes Using the this Pointer Cascading Function Calls

1 // Fig. 6.13: time2.cpp 2 // Member-function definitions for class Time. 3 #include <iostream> Outline. 4 5 using std::cout; 6 7 #include <iomanip>

A Deeper Look at Classes

Computer Programming with C++ (21)

More About Classes. Gaddis Ch. 14, CS 2308 :: Fall 2015 Molly O'Neil

! Determine if a number is odd or even. ! Determine if a number/character is in a range. ! Assign a category based on ranges (wind speed)

Pointer Assignments. CISC181 Introduction to Computer Science. Dr. McCoy. Lecture 18 October 29, The new Operator

57:017, Computers in Engineering C++ Classes

Chapter 9 Classes : A Deeper Look, Part 1

Chapter 6: Classes and Data Abstraction

Preview 9/20/2017. Object Oriented Programing with C++ Object Oriented Programing with C++ Object Oriented Programing with C++

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

Classes: A Deeper Look. Systems Programming

Chapter 16: Classes and Data Abstraction

l Operators such as =, +, <, can be defined to l The function names are operator followed by the l Otherwise they are like normal member functions:

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II

! Operators such as =, +, <, can be defined to. ! The function names are operator followed by the. ! Otherwise they are like normal member functions:

C++ Review. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools

Chapter 17 - C++ Classes: Part II

C++ Classes, Constructor & Object Oriented Programming

2. It is possible for a structure variable to be a member of another structure variable.

Fig. 7.1 Fig. 7.2 Fig. 7.3 Fig. 7.4 Fig. 7.5 Fig. 7.6 Fig. 7.7 Fig. 7.8 Fig. 7.9 Fig. 7.10

Introduction to Classes

Operator Overloading and Templates. Linear Search. Linear Search in C++ second attempt. Linear Search in C++ first attempt

Abstraction in Software Development

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming

Classes: A Deeper Look

Preview 11/1/2017. Constant Objects and Member Functions. Constant Objects and Member Functions. Constant Objects and Member Functions

OBJECT ORIENTED PROGRAMMING USING C++

Chapter 13: Introduction to Classes Procedural and Object-Oriented Programming

Chapter 15: Object Oriented Programming

Constructor - example

Lecture 5. Function Pointers

Computer Programming Class Members 9 th Lecture

Introduction & Review

Introduction to Programming session 24

Classes - 2. Data Processing Course, I. Hrivnacova, IPN Orsay

Angela Chih-Wei Tang Visual Communications Lab Department of Communication Engineering National Central University JhongLi, Taiwan.

IS0020 Program Design and Software Tools Midterm, Fall, 2004

CS304 Object Oriented Programming Final Term

Recharge (int, int, int); //constructor declared void disply();

Constants, References

CS 11 C++ track: lecture 1

Come and join us at WebLyceum

Purpose of Review. Review some basic C++ Familiarize us with Weiss s style Introduce specific constructs useful for implementing data structures

(5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 12: Classes and Data Abstraction

QUIZ How do we implement run-time constants and. compile-time constants inside classes?

Operator Overloading

Classes: A Deeper Look, Part 2

9.1 Introduction. Integrated Time class case study Preprocessor wrapper Three types of handles on an object. Class functions

Classes: Member functions // classes example #include <iostream> using namespace std; Objects : Reminder. Member functions: Methods.

Object Oriented Design

(b) Draw a hash table having 10 buckets. Label the buckets 0 through 9.

Practice Problems CS2620 Advanced Programming, Spring 2003

Lecture 18 Tao Wang 1

Chapter 10 Introduction to Classes

Midterm Review. PIC 10B Spring 2018

BITG 1113: Function (Part 2) LECTURE 5

Implementing an ADT with a Class

G205 Fundamentals of Computer Engineering. CLASS 3, Wed. Sept Stefano Basagni Fall 2004 M-W, 1:30pm-3:10pm

CS201 Latest Solved MCQs

More C++ Classes. Systems Programming

Introduction Of Classes ( OOPS )

Review: C++ Basic Concepts. Dr. Yingwu Zhu

III. Classes (Chap. 3)

Scope. Scope is such an important thing that we ll review what we know about scope now:

C++ 8. Constructors and Destructors

Topics. Topics (Continued) 7.1 Abstract Data Types. Abstraction and Data Types. 7.2 Object-Oriented Programming

Classes and Objects in C++

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

! A data structure representing a list. ! A series of dynamically allocated nodes. ! A separate pointer (the head) points to the first

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES III

CSCS 261 Programming Concepts Exam 2 Fall EXAM 2 VERSION 1 Fall Points. Absolutely no electronic devices may be used during this exam.

Review Questions for Final Exam

Inheritance, and Polymorphism.

CS 247: Software Engineering Principles. ADT Design

THE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~) BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF THE CLASS IN WHICH THEY ARE DECLARED.

Classes and Data Abstraction

(b) Draw a hash table having 10 buckets. Label the buckets 0 through 9.

Class 15. Object-Oriented Development from Structs to Classes. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

Next week s homework. Classes: Member functions. Member functions: Methods. Objects : Reminder. Objects : Reminder 3/6/2017


CSCE 110 PROGRAMMING FUNDAMENTALS

Transcription:

Classes and Objects Week 5 Gaddis:.2-.12 14.3-14.4 CS 5301 Spring 2018 Jill Seaman The Class l A class in C++ is similar to a structure. l A class contains members: - variables AND - functions (often called methods) (these manipulate the member variables). Members can be: - inaccessible outside the class (this is the default) - accessible outside the class. 1 2 Example class: Time class declaration with functions defined inline class Time //new data type int hour; int minute; void sethour(int hr) hour = hr; void setminute(int min) minute = min; int gethour() const return hour; int getminute() const return minute; void display() const cout << hour << : << minute; ; int main() Time t1, t2; t1.sethour(6); t1.setminute(30); cout << t1.gethour() << endl; t2.sethour(9); t2.setminute(20); t2.display(); 6 9:20 3 Using const with member functions l const appearing after the parentheses in a member function declaration specifies that the function will not change any data inside the object. int gethour() const return hour; int getminute() const return minute; void display() const cout << hour << : << minute; l These member functions don t change hour or minute. 4

Accessors and mutators l Accessor functions - return a value from the object (without changing it) - a getter returns the value of a member variable int gethour() const return hour; int getminute() const return minute; l Mutator functions - Change the value(s) of member variable(s). - a setter changes (sets) the value of a member variable. void sethour(int hr) hour = hr; void setminute(int min) minute = min; 5 Access rules l Used to control access to members of the class l can be accessed by functions inside AND outside of the class l can be called by or accessed by only functions that are members of the class (inside) int main() Time t1; ; t1.sethour(6); t1.setminute(30); cout << t1.hour << endl; //Error, hour is private 6 Separation of Interface from Implementation l Class declarations are usually stored in their own header files (Time.h) - called the specification file - filename is usually same as class name. l Member function definitions are stored in a separate file (Time.cpp) - called the class implementation file - it must #include the header file, l Any program/file using the class must include Time class, separate files // models a 12 hour clock class Time int hour; int minute; void sethour(int); void setminute(int); int gethour() const; int getminute() const; void display() const; void Time::display() const the class s header file (#include Time.h ) 7 cout << hour << : << minute; 8 Time.h ; Time.cpp #include <iostream> void Time::setHour(int hr) hour = hr; void Time::setMinute(int min) minute = min; int Time::getHour() const return hour; int Time::getMinute() const return minute;

Time class, separate files Constructors Driver.cpp //Example using Time class #include<iostream> int main() Time t; t.sethour(12); t.setminute(58); t.display(); cout <<endl; t.setminute(59); t.display(); 9 A constructor is a member function with the same name as the class. It is called automatically when an object is created It performs initialization of the new object It has no return type It can be overloaded: more than one constructor function, each with different parameter lists. A constructor with no parameters is the default constructor. If your class defines no constructors, C++ will provide 10 a default constructor automatically. Constructor Declaration+Definition l Note no return type, same name as class: Constructor Use l Called from the object declaration // models a 12 hour clock class Time int hour; int minute; Time(); Time(int,int); void sethour(int); void setminute(int); int gethour() const; int getminute() const; #include <iostream> Time::Time() hour = 12; minute = 0; Time::Time(int hr, int min) hour = hr; minute = min;... Time.cpp //Example using Time class #include<iostream> int main() Time t; t.display(); cout <<endl; Time t1(10,30); t1.display(); ; void display() const; 11 12:0 10:30 12

Destructors Member function that is automatically called when an object is destroyed Destructor name is ~classname, e.g., ~Time Has no return type; takes no arguments Only one destructor per class, i.e., it cannot be overloaded, cannot take arguments If the class allocates dynamic memory, the destructor should release (delete) it. class Time Time(); // Constructor prototype ~Time(); // Destructor prototype Arrays of Objects with initializer lists Each initializer takes the form of a function call: int main() Time recentcalls[7] = Time(1), Time(2,), Time(3,24), Time(4), Time(4,50); If there are fewer initializers in the list than elements in the array, the default constructor will be called for all the remaining elements. This array is initialized to 7 Time objects, set to 1:00, 2:, 3:24, 4:00, 4:50, 12:00 and 12:00. 14 Composition Composition l When one class contains another as a member: #include Time.h" Calls.h class Calls Time calls[10]; // times of 10 phone calls // this array is initialized using default constructor void set(int,time); void displayall(); #include "Calls.h" #include <iostream> void Calls::set(int i, Time t) calls[i] = t; void Calls::displayAll () for (int i=0; i<10; i++) calls[i].display(); //calls member function cout << ; Calls.cpp 15 l Driver for Calls //Example using Calls and Time classes #include<iostream> #include Calls.h //this includes Time.h int main() Calls calltimes; Time t1(4,30); calltimes.set(0,t1); Time t2(11,42); calltimes.set(1,t2); calltimes.displayall(); 4:30 11:42 12:0 12:0 12:0 12:0 12:0 12:0 12:0 12:0 16

Copy Constructors l Special constructor used when a newly created object is initialized using another object of the same class. Time t1; Time t2 = t1; Time t3 (t1); Both of the last two use the copy constructor l The default copy constructor, provided by the compiler, copies member-to-member. l Default copy constructor works fine in most cases 17 l You can re-define it for your class as needed. IntCell declaration l Problem with the default copy constructor: what if the class contains a pointer member? class IntCell IntCell (int); int read () const; void write (int ); ; int *; IntCell::IntCell (int initialvalue) = new int; * = initialvalue; int IntCell::read () const return *; void IntCell::write (int x) * = x; Note: dynamic memory allocation 18 Problem with member-wise assignment l What we get from member-wise assignment in objects containing dynamic memory (ptrs): IntCell object1(5); IntCell object2 = object1; // calls copy constructor //object2.=object1. object2.write(); cout << object1.read() << endl; cout << object2.read() << endl; object1 object2 19 Programmer-Defined Copy Constructor l Prototype and definition of copy constructor: IntCell(const IntCell &obj); IntCell::IntCell(const IntCell &obj) = new int; * = *(obj.); l Copy constructor takes a reference parameter to an object of the class - This is required. Add to class declaration 20

Programmer-Defined Copy Constructor l Each object now points to separate dynamic memory: IntCell object1(5); IntCell object2 = object1; //now calls MY copy constr object2.write(); cout << object1.read() << endl; cout << object2.read() << endl; object1 5 object2 21 5 Pointers to Objects l We can define pointers to objects, just like pointers to structures Time t1(12,20); Time *timeptr; timeptr = &t1; l We can access public members of the object using the structure pointer operator (->) timeptr->setminute(21); cout << timeptr->display() << endl; 12:21 22 Dynamically Allocating Objects l Objects can be dynamically allocated with new: Time *tptr; tptr = new Time(12,20);... delete tptr; You can pass arguments to a constructor using this syntax. l Arrays of objects can also be dynamically allocated: Time *tptr; tptr = new Time[100]; tptr[0].setminute(11);... delete [] tptr; It can use only the default constructor to initialize the elements in the new array. 23