Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Using Member Functions and Data Members.

Slides:



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

This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Classes & Objects classes member data and member function access control and data hiding instantiation of objects class constructor and destructor objects.
1 Classes with Pointer Data Members (II) Ying Wu Electrical Engineering & Computer Science Northwestern University EECS 230.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 6 Functions.
More on Operator Overloading CS-2303, C-Term More on Operator Overloading CS-2303 System Programming Concepts (Slides include materials from The.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Linked List and Namespace ~ include dynamic objects.
OOP Spring 2006 – Recitation 31 Object Oriented Programming Spring 2006 Recitation 3.
Computer Science 1620 Reference Parameters. Parameters – Pass by Value recall that the parameter of a function is assigned the value of its corresponding.
CS 117 Spring 2002 Review for Exam 3 arrays strings files classes.
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
CSE 332: C++ Overloading Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Chapter 9 Defining New Types. Objectives Explore the use of member functions when creating a struct. Introduce some of the concepts behind object-oriented.
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
CSE 232: C++ pointers, arrays, and references Overview of References and Pointers Often need to refer to another object –Without making a copy of the object.
Case Study - Fractions Timothy Budd Oregon State University.
CSC 107 – Programming For Science. Today’s Goal  Discuss how to hand data to functions  Review loopholes in variables & scoping rules  Ways to get.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
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 Advanced Issues on Classes Part 3 Reference variables (Tapestry pp.581, Horton 176 – 178) Const-reference variables (Horton 176 – 178) object sharing:
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Operator Overloading Operator Overloading allows a programmer to define new uses of the existing C/C++ operator symbols. –useful for defining common operations.
Overloading Operator MySting Example. Operator Overloading 1+2 Matrix M 1 + M 2 Using traditional operators with user-defined objects More convenient.
CPSC 252 Operator Overloading and Convert Constructors Page 1 Operator overloading We would like to assign an element to a vector or retrieve an element.
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.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved More about.
Review of Last Lecture. What we have learned last lecture? What does a constructor do? What is the way to define a constructor? Can it be defined under.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
C++ Lecture 5 Monday, 18 July Chapter 7 Classes, continued l const objects and const member functions l Composition: objects as members of classes.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
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?
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Today: –Review declaration, implementation, simple class structure. –Add an exception class and show.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
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.
Pointer. lvalues In C++, any expression that refers to an internal memory location is called an lvalue Appear on left side of assignment statement e.g.
1 2/2/05CS250 Introduction to Computer Science II Pointers.
Classes - Part II (revisited) n Constant objects and member functions n Definition Form of Member Functions n friend functions and friend classes n Constructors.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
Introduction to Classes in C++ Instructor - Andrew S. O’Fallon CptS 122 Washington State University.
Chapter 6 Functions. 6-2 Topics 6.1 Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes 6.4 Sending Data into a Function 6.5.
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
CS 342: C++ Overloading Copyright © 2004 Dept. of Computer Science and Engineering, Washington University Overview of C++ Overloading Overloading occurs.
C++ Functions A bit of review (things we’ve covered so far)
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
C++ Features Function Overloading Default Functions arguments Thinking about objects – relationship to classes Types of member functions Constructor and.
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?
Overloading Operator MySting Example
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
CMSC202 Computer Science II for Majors Lecture 08 – Overloaded Constructors Dr. Katherine Gibson Based on slides by Chris Marron at UMBC.
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?
Pointer.
Overview of C++ Overloading
COP 3330 Object-oriented Programming in C++
Data Structures and Algorithms Introduction to Pointers
Pointers and dynamic objects
A Deeper Look at Classes
CS 144 Advanced C++ Programming February 21 Class Meeting
Class rational part2.
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
(4 – 2) Introduction to Classes in C++
Presentation transcript:

Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Using Member Functions and Data Members

2 Overview  Accessing member functions  Inspector Function (Accessor)  Mutator Function  Function Overloading  Friend Functions/Class  Static Member Functions  Static Data Member  Data Sharing - extern  Changing Constant Objects - mutable

3 Accessing member functions  Use member access operator (.) Word vowel(“a”, 12); vowel.addfreq(3);// call a member function // in Word class  Use dereference member access operator (->) // a pointer to a Word object Word* boy = new Word(“boy”, 2); vowel->addfreq(1); It is equal to a deference operator plus a member access operator, i.e. (*boy).addfreq(1);

4 Inspector Function (Accessor)  An inspector function allows programmers to read (but not modify) data members of the class.  It has another name called “ accessor ” or “ gettor ”.  Usually it has a “ get ” as prefix and declared as a constant function. int Word::getfreq() const { return frequency; } char* Word::getword() const { if (str != NULL) { char *temp = new char [strlen(str)+1]; strcpy(temp, str); return temp; } else { return NULL; } }

5 Mutator Function  A mutator function (or called “ settor ” ) modifies data members of the class.  Usually it has a “ set ” as prefix.  You can use “ const ” and pass-by-reference(&) to avoid unnecessary copying and prevent accidental change of parameter content. int Word::setfreq(const int& new_freq) { frequency = new_freq; return frequency;// return the new frequency // but it is not necessary, // you can use “void” instead }

6 Function Overloading  We can define a few functions using the same name with different kinds of argument.  That will increase the usability of your class. E.g. void Word::setword(const char* new_word) { … } void Word::setword(const string& new_word) { … }  Both of them has the name “setword” but accept different argument. User can use “char*” or “string” in this function.

7 Function Overloading  When overloading functions, we have to pay attention to their signature.  A function’s signature includes its parameter list and const-ness of function (except its return type), i.e. int Word::addfreq(int amount); int Word::addfreq(float amount); int Word::addfreq(int amount) const;  All of the above are valid overloaded functions. Be careful, const function and non-const function are considered different. (1 st and 3 rd example)

8 Friend Functions/Class  A friend function of a class is an ordinary (nonmember) function except that it has access to the private members of the objects.  We usually place friend function prototypes in the “public” section.  General guidelines: Use a nonmember/friend function only if the task being performed involves multiple objects. Whether an ordinary nonmember function or a friend function should be used is a matter of efficiency and personal taste.

9 Friend Functions/Class void print_date(const Date& today, const Clock& time) { cout << today.day << “-” << today.month << “-” << today.year; cout << “ “ << time.hour << “:” << time.minute << endl; }  To let the above function work, we can put its prototype to both Date and Clock class. class Date { public: friend void print_date(const Date&, const Clock&); … }; // class Clock is similar

10 Friend Function/Class  Friend class is similar to friend functions. You can put the declare of a class as friend class in another class.  Usually when a class is controlled by another class, it will let the controller class to touch its private members, e.g. In a linked-list, the Node class can friend the List class to let it touch its data. class Node { public: friend class List; … };  One important thing: If you friend a class, that class can access all your private data, but not in reverse.

11 Static Member Functions  For example, we have a clock class like this, class Clock { private: int hour, minute; public: Clock(int h = 0, int m = 0) : hour(h), minute(m) { } void tick(); void print(); }; // Global functions that will call the clock constructor Clock make_clock_hhmm(int hhmm) { return Clock(hhmm/100, hhmm%100); } Clock make_clock_minutes(int min) { return Clock(min/60, min%60); }

12 Static Member Functions  In order to let user have two ways to create a clock (in hhmm or in minutes, both are int type), we created two global functions to help our user.  It seems good, but it has some drawbacks, They are not belong to class, so it is easy to forget them when we update the codes in the class. They are global functions, so they can’t access private data of a class. (or we can use friend functions.)

13 Static Member Functions  A better solution is to use static member functions. class Clock { … public: static Clock HHMM(int hhmm) {…} static Clock minutes(int i) {…} };  Static methods of a class are really global functions with a “funnyname”. They belong to the class, and can access private data. NO object is required to invoke them, they exist whenever the class exists.

14 Static Member Functions class Clock { private: int hour, minute; Clock(int h, int m) : hour(h), minute(m) { } public: Clock() : hour(0), minute(0) { } void tick(); void print(); static Clock HHMM(int hhmm) { return Clock(hhmm/100, hhmm%100); } static Clock minutes(int i) { return Clock(i/60, i%60); } }; // Now we can set clocks Clock c1; // 0:00 Clock c2 = Clock::HHMM(120);// 1:20 Clock c3 = Clock::minutes(120); // 2:00

15 Static Data Member  Classes can also have static data members.  Static data members are really global variables with a funny name.  They also follow access control (public and private), just like normal variables. class Car { private: static int num_cars; // count total number of // Car objects produced int total_km; public: Car():total_km(0) { ++num cars; } ~Car() { --num cars; } static int cars_produced() { return num_cars; } };

16 Static Data Member #include "car.h" int Car::num cars = 0; // definition of static member int main() { cout << Car::cars_produced() << endl; // prints 0 Car vw; Car bmw; cout << Car::cars_produced() << endl; // prints 2 return 0; } /* It can count the number of objects produced. But remember, if you don’t provide your own copy constructor and assignment operator(=), the counting will be wrong. Because the default copy constructor don’t know how to count objects. */

17 Static Data Member  Static variables are shared among all objects of the same class.  They do not take up space inside an object.  Static variables, though act like global variables, cannot be initialized in the class definition. Instead, they must be defined outside the class definition.  Usually the definitions of static variables are put in the class implementation (.cpp) file.

18 Static Data Member  Static member functions can only use static data members of the class. Because static methods do not have the implicit this pointer like regular member functions, e.g.  A regular member function of Car like void drive(int km) { total_km += km; } after compilation becomes: void Car::drive( Car* this, int km){ this->total_km+=km; }  On the other hand, a static method of Car like static int cars_produced() { return num_cars; } after compilation becomes: int Car::cars_produced() { return num_cars; }

19 Data Sharing - extern  Extern means a variable (or function) has an external linkage with a variable (or function) in another file.  External variable declaration: extern int global_var;  External function declaration extern void reverse_print(const char* s);  The above two are declaration only, they are not the real variable. They don’t have memories assigned.  The actual variable (or function) is defined in another file.

20 Data Sharing - extern // main.cpp extern int global_var; extern void rev_print(const char* s); int main(int argc, const char* argv[]) { cout << “global var = “ << global_var << endl; cout << “input string backwards = “; rev_print(argv[1]); } // Output: // global var = 23 // input string backwards = … // otherfile.cpp // compile it with main.cpp int global_var = 23; void rev_print( const char* s){ for (int j = strlen(s)-1; j >= 0; --j) { cout<< s[j]; } cout<< endl; } // Actual variables and functions // are defined here

21 Changing Constant Objects - mutable  The concept is easy: when a variable is declared as mutable, its content can be changed even if the object is a constant. class Word { public: char* str; mutable int frequency; // can be changed }; const Word movie(“Superman”, 0);// const object movie.frequency += 1;//it is ok