OOP Spring 2006 – Recitation 31 Object Oriented Programming Spring 2006 Recitation 3.

Slides:



Advertisements
Similar presentations
Chapter 4 Constructors and Destructors. Objectives Constructors – introduction and features The zero-argument constructor Parameterized constructors Creating.
Advertisements

F UNCTION O VERLOADING Chapter 5 Department of CSE, BUET 1.
Object Oriented Programming COP3330 / CGS5409.  C++ Automatics ◦ Copy constructor () ◦ Assignment operator =  Shallow copy vs. Deep copy  DMA Review.
Pointers Revisited l What is variable address, name, value? l What is a pointer? l How is a pointer declared? l What is address-of (reference) and dereference.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
OOP Etgar 2008 – Recitation 51 Object Oriented Programming Etgar 2008 Recitation 5.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
OOP Spring 2007 – Recitation 21 Object Oriented Programming Spring 2007 Recitation 2.
Introduction to Classes and Objects CS-2303, C-Term Introduction to Classes and Objects CS-2303 System Programming Concepts (Slides include materials.
© The McGraw-Hill Companies, 2006 Chapter 7 Implementing classes.
1 Classes and Objects. 2 Outlines Class Definitions and Objects Member Functions Data Members –Get and Set functions –Constructors.
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
Review of C++ Programming Part II Sheng-Fang Huang.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to Classes and Objects Outline Introduction Classes, Objects, Member Functions and Data.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Copy Control Joe Meehean. More Class Responsibilities When making a new type (i.e., class) we must specify what happens when it is: Copied Assigned Destroyed.
Memory Management CS Chakrabarti Variable storage thus far  Never used global variables  All variables allocated inside functions, passed.
The Rest of the Story.  Constructors  Compiler-generated  The Initializer List  Copy Constructors  Single-arg (conversion ctors)  The Assignment.
Chapter 9 Defining New Types. Objectives Explore the use of member functions when creating a struct. Introduce some of the concepts behind object-oriented.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
Copyright  Hannu Laine C++-programming Part 3 Hannu Laine.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
CS212: Object Oriented Analysis and Design Lecture 10: Copy constructor.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
Learners Support Publications Classes and Objects.
Chapter 8 Operator Overloading, Friends, and References.
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.
User Defined Functions Chapter 7 2 Chapter Topics Void Functions Without Parameters Void Functions With Parameters Reference Parameters Value and Reference.
Object Oriented Programming Elhanan Borenstein Lecture #3 copyrights © Elhanan Borenstein.
CSC241 Object-Oriented Programming (OOP) Lecture No. 6.
Slide 1 Chapter 8 Operator Overloading, Friends, and References.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
Chapter 4 Introduction to Classes, Objects, Methods and strings
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:
Object-Based Programming Mostly Review. Objects Review what is object? class? member variables? member functions? public members? private members? friend.
1 Chapter 1 C++ Basics Review Reading: Sections 1.4 and 1.5.
1 CSC241: Object Oriented Programming Lecture No 02.
Object Management. Constructors –Compiler-generated –The Initializer List –Copy Constructors –Single-arg (conversion ctors) The Assignment Operator.
OOP in C++ CS 124. Program Structure C++ Program: collection of files Source (.cpp) files be compiled separately to be linked into an executable Files.
Static. 2 Objectives Introduce static keyword –examine syntax –describe common uses.
C++ Lecture 5 Monday, 18 July Chapter 7 Classes, continued l const objects and const member functions l Composition: objects as members of classes.
Effective C++, 2nd Ed. By Scott Myers. Constructors, Destructors, and Assignment Operators 11.Define a copy constructor and an assignment operator for.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 15 Inheritance.
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
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.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
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.
Chapter 7 Constructors and Other Tools Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Monday, Jan 27, 2003Kate Gregory with material from Deitel and Deitel Week 4 Questions from Last Week Hand in Lab 2 Classes.
CSIS 123A Lecture 7 Static variables, destructors, & namespaces.
Lecture 9 – Array (Part 2) FTMK, UTeM – Sem /2014.
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
C++ Functions A bit of review (things we’ve covered so far)
Chapter 2 Objects and Classes
Pointer to an Object Can define a pointer to an object:
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.
This pointer, Dynamic memory allocation, Constructors and Destructor
CISC/CMPE320 - Prof. McLeod
Introduction to Classes
Dr. Bhargavi Dept of CS CHRIST
COP 3330 Object-oriented Programming in C++
Submitted By : Veenu Saini Lecturer (IT)
COP 3330 Object-oriented Programming in C++
ENERGY 211 / CME 211 Lecture 8 October 8, 2008.
SPL – PS3 C++ Classes.
Presentation transcript:

OOP Spring 2006 – Recitation 31 Object Oriented Programming Spring 2006 Recitation 3

OOP Spring 2006 – Recitation 32 Static Members The Way to Avoid Duplications

OOP Spring 2006 – Recitation 33 Motivation We’ve been hired to write a bank account managing application. Each account has its owner and balance. All accounts bear the same interest rate. How do we “say” in OO language that all objects of class Account bear the same interest (Remembering that global variables are a disadvantage)?

OOP Spring 2006 – Recitation 34 Solution We can declare the _interest member of Account as static. This means that all objects of class Account share one _interest variable, while each object has its own copy of non-static variables. Similar to static function variable, where all function invocations share the same variable.

OOP Spring 2006 – Recitation 35 Account Class class Account { public: Account(string owner, double init_balance); string owner(){ return _owner;} double balance(){ return _balance;} double interest(){ return _interest;} private: string _owner; double _balance; static double _interest; };

OOP Spring 2006 – Recitation 36 Definition The _interest member above is declared, but not defined. Just as we need to define a function, we need to define a static member of a class. It must be defined only once in the program, thus the definition should not be in the header. double Account::_interest; outside of the class is the way to define.

OOP Spring 2006 – Recitation 37 Initialization We can specify an initial value for a static variable: double Account::_interest = 1.12; If the value is not specified, the value is zero (more precisely, the memory belonging to the variable is zeroed out).

OOP Spring 2006 – Recitation 38 Accessing Static Members Member functions access static member just as any other member: double Account::interest() { return _interest; } Two ways to access from outside: –Using. and -> member access operators: cout << a1._interest; –Using :: scope operator: cout << Account::_interest; –(had _interest been declared public and a1 was an Account object)

OOP Spring 2006 – Recitation 39 Static Methods If a method doesn’t use non- static members, why should each object carry a copy of it? The behavior is the same across all objects of that class. Such method can be declared static too. interest() above is a good candidate.

OOP Spring 2006 – Recitation 310 Declaration and Definition To make a method static, add keyword static before its declaration in the class. Definition is the same as for non-static methods (do not add static in definition). A static method cannot access non- static members and methods.

OOP Spring 2006 – Recitation 311 Accessing Static Methods The access is similar to static members: –Through. and -> member access operators: cout << a1.interest(); –Through :: scope operator: cout << Account::interest();

OOP Spring 2006 – Recitation 412 The Implicit this

OOP Spring 2006 – Recitation 413 The Implicit this Sometimes we need to address the “whole object” inside a member function (for example, in a copy() method to check against self-assignment). Member functions actually have an implicit parameter (of the class’s type) – the this pointer. this points to the actual object “called”.

OOP Spring 2006 – Recitation 414 A copy() Method class Car { public: // other methods… void copy(const Car& rhs); private: // other data members… int _color; }; void Car::copy(const Car& rhs) { if (this == &rhs) { return; } _color = rhs._color; // _color this->_color }

OOP Spring 2006 – Recitation 415 this Come From… The compiler “rewrites” method fingerprints (and calls) to accept another parameter: –A method fingerprint will “look” like: // void Car::copy(Car *this, const Car& rhs); –A method call will “look” like: // Car c1, c2; // Car::copy(&c1, c2); The type of this in previous example is Car *. If the variable is const, its type is const Car *.

OOP Spring 2006 – Recitation 416 Constants

OOP Spring 2006 – Recitation 417 Constant Values Sometimes we need to use values that cannot be changed, i.e. constant values: –Arrays sizes ( int buffer[MAX_LEN] ) –Numeric constants ( double pi = ) C++ provides the const qualifier to declare that a variable’s value cannot be changed. The compiler then checks to see that it is really never changed.

OOP Spring 2006 – Recitation 418 A const Variable const variables must always be initialized. A const variable is used the same way a normal variable is, but it cannot be assigned to: const int i = 5; i = 10; // error, i is const const variable can also be used as an array size (instead of C’s #define ). Pointers and references can be const too.

OOP Spring 2006 – Recitation 419 const Pointers char greeting[] = "Hello"; char *p = greeting;// non-const pointer, // non-const data const char *p = greeting;// non-const pointer, // const data char * const p = greeting;// const pointer, // non-const data const char* const p= greeting;// const pointer, // const data

OOP Spring 2006 – Recitation 420 const References int i= 10; constint& j= i; int& k= i; i= 5;// legal, changes i, j and k j= 0;// error, j is reference to const k= -5;// legal, changes i, j and k

OOP Spring 2006 – Recitation 421 const Members Since any variable can be const, class’s members can too be const. For example, each Car can have a Serial Number, but it should not be changed once the Car is made, hence it’s const. It must be initialized in all constructors.

OOP Spring 2006 – Recitation 422 A Car with Serial Number class Car { public: Car(int serial, int color); int color() { return _color; } private: const int _serial; int _color; }; // Initialization using initialization list Car::Car(int serial, int color) : _serial(serial), _color(color) {}

OOP Spring 2006 – Recitation 423 Initialization List The part after : in Car’s constructor is called initialization list. We can give initial values to data members there instead of the constructor’s body. const and reference data members can only be initialized there. NOTE: List members in the initialization list in the order in which they are declared. static const members are initialized as regular static members.

OOP Spring 2006 – Recitation 424 const Methods Just as any other variable, an object can be const. const Car PM1(001); // Prime-minister's car The method Car::copy() declared earlier would change this object, thus it should not be allowed to execute. The method Car::color() would not change PM1, thus is should be allowed to execute. We need a way to tell which method will change the object, and which will not.

OOP Spring 2006 – Recitation 425 const Method Declaration A const method is one which will not change its object, thus it can be applied to const objects. To make a method const, add const after its name (both in declaration and definition): int Car::color() const; Now Car::color() can be called for PM1. A const method can be applied to non- const objects too (but not the other way).

OOP Spring 2006 – Recitation 526 The Big Three Compiler-generated Methods

OOP Spring 2006 – Recitation 527 Who Are They? Actually, just like the three musketeers that were four – there are four compiler- generated methods. These are –default constructor, –copy constructor, –destructor and –assignment operator.

OOP Spring 2006 – Recitation 528 Class is Never Empty If we write class Empty {}; it is as if we’d written class Empty { public: Empty(); Empty(const Empty&); ~Empty(); Empty& operator=(const Empty& rhs); };

OOP Spring 2006 – Recitation 529 When They Come to Life? They are generated only when needed: void useEmty(Empty e); void func() { Empty e1, e2;// Causes default constructor // to be generated useEmty(e1);// Copy constructor e2 = e1;// Assignment operator }// Destructor

OOP Spring 2006 – Recitation 530 Default Constructor and Destructor The default constructor and destructor are empty. Default constructor is generated only if no other constructor has been defined.

OOP Spring 2006 – Recitation 531 Copy Constructor The default copy constructor initializes each data member with corresponding data member in the given object using corresponding copy constructor. The copy constructor for built-in types ( int, double, void* ) is bitwise copy.

OOP Spring 2006 – Recitation 532 Assignment Operator The default assignment operator initializes each data member with corresponding data member in the given object using corresponding assignment operator. The assignment operator for built-in types ( int, double, void* ) is bitwise copy.

OOP Spring 2006 – Recitation 533 Works, But Not Always The default behavior is not always good. –If the class has a pointer member, the memory where points should be copied in copy constructor and assignment operator, and not the pointer itself. –The memory needs to be deleted in destructor. When the default behavior is not enough, we need to write our own version. We can’t use the default version in our version.

OOP Spring 2006 – Recitation 534 The Rule of Big Three The rule states that If a class needs any of the Big Three (copy constructor, assignment operator, destructor), it needs them all. If we see that we need to do some non- trivial task in any of the Big Three, chances are that we will need to implement all of them.