! A class in C++ is similar to a structure. ! 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.

l A class in C++ is similar to a structure. l 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

! 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

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

! 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)

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++

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:

Classes: A Deeper Look. Systems Programming

Chapter 16: Classes and Data Abstraction

! 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

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II

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

Constructor - example

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools

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

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

IS 0020 Program Design and Software Tools

Chapter 17 - C++ Classes: Part II

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

C++ Classes, Constructor & Object Oriented Programming

Introduction to Classes

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

Abstraction in Software Development

Classes: A Deeper Look

CS304 Object Oriented Programming Final Term

Introduction & Review

OBJECT ORIENTED PROGRAMMING USING C++

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

Chapter 15: Object Oriented Programming

Lecture 5. Function Pointers

Operator Overloading

Computer Programming Class Members 9 th Lecture

Introduction to Programming session 24

Practice Problems CS2620 Advanced Programming, Spring 2003

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

Object Oriented Design

CS201 Latest Solved MCQs

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

Lecture 18 Tao Wang 1

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

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

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

Chapter 10 Introduction to Classes

IS0020 Program Design and Software Tools Midterm, Fall, 2004

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. 1

Classes: A Deeper Look, Part 2

Midterm Review. PIC 10B Spring 2018

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

Constants, References

CS201- Introduction to Programming Current Quizzes

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

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

C++ 8. Constructors and Destructors

CS 11 C++ track: lecture 1

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?

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7.

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

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

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7. CS 5301 Spring 2018

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

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

III. Classes (Chap. 3)

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

Short Notes of CS201

Review Questions for Final Exam

BITG 1113: Function (Part 2) LECTURE 5

Implementing an ADT with a Class

CS250 Final Review Questions

CS250 Final Review Questions

Lecture-5. Miscellaneous topics Templates. W3101: Programming Languages C++ Ramana Isukapalli

Quiz Start Time: 09:34 PM Time Left 82 sec(s)


CS201 - Introduction to Programming Glossary By

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

C++_ MARKS 40 MIN

CS304 Object Oriented Programming

Composition I. composition is a way to combine or compose multiple classes together to create new class

Transcription:

Classes and Objects Week 5 Gaddis:.2-.12 14.3-14.4 CS 5301 Spring 2015 Jill Seaman The Class! A class in C++ is similar to a structure.! 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! 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;! These member functions don t change hour or minute. 4

Accessors and mutators! 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;! 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! Used to control access to members of the class! can be accessed by functions inside AND outside of the class! 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! Class declarations are usually stored in their own header files (Time.h) - called the specification file - filename is usually same as class name.! Member function definitions are stored in a separate file (Time.cpp) - called the class implementation file - it must #include the header file,! 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! Note no return type, same name as class: Constructor Use! 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 Composition! When one class contains another as a member: #include Time.h" class Calls Time calls[10]; // times of last 10 phone calls // 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 << ; 14 Calls.h Calls.cpp Composition Pointers to Objects! 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 15! We can define pointers to objects, just like pointers to structures Time t1(12,20); Time *timeptr; timeptr = &t1;! We can access public members of the object using the structure pointer operator (->) timeptr->setminute(21); cout << timeptr->display() << endl; 12:21 16

Dynamically Allocating Objects Copy Constructors! Objects can be dynamically allocated with new: Time *tptr; tptr = new Time(12,20);... delete tptr;! Arrays of objects can also be dynamically allocated: Time *tptr; tptr = new Time[100]; tptr[0].setminute(11);... delete [] tptr; You can pass arguments to a constructor using this syntax. It can use only the default constructor to initialize the elements in the new array. 17! 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! The default copy constructor, provided by the compiler, copies member-to-member.! Default copy constructor works fine in most cases 18! You can re-define it for your class as needed. IntCell declaration! 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 19 Problem with member-wise assignment! 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 20

Programmer-Defined Copy Constructor! Prototype and definition of copy constructor: IntCell(const IntCell &obj); IntCell::IntCell(const IntCell &obj) = new int; * = *(obj.) Add to class declaration Programmer-Defined Copy Constructor! 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; 5! Copy constructor takes a reference parameter to an object of the class - This is required. object1 5 object2 21 22 Sample Problem 1 Sample Problem 2 Car class: Write a class named Car that has the following member variables:! yearmodel An int that holds the car s year model.! make A string that holds the make of the car.! speed An int that holds the car s current speed. The class should have the following member functions.! Constructor. Accepts the car s year model and make as arguments. Assigns 0 to the speed variable.! Accessors. Functions to get the values stored in member variables.! accelerate. The accelerate function should add 5 to the speed member variable Number Array Class: Design a class that has an array of floating-point numbers. The constructor should accept an integer argument and dynamically allocate the array to hold that many numbers. The destructor should free the memory held by the array. In addition, there should be member functions to perform the following operations:! Store a number in a specified position of the array! Retrieve a number from a position of the array! Return the average of the values stored in the array 23 24 Demonstrate the class in a driver program.! Include a copy constructor!