CMSC 202 Lesson 9 Classes III. Warmup Using the following part of a class, implement the Sharpen() method, it removes 1 from the length: class Pencil.

Slides:



Advertisements
Similar presentations
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Advertisements

Lecture 3 Feb 4 summary of last week’s topics and review questions (handout) Today’s goals: Chapter 1 overview (sections 1.4 to 1.6) c++ classes constructors,
Computer Science 1620 Arrays. Problem: Given a list of 5 student grades, adjust the grades so that the average is 70%. Program design: 1. read in the.
CS 1031 C++: Object-Oriented Programming Classes and Objects Template classes Operator Overloading Inheritance Polymorphism.
Functions Parameters & Variable Scope Chapter 6. 2 Overview  Using Function Arguments and Parameters  Differences between Value Parameters and Reference.
1 Chapter 9 Scope, Lifetime, and More on Functions.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Structures  2 nd aggregate data type: struct  Recall:
Chapter 8 Friends and Overloaded Operators. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Friend Function (8.1) Overloading.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
1 Fall 2002 ACS 168 Problem Solving Using the Computer Weeks 9 and 10 Structures and Classes Class Diagrams Weeks 9 and 10 Structures and Classes Class.
Operator Overloading Mark Hennessy Dept. Computer Science NUI Maynooth C++ Workshop 18 th – 22 nd September 2006.
1 Overloading Overloading allows a function or operator to have a different meaning depending on the type of objects it is used on. Examples: operator+
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 3 More About Classes Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
CMSC 202 Lesson 14 Copy and Assignment. Warmup Write the constructor for the following class: class CellPhone { public: CellPhone(int number, const string&
CMSC 202 Lesson 7 Classes I. Warmup  Add the correct parameter list and return type to the following function: (hint: all the information you need is.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
Object Orientation A Crash Course Intro. What is an Object? An object, in the context of object- oriented programming, is the association of a state with.
CMSC 202 Lesson 10 Classes IV. Warmup Class Oven { public Oven( int initTemp = 0 ); void SetTemp( int newTemp ); int GetTemp() const; private int m_temp.
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
Functions Overview Functions are sequence of statements with its own local variables supports modularity, reduces code duplication Data transfer between.
Chapter 11 Friends and Overloaded Operators. Introduction to function equal // Date.h #ifndef _DATE_H_ #define _DATE_H_ class CDate { public: CDate();
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.
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?
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
CS Class 19 Today  Practice with classes Announcements  Turn in algorithm for Project 5 in class today  Project 5 due 11/11 by midnight – .
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Friend Functions.  An ordinary function that is given special access to the private members of a class  NOT a member function of the class  Prototype.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Today: –Review declaration, implementation, simple class structure. –Add an exception class and show.
Slide 1 Chapter 6 Structures and Classes. Slide 2 Learning Objectives  Structures  Structure types  Structures as function arguments  Initializing.
Lecture 2 Functions. Functions in C++ long factorial(int n) The return type is long. That means the function will return a long integer to the calling.
CMSC 202 Lesson 6 Functions II. Warmup Correctly implement a swap function such that the following code will work: int a = 7; int b = 8; Swap(a, b); cout.
Classes - Part II (revisited) n Constant objects and member functions n Definition Form of Member Functions n friend functions and friend classes n Constructors.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
Manipulator example #include int main (void) { double x = ; streamsize prec = cout.precision(); cout
The const Keyword Extreme Encapsulation. Humble Beginnings There are often cases in coding where it is helpful to use a const variable in a method or.
Reference Parameters There are two ways to pass arguments to functions: pass- by-value and pass-by-reference. pass-by-value –A copy of the arguments’svalue.
Defining Classes I Part B. Information hiding & encapsulation separate how to use the class from the implementation details separate how to use the class.
1 Introduction to Object Oriented Programming Chapter 10.
1 COMS 261 Computer Science I Title: Classes Date: November 4, 2005 Lecture Number: 27.
Classes.  A collection of variables combined with a set of related functions MemberFunctions (methods) (methods) MemberVariables (data members) (data.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-1 Learning Objectives  Classes  Constructors  Principles of OOP  Class type member.
CPSC 252 ADTs and C++ Classes Page 1 Abstract data types (ADTs) An abstract data type is a user-defined data type that has: private data hidden inside.
100 學年度碩士班新生暑期課程 程式設計 Object-Oriented Programming: Part I The Basics of Classes.
Classes CMSC 202. Version 9/12 2 Programming & Abstraction All programming languages provide some form of abstraction. –Also called information hiding.
1 Object-Oriented Programming Using C++ CLASS 2 Honors.
Functions CMSC 202. Topics Covered Function review More on variable scope Call-by-reference parameters Call-by-value parameters Function overloading Default.
CMSC 202 Lesson 8 Classes II. Warmup Declare a class (.h part) named “Cup” It has a data member that says how full it is One method called “Drink” that.
Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 1 Pass-by-Value - default passing mechanism except.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2002 Pearson Education, Inc. Slide 1.
1 C++ Classes and Data Structures Course link…..
COMP 53 – Week Two Operator Overloading.
Chapter 1.2 Introduction to C++ Programming
A First C++ Class – a Circle
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?
Lesson 14 Copy and Assignment
group work #hifiTeam
More on Classes Classes may have constructors which are called when objects are created and destructors which are called when objects are destroyed. Classes.
Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.
CMSC 202 Lesson 22 Templates I.
Learning Objectives Classes Constructors Principles of OOP
Friends, Overloaded Operators, and Arrays in Classes
Classes.
CMSC202 Computer Science II for Majors Lecture 07 – Classes and Objects (Continued) Dr. Katherine Gibson Based on slides by Chris Marron at UMBC.
Templates I CMSC 202.
CMSC 202 Lesson 6 Functions II.
CMSC 202 Lesson 8 Classes II.
Class rational part2.
Presentation transcript:

CMSC 202 Lesson 9 Classes III

Warmup Using the following part of a class, implement the Sharpen() method, it removes 1 from the length: class Pencil { public: bool Sharpen(); private: int m_length; };

Class Review class DayOfYear { public: void Input( ); void Output( ); void Set( int newMonth, int newDay ); void Set( int newMonth ); int GetMonthNumber( ); int GetDay( ); private: int m_month; int m_day; }; // Declaring a DayOfYear object DayOfYear today; Mutators Accessors Facilitators What’s going on here?

Constructors Special Methods that “build” (construct) an object  Supply default values  Initialize an object Syntax: ClassName(); ClassName::ClassName(){ /* code */ } Notice  No return type  Same name as class!

Constructor Example class DayOfYear { public: DayOfYear( int initMonth, int initDay ); void Input( ); void Output( ); void Set( int newMonth, int newDay ); void Set( int newMonth ); int GetMonthNumber( ); int GetDay( ); private: int m_month; int m_day; };

Constructor Example Implementation DayOfYear::DayOfYear( int initMonth, int initDay ) { m_month = initMonth; m_day = initDay; } // Improved version DayOfYear::DayOfYear( int initMonth, int initDay ) { Set(initMonth, initDay); } How can this method be improved? Why use a mutator?

Constructor Example Implementation Initialization Lists  Alternative to assignment statements (sometimes necessary!)  Comma-separated list following colon in method definition Syntax: DayOfYear::DayOfYear( int initMonth, int initDay ) : m_month( initMonth ), m_day( initDay ) { }

Overloading Constructors Yes – different parameter lists Example class DayOfYear { public: DayOfYear( int initMonth, int initDay ); DayOfYear( int initMonth ); DayOfYear( ); // other public methods… private: int m_month; int m_day; };

Overloading Constructors DayOfYear::DayOfYear( int initMonth, int initDay ) { Set(initMonth, initDay); } DayOfYear::DayOfYear( int initMonth ) { Set(initMonth, 1); } DayOfYear::DayOfYear( ) { Set(1, 1); } What would be another alternative to having all 3 of these methods?

Overloading Constructors class DayOfYear { public: DayOfYear( int initMonth = 1, int initDay = 1 ); // other public methods… private: int m_month; int m_day; }; DayOfYear::DayOfYear( int initMonth, int initDay ) { Set(initMonth, initDay); } Default Parameters!

Constructors Why haven’t we seen this before?  Compiler builds a default constructor Unless you define a constructor… Think about the following:  vector days( 20 ); Calls default constructor for DayOfYear! What if something goes wrong?  One solution: Zombie objects  Another solution: Throw exception (later…)

Zombie Objects class DayOfYear { public: DayOfYear( int initMonth = 1, int initDay = 1 ); bool isValid(); // other public methods… private: int m_month; int m_day; bool m_isValid; }; bool DayOfYear::isValid() { return m_isValid; } DayOfYear::DayOfYear( int initMonth, int initDay ) :m_month( initMonth), m_day( initDay ) { if (m_month 12) m_isValid = false; else if ( m_day 31) m_isValid = false; else if ( day too big for the specified month) m_isValid = false else m_isValid = true; }

Practice Stapler class  What would the constructor look like? Initialize a stapler to have 50 staples

Const and Objects With an Object const DayOfYear jan1st(1, 1); jan1st.Set(1, 5);// ERROR myfile.cpp: In function `int main()': myfile.cpp:20: passing `const DayOfYear' as `this' argument of `void DayOfYear::Set(int, int)' discards qualifiers

Const and Methods Const member functions  Promise not to modify the current object Usually accessors, print functions, … Compiler checks  Directly – is there an assignment to data member in method?  Indirectly – is there a call to a non-const method? Syntax retType methodName(parameters) const;

Const Example class DayOfYear { public: DayOfYear( int initMonth = 1, int initDay = 1 ); void Input( ); void Output( ) const; void Set( int newMonth, int newDay ); void Set( int newMonth ); int GetMonthNumber( ) const; int GetDay( ) const; private: int m_month; int m_day; }; Promise not to alter data members!

Const Rules Const member functions  Can be called on const and non-const objects  Can call other const member functions  Cannot call non-const member functions Non-const member functions  Can be called only on non-const objects Otherwise, compiler error!  Can call const and non-const member functions Const objects  Can be passed as const argument Non-const objects  Can be passed as const or non-const argument

Practice? What is wrong with this? int DayOfYear::GetDay ( ) const { if (m_day < 1 ) Set( m_month, 1 ); return m_day; }

Practice What is wrong with this? void Bob ( const DayOfYear& doy) { OutputDayOfYear ( doy ); cout << "Please enter your birth month and day \n"; int birthMonth, birthDay; cin >> birthMonth >> birthDay; doy.Set( birthMonth, birthDay ); }

Implementing with Const Start from the beginning  Don’t try to add const at the end of implementing Use for  Member functions that don’t change object Facilitators (maybe) and Accessors (most definitely)  Parameters whenever reasonable Not with pass-by-value Yes with pass-by-reference

Designing Classes Ask yourself the following questions:  What are the responsibilities of this type of object?  What actions can an object take?  What actions can another function take on an object?  What information does an object store?  What information does an object need access to? For each method:  What parameters (const, ref, const-ref, val)? Preconditions – what values are legal for parameters?  What return value (const, ref, const-ref, val)? Postconditions – what was altered by method?  Does this method change the object (const, non-const)?

Practice – Add const! #include using namespace std; class Person { public: Person( string name, int age ); string GetName( ); int GetAge( ); void HappyBirthday( ); private: string m_name; int m_age; }; #include #include "Person.h“ using namespace std; Person::Person( string name, int age ) { m_name = name; m_age = age; } string Person::GetName( ) { return m_name; } int Person::GetAge( ) { return m_age; } void Person::HappyBirthday( ) { cout << "Happy Birthday " << m_name << endl; ++m_age; }

Challenge Revisiting our Staple class  Add a constructor Initialize number of staples to the value of a parameter  Retain the “Staple” method Removes 1 staple  Retain the “Fill” method Completely fills to 100  Add a “AddStaples” method Adds some number of staples (parameter)  Add a “GetNbrOfStaples” method Returns the current number of Staples  Add consts whenever appropriate Parameters and methods!