Object Oriented Programming COP3330 / CGS5409

Similar documents
Determine a word is a palindrome? bool ispalindrome(string word, int front, int back) { Search if a number is in an array

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Object Oriented Programming COP3330 / CGS5409

And Even More and More C++ Fundamentals of Computer Science

Special Member Functions

Midterm Exam #2 Review. CS 2308 :: Spring 2016 Molly O'Neil

Constructors and Destructors. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Dynamic memory in class Ch 9, 11.4, 13.1 & Appendix F

Special Member Functions. Compiler-Generated Destructor. Compiler-Generated Default Constructor. Special Member Functions

Programming in C ++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Dynamic Memory Allocation

Object-Oriented Programming

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

Object-Oriented Principles and Practice / C++

CS32 - Week 1. Umut Oztok. June 24, Umut Oztok CS32 - Week 1

Object Oriented Programming COP3330 / CGS5409

Chapter 10 Introduction to Classes

Implementing Abstractions

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming

Constructors.

Launchpad Lecture -10

CPSC 427: Object-Oriented Programming

Exam 3 Chapters 7 & 9

More class design with C++ Starting Savitch Chap. 11

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I

(5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University

An Introduction to C++

THE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~) BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF THE CLASS IN WHICH THEY ARE DECLARED.

04-19 Discussion Notes

CSCI 262 Data Structures. The Big 3. Copy Constructor. Destructor. Assignment Operator 3/4/ The Big 3

Lecture 18 Tao Wang 1

Assignment of Structs

Object-Oriented Principles and Practice / C++

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Operator overloading. Conversions. friend. inline

Name: Username: I. 10. Section: II. p p p III. p p p p Total 100. CMSC 202 Section 06 Fall 2015

Assignment operator string class c++ Assignment operator string class c++.zip

More About Classes. Gaddis Ch. 14, CS 2308 :: Fall 2015 Molly O'Neil

Intermediate Programming & Design (C++) Classes in C++

Copying Data. Contents. Steven J. Zeil. November 13, Destructors 2

CS304 Object Oriented Programming Final Term

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

Object-Oriented Principles and Practice / C++

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved.

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

Initializing and Finalizing Objects

CGS 2405 Advanced Programming with C++ Course Justification

Programming, numerics and optimization

Classes and Objects. Class scope: - private members are only accessible by the class methods.

Introduction Of Classes ( OOPS )

explicit class and default definitions revision of SC22/WG21/N1582 =

CSC1322 Object-Oriented Programming Concepts

Assignment of Objects

Separate Compilation Model

Class Vector: Interface CSE 143. Dynamic Memory In Classes [Chapter 4, p ] Vector Implementation. Many Ways to Implement. Draw the picture!

Review: C++ Basic Concepts. Dr. Yingwu Zhu

CSCI 123 Introduction to Programming Concepts in C++

Assignment 1: grid. Due November 20, 11:59 PM Introduction

Chapter 13: Copy Control. Overview. Overview. Overview

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

C++ (classes) Hwansoo Han

nptr = new int; // assigns valid address_of_int value to nptr std::cin >> n; // assigns valid int value to n

Outline. Dynamic Memory Classes Dynamic Memory Errors In-class Work. 1 Chapter 10: C++ Dynamic Memory

Object Oriented Design

Vectors of Pointers to Objects. Vectors of Objects. Vectors of unique ptrs C++11. Arrays of Objects

Short Notes of CS201

CS201 Some Important Definitions

CPSC 427: Object-Oriented Programming

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

IS0020 Program Design and Software Tools Midterm, Fall, 2004

CS201 - Introduction to Programming Glossary By

Name: Username: I. 20. Section: II. p p p III. p p p p Total 100. CMSC 202 Section 06 Fall 2015

Iterator: A way to sequentially access ( traverse ) each object in a container or collection. - Access is done as needed, not necessarily at once.

CLASSES AND OBJECTS. Summer 2018

CSE 333. Lecture 11 - constructor insanity. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

Written by John Bell for CS 342, Spring 2018

Next week s homework. Classes: Member functions. Member functions: Methods. Objects : Reminder. Objects : Reminder 3/6/2017

Classes in C++98 and C++11

C++ Basic Syntax. Constructors and destructors. Wojciech Frohmberg / OOP Laboratory. Poznan University of Technology

CSCI-1200 Data Structures Spring 2018 Lecture 8 Templated Classes & Vector Implementation

EL2310 Scientific Programming

Concepts (this lecture) CSC 143. Classes with Dynamically Allocated Data. List of ints w/dups (cont.) Example: List of ints with dups.

Classes: Member functions // classes example #include <iostream> using namespace std; Objects : Reminder. Member functions: Methods.

Recharge (int, int, int); //constructor declared void disply();

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

CSI33 Data Structures

A brief introduction to C++

Course Text. Course Description. Course Objectives. StraighterLine Introduction to Programming in C++

C++ 8. Constructors and Destructors

Classes - 2. Data Processing Course, I. Hrivnacova, IPN Orsay

Constructors for classes

Pointers Ch 9, 11.3 & 13.1

Advanced Systems Programming

... IntArray B (100); // IntArray with 100 elements, each initialized to 0

CMSC 132: Object-Oriented Programming II

struct Properties C struct Types

Programming in C and C++

Constructor - example

Transcription:

Object Oriented Programming COP3330 / CGS5409

C++ Automatics Copy constructor () Assignment operator = Shallow copy vs. Deep copy DMA Review c-strings vs. concept of string class

Constructor Destructor Copy Constructor Assignment operator = if you do not explicitly define one in a class, a default version will automatically be built for you by the compiler

The automatic versions of the constructor and destructor don't do anything, but they will be there if you do not build them. The constructor you get is the "default constructor" -- no parameters The automatic versions of the Copy Constructor and the Assignment operator overload are similar to each other, and their default versions are always built in a standard way.

A copy constructor IS a constructor, so it is a function with the same name as the class and no return type (just like any constructor). However, it is invoked implicitly when something is done that causes a COPY of an existing object to be created. This happens when: An object is defined to have the value of another object of the same type An object is passed by value into a function An object is returned (by value) from a function

Here's an example of item #1 in the above list: Fraction f1, f2(3,4); // declaration of two //fractions Fraction f3 = f2; // declaration of f3 being // initialized as a copy of f2 Note: This last line of code calls the copy constructor, since the initialization is on the same line as the declaration of f3. Contrast this with the following: f1 = f2; // this uses the assignment // operator, since f1 and f2 already exist

Since the purpose of a copy constructor is to not only initialize the data in an object, but to initialize it as a copy of another existing object, the original object must be passed in as a parameter. So, a copy constructor always has one parameter, which is of the same type as the class itself. It is always passed by reference, as well (it has to be - - since to pass by value, we must invoke a copy constructor, and this is what we are defining!) Format: classname(const classname &);

The const is not required, but it is usally a good idea, because we only want to make a copy -- we don't want to change the original. Here are some examples of copy constructor declarations for classes we have seen: Fraction(const Fraction & f); Timer(const Timer & t); Directory(const Directory & d); Store(const Store & s);

The default version of the copy constructor (created by the compiler) makes what is known as a shallow copy. This simply means that the object is copied exactly as is -- each member data value is copied exactly over to the corresponding member data location in the new object. This is sufficient for many cases, but not for ALL cases.

Example: Fraction f1(3,4); This fraction object has a numerator of 3 and a denominator of 4. If this object is passed into a function by value, a copy will be made, and the new object's numerator will be 3, denominator 4. In this case, the shallow copy is sufficient.

Consider, however, the Directory class of the phone book example. The member data variables were currentsize and maxsize (both of type int), and a pointer, entrylist (of type Entry * ), which pointed to dynamically allocated data outside the actual object. This is the situation in which a shallow copy is not sufficient.! For instance, if the original object is storing the address 1024 in entrylist, the copy will also get the 1024, and therefore the copy will be pointing to the original dynamic data!

This will especially pose problems if, when the copy goes out of scope, it cleans up the dynamic data along with it. When there is a pointer (inside an object) that points to dynamic data, the shallow copy is not sufficient, because it does not copy the dynamic data, only the pointer. A deep copy is needed. The following slide is what we might write for a copy constructor definition in the Directory class (from the phonebook database example):

Directory::Directory(const Directory & d) // copies object 'd' into the new object being created (this one) { // copy the static variables normally maxsize = d.maxsize; currentsize = d.currentsize; // create a new dynamic array for the // new object's pointer entrylist = new Entry[d.maxsize]; // copy the dynamic data } for (int i = 0; i < currentsize; i++) entrylist[i] = d.entrylist[i];

The assignment operator = is similar to the copy constructor. It is called when one object is assigned to another. Example call: Fraction f1, f2; f1 = f2; // this call invokes the //assignment operator Like the copy constructor, the assignment operator has to make a copy of an object. The default version makes a shallow copy. If a deep copy is desired for assignments on a user-defined type (e.g. a class), then the assignment operator should be overloaded for the class. The task done by the assignment operator is very similar to that of a copy constructor, but there are a couple of differences.

The copy constructor is initializing a brand new object as a copy of an existing one. The new object's data is being initialized for the first time. An assignment operator sets an existing object's state to that of another existing object. In situations with dynamic allocation, this may mean that old dynamic space must be cleaned up first before the copy is made. Also, an assignment operator also returns the value that was assigned (the copy constructor has no return). Consider the case of integers. In the statement: a = b = c = 4; The first operation is (c = 4), and this operation returns the assigned value (4), so that the result can be used as an operand in the next assignment (b = 4). This value should be returned by reference when overloading = for objects. To return the object, we need to be able to refer to an object from inside the object itself.

From inside any member function, an object has access to its own address through a pointer called this, which is a keyword in C++. In an assignment operator, you must return the object itself (by reference), so you can return the target of the this pointer (which would be *this) Like the copy constructor, the original object needs to be passed in, so there will be one parameter (of the same type as the object itself). The parameter is the same as in the copy constructor. Declaration examples for a few classes: Directory& operator= (const Directory &); Fraction& operator=(const Fraction &); Timer& operator=(const Timer &); Circle& operator=(const Circle &);

Directory& Directory::operator=(const Directory & d); // copies object 'd' into the new object being created (this one) { if (this!= &d) // only copy if object passed is not this one { // since this is not a brand new object, we // should delete any information currently attached delete [] entrylist; } // similar to the copy constructor definition maxsize = d.maxsize; currentsize = d.currentsize; entrylist = new Entry[d.maxsize]; for (int i = 0; i < currentsize; i++) entrylist[i] = d.entrylist[i]; } return *this; // return the object itself (by reference)

http://www.cs.fsu.edu/~myers/savitch3c++/ch10/10-10,%20-11,%20-12/chapter%2011%20version/ This example shows a class called PFArrayD, which is declared in the file "pfarrayd.h" and defined in "pfarrayd.cpp". This class stores a list of values of type double -- the list is stored using a dynamically allocated array, so there is no size limit. There are tracking variables in the member data for keeping track of the allocated space and the used space. The class also has a copy constructor and assignment operator -- both of them to do the "deep copy". And of course the destructor cleans up the space. The file "10-12.cpp" contains a main program that demonstrates some of the class features.

http://www.cs.fsu.edu/~myers/savitch3c++/ch10/1 0-10,%20-11,%20-12/Chapter%2011%20Version/ In this particular example, once the capacity of the array is set (when the object is created), it becomes the upper limit of storage for the list. How to use the array resizing technique to add functionality to the class? Specifically, to be able to remove the boundary check in the addelement function, and have no upper limit on the size of the list of values. (This would entail writing a Grow function, or perhaps a more generic "Resize" function -- to allow the allocated space to vary -- then calling it from appropriate places).

http://www.cs.fsu.edu/~myers/deitel5c++/c h11/fig11_17_18/ This is similar to the previous example, involving dynamic allocation inside a class. It is used to build a safer array type -- the class in this one is called Array, and it stores a dynamically created integer array. Both use dynamic memory management, but they vary a little in specific implementation details.

http://www.cs.fsu.edu/~myers/deitel5c++/ch11/fig11_1 7_18/ Some highlights of this example: Dynamic creation of array in the constructor Copy constructor and assignment operator, for deep copy Operator overloads provided (equality comparisons and for I/O) Two subscript operators (the brackets [] ). Note: when bracket operators are provided, the programmer does have the option to provide TWO versions -- one that returns by reference, and one that returns by value or by const reference (and must be a const member function). The difference is that one will return an L-value (storage location that could be modified), and one will return only an R-value (a read-only value).