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

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

! 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

Procedural Programming

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

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

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

Chapter 9 Classes : A Deeper Look, Part 1

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

57:017, Computers in Engineering C++ Classes

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

Classes: A Deeper Look. Systems Programming

Chapter 16: Classes and Data Abstraction

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

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

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

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools

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

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

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

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

Introduction to Programming session 24

OBJECT ORIENTED PROGRAMMING USING C++

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

Chapter 15: Object Oriented Programming

Constructor - example

IS0020 Program Design and Software Tools Midterm, Fall, 2004

Lecture 5. Function Pointers

Computer Programming Class Members 9 th Lecture

Introduction & Review

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.

Chapter 10 Introduction to Classes

CS304 Object Oriented Programming Final Term

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

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

CS 11 C++ track: lecture 1

CS201 Latest Solved MCQs

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

Operator Overloading

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

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.

Lecture 18 Tao Wang 1

BITG 1113: Function (Part 2) LECTURE 5

Implementing an ADT with a Class

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

More C++ Classes. Systems Programming

Introduction Of Classes ( OOPS )

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

III. Classes (Chap. 3)

Practice Problems CS2620 Advanced Programming, Spring 2003

Come and join us at WebLyceum

Constants, References

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

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

C++ 8. Constructors and Destructors

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

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

Ch. 17: Linked Lists. Introduction to Linked Lists

Classes and Objects in C++

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES III

Midterm Review. PIC 10B Spring 2018

Inheritance, and Polymorphism.

Functions, Arrays & Structs

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.

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

! Pass by value: when an argument is passed to a. ! It is implemented using variable initialization. ! Changes to the parameter in the function body

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


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

CSCE 110 PROGRAMMING FUNDAMENTALS

Transcription:

Classes and Objects Week 5 Gaddis:.2-.12 14.3-14.4 CS 5301 Fall 2016 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 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 Copy Constructors! 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! 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 16! 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 17 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 18 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 19 20

Pointers to Objects Dynamically Allocating Objects! 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 21! 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. 22