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,

Slides:



Advertisements
Similar presentations
Copyright © 2002 Pearson Education, Inc. Slide 1.
Advertisements

Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Learning Objectives Structures Structure types Structures.
Object-Oriented Programming and Classes. OOP / Slide 2 Basic, built-in, pre-defined types : char, int, double, … Variables + operations on them int a,
What have we learned so far… Preprocessor directives Introduction to C++ Variable Declaration Display Messages on Screen Get Information from User Performed.
Classes. COMP104 Lecture 25 / Slide 2 Motivation  Types such as int, double, and char are simple objects. * They can only answer one question: “What.
Classes. COMP104 Class / Slide 2 Motivation  Types such as int, double, and char are “stupid” objects. * They can only answer one question: “What value.
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.
Review of pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
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)
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Chapter 11: Classes and Data Abstraction
1 Introduction to C++ Programming Concept Basic C++ C++ Extension from C.
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.
1 Building Classes (the "++" in C++) (Chapter 14) Representing More Complex Objects.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Structures  2 nd aggregate data type: struct  Recall:
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
Structured Programming Instructor: Prof. K. T. Tsang Lecture 13:Object 物件 Oriented 面向 Programming (OOP)
Defining New Types Lecture 21 Hartmut Kaiser
Introduction To Classes Chapter Procedural And Object Oriented Programming Procedural programming focuses on the process/actions that occur in a.
CHAPTER 13 CLASSES AND DATA ABSTRACTION. In this chapter, you will:  Learn about classes  Learn about private, protected, and public members of a class.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
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.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Chapter 8 Operator Overloading, Friends, and References.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
11 Introduction to Object Oriented Programming (Continued) Cats.
Slide 1 Chapter 8 Operator Overloading, Friends, and References.
Simple Classes. ADTs A specification for a real world data item –defines types and valid ranges –defines valid operations on the data. Specification is.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved More about.
Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private: //...
1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Copyright © 2002 W. A. Tucker1 Chapter 10 Lecture Notes Bill Tucker Austin Community College COSC 1315.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
EGR 2261 Unit 11 Classes and Data Abstraction  Read Malik, Chapter 10.  Homework #11 and Lab #11 due next week.  Quiz next week.
Chapter 11 Friends and Overloaded Operators. Introduction to function equal // Date.h #ifndef _DATE_H_ #define _DATE_H_ class CDate { public: CDate();
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?
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
CSC 143A 1 CSC 143 Introduction to C++ [Appendix A]
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 05: Classes and Data Abstraction.
Slide 1 Chapter 6 Structures and Classes. Slide 2 Learning Objectives  Structures  Structure types  Structures as function arguments  Initializing.
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.
11 Introduction to Object Oriented Programming (Continued) Cats.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Constructors, Copy Constructors, constructor overloading, function overloading Lecture 04.
1 Introduction to Object Oriented Programming Chapter 10.
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Structure A Data structure is a collection of variable which can be same or different types. You can refer to a structure as a single variable, and to.
Slide 1 Chapter 9 Strings. Slide 2 Learning Objectives  An Array Type for Strings  C-Strings  Character Manipulation Tools  Character I/O  get, put.
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.
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,
CSIS 123A Lecture 1 Intro To Classes Glenn Stevenson CSIS 113A MSJC.
Structures and Classes
Classes C++ representation of an object
Visit for more Learning Resources
Student Book An Introduction
CMPE Data Structures and Algorithms in C++ February 22 Class Meeting
Operator Overloading
Classes and OOP.
Java Programming Language
Classes C++ representation of an object
Presentation transcript:

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, user-defined types : classes Motivation Variables  objects Types  classes

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

Motivation We want to build user-defined (and “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 Celsius.” What is your wish?

Temperature example * Write a program that, given a temperature in Fahrenheit or Celsius, 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;

(remember that an Array is a collection of variables of same type) The simpliest Class (or a C-structure) can be thought of being a collection of variables of different types Put related variables together … structure Temperature { double degree; char scale; };

A first simple ‘class’ or ‘object-oriented’ solution class Temperature { public: double degree; char scale; }; a new (user-defined) type, a composite type: Temperature! Two member variables: degree and scale In old C, this can be done using ‘structure’: structure Temperature { double degree; char scale; }; similar to ‘record’ in Pascal Remark:

temp1.degree=54.0; temp1.scale=‘F’; temp2.degree=104.5; temp2.scale=‘C’; The dot operator for (public) members Temperature temp1, temp2; The modifier ‘public’ means that the member variables can be accessed from the objects, e.g. A C++ struct is a class in which all members are by default public.

void print(Temperature temp) { cout << “The temperature is degree “ << temp.degree << “with the scale “ << temp.scale << endl; } double celsius(Temperature temp) { double cel; if (temp.scale==‘F’) cel=(temp.degree-32.0)/1.8; else cel=temp.degree; return cel; } double fahrenheit(Temperature temp) { double fa; if(temp.scale==‘C’) fa= temp.degree * ; else fa=temp.degree; return fa; } Some basic operations: Manipulation of the new type:

An application example: double annualAverageCelsius(Temperature arraytemp[]) { double av=0.0; for (int i=0;i<12;i++) av=av+celsius(arraytemp[i]); return av; }; Temperature annualtemp[12];

Put the variables and functions together … Actual problem: 1. Member ‘variables’ are still separated from ‘functions’ manipulating these variables. 2. However, ‘functions’ are intrinsically related to the ‘type’. A more advanced class is a collection of (member) variables and (member) functions The simplest class (or a C-structure) defined this way is a collection of (member) variables (similar to RECORD in Pascal) “The art of programming is the art of organising complextity.”

Assembly the data and operations together into a class! class Temperature{ public: void print(); // member functions double celsius(); double fahrenheit(); double degree; // member variables char scale; }; An improved Temperature class with member functions associated

Operators for members The dot operator not only for public member variables of an object, but also for public member functions (during usage), e.g. Temperature temp1; temp1.celsius(); temp1.print(); 1. Temp1 receives print() message and displays values stored in degree and scale, receives celsius() message to give the temperature in celsius … 3. The temperature are ‘smart objects’ unlike ‘stupid’ basic type objects Comments: 2. It is not the function which is calling the object like print(temp1) traditionally, temp1.print()  object oriented! function  method Function(procedure) call  message

double Temperature::celsius() { double cel; If (scale==‘F’) cel= (degree-32.0)/1.8; else cel=degree; return cel; } :: for member functions of a class (during definition) Operators for defining member functions :: is used with a class name while dot operator is with an object! From the class, not from an object Full name of the function

Using ‘private’ modifier! l Using private member variables for data protection and information hiding l Using member functions to access the private data instead l Try to make functions ‘public’ l Try to make data ‘private’ ‘private’ members can only be used by member functions, nothing else!

New version of Temperature class class Temperature{ public: // member functions void print(); double celsius(); double fahrenheit(); private: // member variables double degree; char scale; };

double Temperature::celsius() { double cel; If (scale==‘F’) cel= (degree-32.0)/1.8; else cel=degree; return cel; } OK it can not be accessed directly by using temp1.degree ! When the datum ‘degree’ is private, Possible only when ‘degree’ is public Private member variables can only be accessed by ‘member functions’ of the same class.

Other functions (not of the class) use ‘member functions’ of the class The member functions use the ‘private’ member data Private data Member functions Other functions

class Temperature{ public: // member functions double getDegree(); char getScale(); void set(double newDegree, char newScale); void print(); double celsius(); double fahrenheit(); private: // member variables double degree; char scale; }; Using member functions to (indirectly) access private data

double Temprature::getDegree() { return degree; } double Temprature::getScale() { return scale; } double Temprature::set(double d, char s) { degree = d; scale = s; } Some member functions on private data:

(Temporary) Summary: l A collection of member variables and member functions is a Class l Struct is a class with only member variables, and all of them public l ‘public’ member can be used outside by dot operator l ‘private’ member can only be used by member functions l Dot operator for objects and Scope resolution operator :: for class

class A { public: void f(); int x; private: int y; } void A::f() { x=10; y=100; } int main() { A a; a.f(); cout << a.x << endl; cout << a.y << endl; // no!!! a.x = 1000; a.y = 10000; // no!!! }

Some basic member functions: l Constructors for initialization l Access for accessing member variables l Update for modifying data l I/O and utility functions … The other (application) functions should be built on these member functions! Classification of member functions:

A more complete definition 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; double fahrenheit(); double celsius(); private: double degree; char scale; }; A complete class should have a complete set of basic member functions manipulating the class objects Protection of data: ‘const’ modifier

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

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. Remarks on ‘constructor’:

Explicit-Value Constructor Temperature::Temperature(double d, char s) { degree = d; scale = toupper(s); } An explicit-value constructor initializes the data members when a Temperature object is declared with parameters: Temperature temp3(98.6, 'F'); Constructor is ‘overloaded’, the same name but different arguments. int a=10;  int a(10);

Data access (inspector) Functions double Temperature::getDegree( ) const { return degree; } char Temperature::getScale( ) const { return scale; } A data access function allows programmers to read (but not modify) data members of the class. double d = temp1.getDegree(); char s = temp1.getScale();

Update (mutator) Functions void Temperature::set(double d, char s){ degree = d; scale = toupper(s); if(scale!='C' && scale!='F'){ cout << "Bad Temperature scale: " << scale << endl; exit(1); } An update function modifies data members of the class. temp1.set(32, 'F');

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

Conversion functions double Temperature::fahrenheit(){ double fa; if(scale == 'C') fa = degree* ; else fa = degree; return fa; } The member function fahrenheit() gives the degree and scale in Fahrenheit.  Using the fahrenheit() member function: Temperature temp1;// default value: 0 C cout << temp1.Fahrenheit();  When temp1 receives the fahrenheit() message, it gets the Fahrenheit temperature 32 F.

void Temperature::celsius(){ double cel; if(scale == 'F') cel = (degree-32.0)/1.8; else cel = degree; return cel; } The member functions celsius()

#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() << “Fahrenheit” << endl; cout << temp.celsius() << “Celsius” << endl; cout << endl << endl; cout << "Another temperature to convert? "; cin >> resp; }while(resp == 'y' || resp == 'Y'); } Application of Temperature class

‘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 display the degrees and scale to the user

Member functions or normal functions * It’s a question of style and taste for OOP * Keep member functions as a small set