Classes. COMP104 Class / Slide 2 Motivation  Types such as int, double, and char are “stupid” objects. * They can only answer one question: “What value.

Slides:



Advertisements
Similar presentations
Contents o Introduction o Characteristics of Constructor. o Types of constructor. - Default Constructor - Parameterized Constructor - Copy Constructor.
Advertisements

Object-Oriented Programming and Classes. OOP / Slide 2 Basic, built-in, pre-defined types : char, int, double, … Variables + operations on them int a,
Parameter Passing Mechanisms Reference Parameters.
Constructors 11/10/10. Today  Use constructors to initialize objects.  Use const to protect data members.
Introduction to Functions Programming. COMP102 Prog Fundamentals I: Introduction to Functions /Slide 2 Introduction to Functions l A complex problem is.
True or false A variable of type char can hold the value 301. ( F )
Classes. COMP104 Lecture 25 / Slide 2 Motivation  Types such as int, double, and char are simple objects. * They can only answer one question: “What.
Computer Science 1620 Variables and Memory. Review Examples: write a program that calculates and displays the average of the numbers 45, 69, and 106.
This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson.
Classes and OOP. Basic, built-in, pre-defined types : char, int, double, … Variables + operations on them int a, b,c; c=a+b; c=a mod b; … More complicated,
1 9/1/06CS150 Introduction to Computer Science 1 What Data Do We Have? CS 150 Introduction to Computer Science I.
Abstract Data Type. COMP104 Slide 2 Summary l A class can be used not only to combine data but also to combine data and functions into a single (compound)
Functions:Passing Parameters by Value Programming.
Computer Programming 1 Functions. Computer Programming 2 Objectives Take a first look at building functions Study how a function is called Investigate.
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.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Functions. COMP104 Lecture 13 / Slide 2 Function Prototype * The function prototype declares the interface, or input and output parameters of the function,
1 Overloading functions C++ allows us to define functions that have the same name but different sets of parameters This capability can be used to define.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Chapter 6: Functions.
Software Engineering 1 (Chap. 1) Object-Centered Design.
The switch Statement Selection Revisited. Problem Using OCD, design and implement a program that allows the user to perform an arbitrary temperature conversion.
PRINCIPLES OF PROGRAMMING Revision. A Computer  A useful tool for solving a great variety of problems.  To make a computer do anything (i.e. solve.
Functions Parameters & Variable Scope Chapter 6. 2 Overview  Using Function Arguments and Parameters  Differences between Value Parameters and Reference.
1 Building Classes (the "++" in C++) (Chapter 14) Representing More Complex Objects.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
C++ Exceptions STL Vector. Example int Quotient (int numer, int denom} { if (denom != 0) return (numer/denom); else //What to do?? }
Chapter 8 Friends and Overloaded Operators. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Friend Function (8.1) Overloading.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 25P. 1Winter Quarter C++: I/O and Classes Lecture 25.
Value and Reference Parameters. CSCE 1062 Outline  Summary of value parameters  Summary of reference parameters  Argument/Parameter list correspondence.
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+
Fundamental Programming: Fundamental Programming Introduction to C++
1 Advanced Issues on Classes Part 3 Reference variables (Tapestry pp.581, Horton 176 – 178) Const-reference variables (Horton 176 – 178) object sharing:
C++ Functions. Objectives 1. Be able to implement C++ functions 2. Be able to share data among functions 2.
Functions Modules in C++ are called functions and classes Functions are block of code separated from main() which do a certain task every C++ program must.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
Basics of Most C++ Programs // Programmer: Clayton Price date: 9/4/ // File: fahr2celc.cpp 03. // Purpose:
Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed.
Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private: //...
Copyright © 2002 W. A. Tucker1 Chapter 10 Lecture Notes Bill Tucker Austin Community College COSC 1315.
Additional Pair Programming Exercises 1. Problem 1 For a wheel of radius r feet, how many revolutions are required for that wheel to travel 1 mile? What.
Lecture 4 Function example. Example1 int max (int a, int b) { int c; if (a > b) c = a; else c = b; return (c); } void main ( ) {int x, y; cin>>x>>y; cout.
Chapter 11 Friends and Overloaded Operators. Introduction to function equal // Date.h #ifndef _DATE_H_ #define _DATE_H_ class CDate { public: CDate();
1 CSE 2341 Object Oriented Programming with C++ Note Set #5.
Computing and Statistical Data Analysis Lecture 6 Glen Cowan RHUL Physics Computing and Statistical Data Analysis Introduction to classes and objects:
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
L what are executable/non-executable statements l out of the ones below which constructs are executable #include p=3.14; const double PI=3.14; int myfunc(int);
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
Fundamental Programming Fundamental Programming More Expressions and Data Types.
Programming Abstract Data Types. COMP104 Lecture 30 / Slide 2 Review: class l Name one reason why we need the class construct. l Why do we need "inspector.
Constructors, Copy Constructors, constructor overloading, function overloading Lecture 04.
Literals A literal (sometimes called a constant) is a symbol which evaluates to itself, i.e., it is what it appears to be. Examples: 5 int literal
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.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Class Operations Creating New Types. Review Last time, we began building, a class to allow us to model temperatures: Last time, we began building Temperature,
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.
1 More About Classes – Instance Methods Chap.6 Study Sections 6.1 – 6.4 Representing More Complex Objects.
Visit for more Learning Resources
Chapter 5 Functions for All Subtasks 1
Chapter 1.2 Introduction to C++ Programming
10.2 Classes Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 1.
CMPE Data Structures and Algorithms in C++ February 22 Class Meeting
Multiple Files Revisited
Classes and OOP.
Life is Full of Alternatives
Multiple Files Revisited
Presentation transcript:

Classes

COMP104 Class / Slide 2 Motivation  Types such as int, double, and char are “stupid” objects. * They can only answer one question: “What value do you contain?” 3!!!

COMP104 Class / Slide 3 Motivation * Classes allow you to build “smart” objects that can answer many questions (and perform various actions). n “What is your temperature?” n “What is your temperature in Fahrenheit?” n “What is your humidity?” n “Print your temperature in Kelvin.” What is your wish?

COMP104 Class / Slide 4 Temperature Example * Write a program that, given a temperature in Fahrenheit, Celsius, or Kelvin, will display the equivalent temperature in each of the scales. double degree = 0.0; // needs 2 items! char scale = 'F';  To apply a function f() to a temperature, we must specify both degree and scale: f(degree, scale); * Also to display a temperature: cout << degree << scale;

COMP104 Class / Slide 5 Temperature Example * Is there a way to build a user-defined data type that combines degree and scale into one object? * Can this object automatically convert between different scales, and know how to print itself out? (Can we construct a “smart” object?) * Answer: Yes, by using the class construct.

COMP104 Class / Slide 6 * Design and build a class to represent the temperature object * Identify: 1) data required (data members), and 2) operations that this object can perform (member functions) class Temperature{ public: // member functions private: double degree; // data members char scale; }; Object-Oriented Solution

COMP104 Class / Slide 7 #include using namespace std; // definition of Temperature class goes here void main(){ char resp; Temperature temp; do{ cout << "Enter temperature (e.g., 98.6 F): "; temp.read(); cout "; temp.Fahrenheit(); temp.print();cout << " = "; temp.Celsius(); temp.print();cout << " = "; temp.Kelvin(); temp.print();cout << endl << endl; cout << "Another temperature to convert? "; cin >> resp; }while(resp == 'y' || resp == 'Y'); } Temperature Conversion Program

COMP104 Class / Slide 8 Enter temperature (e.g., 98.6 F): 212 F -->212 F = 100 C = K Another temperature to convert? y Enter temperature (e.g., 98.6 F): 0 C -->32 F = 0 C = K Another temperature to convert? y Enter temperature (e.g., 98.6 F): 100K --> F = C = 100 K Another temperature to convert? n Temperature Conversion Output

COMP104 Class / Slide 9 Smart Temperature Object * A smart object should carry within itself the ability to perform its operations  Operations of Temperature object : n initialize degree and scale with default values n read a temperature from the user and store it n compute the corresponding Fahrenheit temperature n compute the corresponding Celsius temperature n compute the corresponding Kelvin temperature n display the degrees and scale to the user

COMP104 Class / Slide 10 Temperature Class class Temperature{ public: Temperature(); Temperature(double idegree, char iscale); double getDegree() const; char getScale() const; void set(double newDegree, char newScale); void read(); void print() const; void Fahrenheit(); void Celsius(); void Kelvin(); private: double degree; char scale; };

COMP104 Class / Slide 11 Printing Temperature * Given the following declaration: Temperature temp1, temp2; temp1:temp2:degreescale

COMP104 Class / Slide 12 Printing Temperature * A programmer can write: temp1.print(); temp2.print(); * Smart object interpretation: temp1: Receives print() message and displays values stored in degree and scale temp2: Receives print() message and displays values stored in degree and scale

COMP104 Class / Slide 13 Printing Temperature void Temperature::print() const{ cout << degree << " " << scale; } * Remarks: n Member functions of a class can access the private data members of their class, but normal functions cannot. The modifier const in the print() member function indicates that the function is a constant member function (it does not change any of the data members).

COMP104 Class / Slide 14 Default-Value Constructor * A constructor is a special member function whose name is always the same as the name of the class. * A constructor function initializes the data members when a Temperature object is declared. Temperature temp3; Temperature::Temperature(){ degree = 0.0; scale = 'C'; }

COMP104 Class / Slide 15 Default-Value Constructor * Remarks: n Constructor functions have no return type (not even void!). Because a constructor function initializes the data members, there is no const following its heading. n The constructor function is automatically called whenever a Temperature class object is declared.

COMP104 Class / Slide 16 Explicit-Value Constructor * An explicit-value constructor initializes the data members when a Temperature object is declared with parameters: Temperature temp3(98.6, 'F'); Temperature::Temperature(double d, char s) { degree = d; scale = toupper(s); if(scale!='C' && scale!='F' && scale!='K'){ cout << "Bad Temperature scale: " << scale << endl; exit(1); }

COMP104 Class / Slide 17 Inspector Functions * An inspector function allows programmers to read (but not modify) data members of the class. int d = temp1.getDegree(); char s = temp1.getScale(); double Temperature::getDegree( ) const { return degree; } char Temperature::getScale( ) const { return scale; }

COMP104 Class / Slide 18 Mutator Functions * A mutator function modifies data members of the class. temp1.set(32, 'F'); void Temperature::set(double d, char s){ degree = d; scale = toupper(s); if(scale!='C' && scale!='F' && scale!='K'){ cout << "Bad Temperature scale: " << scale << endl; exit(1); }

COMP104 Class / Slide 19 Reading Temperature  Using the read() member function: Temperature temp1; cout << "Enter temperature (e.g., 98.6 F): "; temp1.read(); // process the temperature in temp1  When temp1 receives the read() message, it gets values from cin into degree and scale. void Temperature::read(){ cin >> degree >> scale; scale = toupper(scale); if(scale!='C' && scale!='F' && scale!='K'){ cout << "Bad Temperature scale: " << scale << endl; exit(1); }

COMP104 Class / Slide 20 Conversion Functions  The member function Fahrenheit() changes the degree and scale of the member data to Fahrenheit. void Temperature::Fahrenheit(){ if(scale == 'C') degree = degree* ; else if(scale == 'K') degree = (degree )* ; scale = 'F'; }

COMP104 Class / Slide 21 Conversion Functions  The member functions Celsius() and Kelvin() are similar. void Temperature::Celsius(){ if(scale == 'F') degree = (degree-32.0)/1.8; else if(scale == 'K') degree = degree ; scale = 'C'; } void Temperature::Kelvin(){ if(scale == 'F') degree = (degree-32.0)/ ; else if(scale == 'C') degree = degree ; scale = 'K'; }

COMP104 Class / Slide 22 Conversion Functions  Using the Fahrenheit() member function: Temperature temp1;// default value: 0 C temp1.Fahrenheit(); temp1.print();// prints: 32 F  When temp1 receives the Fahrenheit() message, it converts to the Fahrenheit temperature 32 F.

COMP104 Class / Slide 23 Calling Member Functions from Member Functions  We can simplify the main() program by building a member function printAll() to print the temperature in all scales: void main(){ char resp; Temperature temp; do{ cout << "Enter temperature (e.g., 98.6 F): "; temp.read(); temp.printAll(); // prints temperature in F, C, K cout << endl << endl; cout << "Another temperature to convert? "; cin >> resp; }while(resp == 'y' || resp == 'Y'); }

COMP104 Class / Slide 24 Calling Member Functions from Member Functions * This member function calls the other member functions: void Temperature::printAll(){ // prints temperature in all scales double d = degree; // save initial degree and scale char s = scale; cout "; // calls member function Fahrenheit() on the same Temperature object Fahrenheit(); // calls member function Fahrenheit() on the same Temperature object print(); cout << " = "; Celsius(); print(); cout << " = "; Kelvin(); print(); degree = d;// restore initial degree and scale scale = s; }

COMP104 Class / Slide 25 Temperature Class class Temperature{ public: Temperature(); Temperature(double idegree, char iscale); double getDegree() const; char getScale() const; void set(double newDegree, char newScale); void read(); void print() const; void printAll(); void Fahrenheit(); void Celsius(); void Kelvin(); private: double degree; char scale; };

COMP104 Class / Slide 26 Some Additional Operations * Additional temperature object operations that a user might need: n display the degree value only n display the scale value only n compute the temperature plus n degrees n compute the temperature minus n degrees n compare to another another Temperature object using any of the six relational operators (==, !=,, >=)

COMP104 Class / Slide 27 Pager Idea * Member functions are similar to the way a pager works: n You can have someone call you. You call their number (e.g., ) and tell the operator your number (e.g., ): call( ); n You can can call a different person at a different pager number call( ); n You can also leave a more detailed message: message("Meet me in LG7"); message("Need help on comp104 Lab!!!");