Classes and OOP.

Slides:



Advertisements
Similar presentations
Object-Oriented Programming and Classes. OOP / Slide 2 Basic, built-in, pre-defined types : char, int, double, … Variables + operations on them int a,
Advertisements

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.
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,
Review of pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
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.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
Defining New Types Lecture 21 Hartmut Kaiser
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.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review Part-I.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
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.
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.
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?
Slide 1 Chapter 6 Structures and Classes. Slide 2 Learning Objectives  Structures  Structure types  Structures as function arguments  Initializing.
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:
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.
Mr H Kandjimi 2016/01/03Mr Kandjimi1 Week 3 –Modularity in C++
C++ Features Function Overloading Default Functions arguments Thinking about objects – relationship to classes Types of member functions Constructor and.
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.
COMP 53 – Week Two Operator Overloading.
EGR 2261 Unit 13 Classes Read Malik, Chapter 10.
Structures and Classes
Procedural and Object-Oriented Programming
Chapter Topics The Basics of a C++ Program Data Types
Classes C++ representation of an object
Visit for more Learning Resources
Class and Objects UNIT II.
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?
C++ Templates.
Programming with ANSI C ++
10.2 Classes Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 1.
Basic Elements of C++.
Why exception handling in C++?
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 5 Classes.
Student Book An Introduction
CMPE Data Structures and Algorithms in C++ February 22 Class Meeting
Basic Elements of C++ Chapter 2.
Lecture 4-7 Classes and Objects
Operator Overloading
Classes and Data Abstraction
FUNCTIONS& FUNCTIONS OVERLOADING
Learning Objectives Classes Constructors Principles of OOP
Classes Short Review of Topics already covered Constructor
Object Oriented Programming Using C++
Operator Overloading, Friends, and References
UNIT I OBJECT ORIENTED PROGRAMMING FUNDAMENTALS
CPS120: Introduction to Computer Science
COP 3330 Object-oriented Programming in C++
Life is Full of Alternatives
Java Programming Language
CS410 – Software Engineering Lecture #5: C++ Basics III
C++ Programming Basics
Classes C++ representation of an object
Chapter 9 Introduction To Classes
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Lecture 2 – Abstract Data Type (ADT)
Presentation transcript:

Classes and OOP

Motivation 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 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?”

Motivation We want to build user-defined (and “smart”) objects that can answer many questions (and perform various actions). “What is your temperature?” “What is your temperature in Fahrenheit?” “What is your humidity?” “Print your temperature in Celsius.”

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;

Put related variables together … (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 structure Temperature { double degree; char scale; };

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

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

Manipulation of the new type: Some basic operations: 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 *1.8+32.0; else fa=temp.degree; return fa;

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

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’. The simplest class (or a C-structure) defined this way is a collection of (member) variables (similar to RECORD in Pascal) A more advanced class is a collection of (member) variables and (member) functions “The art of programming is the art of organising complextity.”

An improved Temperature class with member functions associated 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; };

Operators for members, object-oriented 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(); function  method Function(procedure) call  message Comments: 1. Temp1 receives print() message and displays values stored in degree and scale, receives celsius() message to give the temperature in celsius … 2. It is not the function which is calling the object like print(temp1) traditionally, temp1.print()  object oriented! 3. The temperature are ‘smart objects’  unlike ‘stupid’ basic type objects

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

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

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

When the datum ‘degree’ is private, it can not be accessed directly by using temp1.degree! double Temperature::celsius() { double cel; If (scale==‘F’) cel= (degree-32.0)/1.8; else cel=degree; return cel; } Possible only when ‘degree’ is public OK 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 Other functions Member functions Private data

Using member functions to (indirectly) access private data 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; };

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

(Temporary) Summary: A collection of member variables and member functions is a Class Struct is a class with only member variables, and all of them public ‘public’ member can be used outside by dot operator ‘private’ member can only be used by member functions 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: Classification of member functions: Constructors for initialization Access for accessing member variables Update for modifying data I/O and utility functions … The other (application) functions should be built on these member functions!

A more complete definition A complete class should have a complete set of basic member functions manipulating the class objects 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; }; Protection of data: ‘const’ modifier

Accessors: constant member functions: double Temprature::getDegree() const { return degree; } double Temprature::getScale() const { return scale; } By default, all member functions are mutators. To make an accessor, add ‘const’.

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;

Remarks on ‘constructor’: Constructor functions have no return type (not even void!). Because a constructor function initializes the data members, there is no const following its heading. The constructor function is automatically called whenever a Temperature class object is declared.

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 concept of overloading will be further discussed in 151 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*1.8+32.0; 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.

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

Application of Temperature class #include <iostream> 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'); }

‘Smart’ Temperature Object A smart object should carry within itself the ability to perform its operations Operations of Temperature object : initialize degree and scale with default values read a temperature from the user and store it compute the corresponding Fahrenheit temperature compute the corresponding Celsius temperature 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

over-loaded constructors An even better one … class Temperature{ public: Temperature(); Temperature(double idegree, char iscale); double getDegree() const; char getScale() const; void print() const; double fahrenheit() const; double celsius() const; void set(double newDegree, char newScale); void read(); private: double degree; char scale; }; over-loaded constructors ‘const’ accessors mutators data variables